mac.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package wireguard
  2. import (
  3. "bufio"
  4. "errors"
  5. "os"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/gravitl/netmaker/logger"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/netclient/ncutils"
  12. )
  13. // WgQuickDownMac - bring down mac interface, remove routes, and run post-down commands
  14. func WgQuickDownMac(node *models.Node, iface string) error {
  15. if err := RemoveConfMac(iface); err != nil {
  16. return err
  17. }
  18. if node.PostDown != "" {
  19. runcmds := strings.Split(node.PostDown, "; ")
  20. ncutils.RunCmds(runcmds, true)
  21. }
  22. return nil
  23. }
  24. // RemoveConfMac - bring down mac interface and remove routes
  25. func RemoveConfMac(iface string) error {
  26. realIface, err := getRealIface(iface)
  27. if realIface != "" {
  28. err = deleteInterface(iface, realIface)
  29. }
  30. return err
  31. }
  32. // WgQuickUpMac - bring up mac interface and set routes
  33. func WgQuickUpMac(node *models.Node, iface string, confPath string) error {
  34. var err error
  35. var realIface string
  36. realIface, err = getRealIface(iface)
  37. if realIface != "" && err == nil {
  38. deleteInterface(iface, realIface)
  39. deleteRoutes(realIface)
  40. }
  41. realIface, err = addInterface(iface)
  42. if err != nil {
  43. logger.Log(1, "error creating wg interface")
  44. return err
  45. }
  46. time.Sleep(time.Second / 2)
  47. err = setConfig(realIface, confPath)
  48. if err != nil {
  49. logger.Log(1, "error setting config for ", realIface)
  50. return err
  51. }
  52. var ips = append(node.AllowedIPs, node.Address, node.Address6)
  53. for _, i := range ips {
  54. if i != "" {
  55. err = addAddress(realIface, i)
  56. if err != nil {
  57. logger.Log(1, "error adding address ", i, " on interface ", realIface)
  58. return err
  59. }
  60. }
  61. }
  62. setMTU(realIface, int(node.MTU))
  63. err = upInterface(realIface)
  64. if err != nil {
  65. logger.Log(1, "error turning on interface ", iface)
  66. return err
  67. }
  68. peerIPs := getPeerIPs(realIface)
  69. for _, i := range peerIPs {
  70. if i != "" {
  71. err = addRoute(i, realIface)
  72. if err != nil {
  73. logger.Log(1, "error adding route to ", realIface, " for ", i)
  74. return err
  75. }
  76. }
  77. }
  78. //next, wg-quick runs set_endpoint_direct_route
  79. //next, wg-quick runs monitor_daemon
  80. time.Sleep(time.Second / 2)
  81. if node.PostUp != "" {
  82. runcmds := strings.Split(node.PostUp, "; ")
  83. ncutils.RunCmds(runcmds, true)
  84. }
  85. return err
  86. }
  87. // addInterface - adds mac interface and creates reference file to match iface name with tun iface
  88. func addInterface(iface string) (string, error) {
  89. ncutils.RunCmd("mkdir -p /var/run/wireguard/", true)
  90. ncutils.RunCmd("wireguard-go utun", true)
  91. realIface, err := ncutils.GetNewIface("/var/run/wireguard/")
  92. if iface != "" && err == nil {
  93. ifacePath := "/var/run/wireguard/" + iface + ".name"
  94. err = os.WriteFile(ifacePath, []byte(realIface), 0600)
  95. }
  96. return realIface, err
  97. }
  98. // getRealIface - retrieves tun iface based on reference iface name from config file
  99. func getRealIface(iface string) (string, error) {
  100. ncutils.RunCmd("wg show interfaces", false)
  101. ifacePath := "/var/run/wireguard/" + iface + ".name"
  102. if !(ncutils.FileExists(ifacePath)) {
  103. return "", errors.New(ifacePath + " does not exist")
  104. }
  105. realIfaceName, err := ncutils.GetFileAsString(ifacePath)
  106. if err != nil {
  107. return "", err
  108. }
  109. if !(ncutils.FileExists("/var/run/wireguard/" + realIfaceName + ".sock")) {
  110. return "", errors.New("interface file does not exist")
  111. }
  112. return realIfaceName, nil
  113. }
  114. // deleteRoutes - deletes network routes associated with interface
  115. func deleteRoutes(iface string) error {
  116. realIface, err := getRealIface(iface)
  117. if err != nil {
  118. return err
  119. }
  120. var inets = [2]string{"inet", "inet6"}
  121. for _, inet := range inets {
  122. ifaceList, err := ncutils.RunCmd("netstat -nr -f "+inet+" | grep -e "+realIface+" | awk '{print $1}'", true)
  123. if err != nil {
  124. return err
  125. }
  126. destinations := strings.Split(ifaceList, "\n")
  127. for _, i := range destinations {
  128. ncutils.RunCmd("route -q -n delete -"+inet+" "+i, true)
  129. }
  130. }
  131. // wg-quick deletes ENDPOINTS here (runs 'route -q delete' for each peer endpoint on the interface.)
  132. // We don't believe this is necessary.
  133. return nil
  134. }
  135. // deleteInterface - deletes the real interface and the referance file
  136. func deleteInterface(iface string, realIface string) error {
  137. var err error
  138. var out string
  139. if iface != "" {
  140. os.Remove("/var/run/wireguard/" + realIface + ".sock")
  141. os.Remove("/var/run/wireguard/" + iface + ".name")
  142. }
  143. out, err = ncutils.RunCmd("ifconfig "+realIface+" down", false)
  144. if strings.Contains(err.Error(), "does not exist") {
  145. err = nil
  146. } else if err != nil && out != "" {
  147. err = errors.New(out)
  148. }
  149. return err
  150. }
  151. // upInterface - bring up the interface with ifconfig
  152. func upInterface(iface string) error {
  153. var err error
  154. _, err = ncutils.RunCmd("ifconfig "+iface+" up", true)
  155. return err
  156. }
  157. // addAddress - adds private address to the interface
  158. func addAddress(iface string, addr string) error {
  159. var err error
  160. if strings.Contains(addr, ":") {
  161. _, err = ncutils.RunCmd("ifconfig "+iface+" inet6 "+addr+" alias", true)
  162. } else {
  163. _, err = ncutils.RunCmd("ifconfig "+iface+" inet "+addr+" 255.255.255.0 alias", true)
  164. }
  165. return err
  166. }
  167. // setMTU - sets MTU for the interface
  168. func setMTU(iface string, mtu int) error {
  169. var err error
  170. if mtu == 0 {
  171. mtu = 1280
  172. }
  173. _, err = ncutils.RunCmd("ifconfig "+iface+" mtu "+strconv.Itoa(mtu), true)
  174. return err
  175. }
  176. // addRoute - adds network route to the interface if it does not already exist
  177. func addRoute(addr string, iface string) error {
  178. var err error
  179. var out string
  180. var inetx = "inet"
  181. if strings.Contains(addr, ":") {
  182. inetx = "inet6"
  183. }
  184. out, err = ncutils.RunCmd("route -n get -"+inetx+" "+addr, true)
  185. if err != nil {
  186. return err
  187. }
  188. if !(strings.Contains(out, iface)) {
  189. _, err = ncutils.RunCmd("route -q -n add -"+inetx+" "+addr+" -interface "+iface, true)
  190. }
  191. return err
  192. }
  193. // setConfig - sets configuration of the wireguard interface from the config file
  194. func setConfig(realIface string, confPath string) error {
  195. confString := getConfig(confPath)
  196. // pathFormatted := strings.Replace(confPath, " ", "\\ ", -1)
  197. err := os.WriteFile(confPath+".tmp", []byte(confString), 0600)
  198. if err != nil {
  199. return err
  200. }
  201. _, err = ncutils.RunCmd("wg setconf "+realIface+" "+confPath+".tmp", true)
  202. os.Remove(confPath + ".tmp")
  203. return err
  204. }
  205. // getConfig - gets config from config file and strips out incompatible fields
  206. func getConfig(path string) string {
  207. // pathFormatted := strings.Replace(path, " ", "\\ ", -1)
  208. var confCmd = "grep -v -e Address -e MTU -e PostUp -e PostDown "
  209. confRaw, _ := ncutils.RunCmd(confCmd+path, false)
  210. return confRaw
  211. }
  212. // SetMacPeerRoutes - sets routes for interface from the peer list for all AllowedIps
  213. func SetMacPeerRoutes(realIface string) error {
  214. var err error
  215. peerIPs := getPeerIPs(realIface)
  216. if len(peerIPs) == 0 {
  217. return err
  218. }
  219. for _, i := range peerIPs {
  220. if i != "" {
  221. err = addRoute(i, realIface)
  222. if err != nil {
  223. logger.Log(1, "error adding route to ", realIface, " for ", i)
  224. return err
  225. }
  226. }
  227. }
  228. return err
  229. }
  230. // getPeerIPs - retrieves peer AllowedIPs from WireGuard interface
  231. func getPeerIPs(realIface string) []string {
  232. allowedIps := []string{}
  233. out, err := ncutils.RunCmd("wg show "+realIface+" allowed-ips", false)
  234. if err != nil {
  235. return allowedIps
  236. }
  237. scanner := bufio.NewScanner(strings.NewReader(out))
  238. for scanner.Scan() {
  239. fields := strings.Fields(scanner.Text())
  240. if len(fields) > 1 {
  241. allowedIps = append(allowedIps, fields[1:]...)
  242. }
  243. }
  244. return allowedIps
  245. }