mac.go 7.2 KB

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