netsh.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. package netsh
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. "errors"
  9. utilexec "k8s.io/utils/exec"
  10. )
  11. // Interface is an injectable interface for running netsh commands. Implementations must be goroutine-safe.
  12. type Interface interface {
  13. // EnsurePortProxyRule checks if the specified redirect exists, if not creates it
  14. EnsurePortProxyRule(args []string) (bool, error)
  15. // DeletePortProxyRule deletes the specified portproxy rule. If the rule did not exist, return error.
  16. DeletePortProxyRule(args []string) error
  17. // DeleteIPAddress checks if the specified IP address is present and, if so, deletes it.
  18. DeleteIPAddress(args []string) error
  19. // Restore runs `netsh exec` to restore portproxy or addresses using a file.
  20. // TODO Check if this is required, most likely not
  21. Restore(args []string) error
  22. // Get the interface name that has the default gateway
  23. GetDefaultGatewayIfaceName() (string, error)
  24. // Get a list of interfaces and addresses
  25. GetInterfaces() ([]Ipv4Interface, error)
  26. // Gets an interface by name
  27. GetInterfaceByName(name string) (Ipv4Interface, error)
  28. // Gets an interface by ip address in the format a.b.c.d
  29. GetInterfaceByIP(ipAddr string) (Ipv4Interface, error)
  30. // Enable forwarding on the interface (name or index)
  31. EnableForwarding(iface string) error
  32. }
  33. const (
  34. cmdNetsh string = "netsh"
  35. )
  36. // runner implements Interface in terms of exec("netsh").
  37. type runner struct {
  38. mu sync.Mutex
  39. exec utilexec.Interface
  40. }
  41. // Ipv4Interface models IPv4 interface output from: netsh interface ipv4 show addresses
  42. type Ipv4Interface struct {
  43. Idx int
  44. Name string
  45. InterfaceMetric int
  46. DhcpEnabled bool
  47. IpAddress string
  48. SubnetPrefix int
  49. GatewayMetric int
  50. DefaultGatewayAddress string
  51. }
  52. // New returns a new Interface which will exec netsh.
  53. func New(exec utilexec.Interface) Interface {
  54. if exec == nil {
  55. exec = utilexec.New()
  56. }
  57. runner := &runner{
  58. exec: exec,
  59. }
  60. return runner
  61. }
  62. func (runner *runner) GetInterfaces() ([]Ipv4Interface, error) {
  63. interfaces, interfaceError := runner.getIpAddressConfigurations()
  64. if interfaceError != nil {
  65. return nil, interfaceError
  66. }
  67. indexMap, indexError := runner.getNetworkInterfaceParameters()
  68. if indexError != nil {
  69. return nil, indexError
  70. }
  71. // zip them up
  72. for i := 0; i < len(interfaces); i++ {
  73. name := interfaces[i].Name
  74. if val, ok := indexMap[name]; ok {
  75. interfaces[i].Idx = val
  76. } else {
  77. return nil, fmt.Errorf("no index found for interface \"%v\"", name)
  78. }
  79. }
  80. return interfaces, nil
  81. }
  82. // GetInterfaces uses the show addresses command and returns a formatted structure
  83. func (runner *runner) getIpAddressConfigurations() ([]Ipv4Interface, error) {
  84. args := []string{
  85. "interface", "ipv4", "show", "addresses",
  86. }
  87. output, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput()
  88. if err != nil {
  89. return nil, err
  90. }
  91. interfacesString := string(output[:])
  92. outputLines := strings.Split(interfacesString, "\n")
  93. var interfaces []Ipv4Interface
  94. var currentInterface Ipv4Interface
  95. quotedPattern := regexp.MustCompile("\\\"(.*?)\\\"")
  96. cidrPattern := regexp.MustCompile("\\/(.*?)\\ ")
  97. if err != nil {
  98. return nil, err
  99. }
  100. for _, outputLine := range outputLines {
  101. if strings.Contains(outputLine, "Configuration for interface") {
  102. if currentInterface != (Ipv4Interface{}) {
  103. interfaces = append(interfaces, currentInterface)
  104. }
  105. match := quotedPattern.FindStringSubmatch(outputLine)
  106. currentInterface = Ipv4Interface{
  107. Name: match[1],
  108. }
  109. } else {
  110. parts := strings.SplitN(outputLine, ":", 2)
  111. if len(parts) != 2 {
  112. continue
  113. }
  114. key := strings.TrimSpace(parts[0])
  115. value := strings.TrimSpace(parts[1])
  116. if strings.HasPrefix(key, "DHCP enabled") {
  117. if value == "Yes" {
  118. currentInterface.DhcpEnabled = true
  119. }
  120. } else if strings.HasPrefix(key, "InterfaceMetric") {
  121. if val, err := strconv.Atoi(value); err == nil {
  122. currentInterface.InterfaceMetric = val
  123. }
  124. } else if strings.HasPrefix(key, "Gateway Metric") {
  125. if val, err := strconv.Atoi(value); err == nil {
  126. currentInterface.GatewayMetric = val
  127. }
  128. } else if strings.HasPrefix(key, "Subnet Prefix") {
  129. match := cidrPattern.FindStringSubmatch(value)
  130. if val, err := strconv.Atoi(match[1]); err == nil {
  131. currentInterface.SubnetPrefix = val
  132. }
  133. } else if strings.HasPrefix(key, "IP Address") {
  134. currentInterface.IpAddress = value
  135. } else if strings.HasPrefix(key, "Default Gateway") {
  136. currentInterface.DefaultGatewayAddress = value
  137. }
  138. }
  139. }
  140. // add the last one
  141. if currentInterface != (Ipv4Interface{}) {
  142. interfaces = append(interfaces, currentInterface)
  143. }
  144. if len(interfaces) == 0 {
  145. return nil, fmt.Errorf("no interfaces found in netsh output: %v", interfacesString)
  146. }
  147. return interfaces, nil
  148. }
  149. func (runner *runner) getNetworkInterfaceParameters() (map[string]int, error) {
  150. args := []string{
  151. "interface", "ipv4", "show", "interfaces",
  152. }
  153. output, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput()
  154. if err != nil {
  155. return nil, err
  156. }
  157. // Split output by line
  158. outputString := string(output[:])
  159. outputString = strings.TrimSpace(outputString)
  160. var outputLines = strings.Split(outputString, "\n")
  161. if len(outputLines) < 3 {
  162. return nil, errors.New("unexpected netsh output:\n" + outputString)
  163. }
  164. // Remove first two lines of header text
  165. outputLines = outputLines[2:]
  166. indexMap := make(map[string]int)
  167. reg := regexp.MustCompile("\\s{2,}")
  168. for _, line := range outputLines {
  169. line = strings.TrimSpace(line)
  170. // Split the line by two or more whitespace characters, returning all substrings (n < 0)
  171. splitLine := reg.Split(line, -1)
  172. name := splitLine[4]
  173. if idx, err := strconv.Atoi(splitLine[0]); err == nil {
  174. indexMap[name] = idx
  175. }
  176. }
  177. return indexMap, nil
  178. }
  179. // Enable forwarding on the interface (name or index)
  180. func (runner *runner) EnableForwarding(iface string) error {
  181. args := []string{
  182. "int", "ipv4", "set", "int", strconv.Quote(iface), "for=en",
  183. }
  184. cmd := strings.Join(args, " ")
  185. if stdout, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput(); err != nil {
  186. return fmt.Errorf("failed to enable forwarding on [%v], error: %v. cmd: %v. stdout: %v", iface, err.Error(), cmd, string(stdout))
  187. }
  188. return nil
  189. }
  190. // EnsurePortProxyRule checks if the specified redirect exists, if not creates it.
  191. func (runner *runner) EnsurePortProxyRule(args []string) (bool, error) {
  192. out, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput()
  193. if err == nil {
  194. return true, nil
  195. }
  196. if ee, ok := err.(utilexec.ExitError); ok {
  197. // netsh uses exit(0) to indicate a success of the operation,
  198. // as compared to a malformed commandline, for example.
  199. if ee.Exited() && ee.ExitStatus() != 0 {
  200. return false, nil
  201. }
  202. }
  203. return false, fmt.Errorf("error checking portproxy rule: %v: %s", err, out)
  204. }
  205. // DeletePortProxyRule deletes the specified portproxy rule. If the rule did not exist, return error.
  206. func (runner *runner) DeletePortProxyRule(args []string) error {
  207. out, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput()
  208. if err == nil {
  209. return nil
  210. }
  211. if ee, ok := err.(utilexec.ExitError); ok {
  212. // netsh uses exit(0) to indicate a success of the operation,
  213. // as compared to a malformed commandline, for example.
  214. if ee.Exited() && ee.ExitStatus() == 0 {
  215. return nil
  216. }
  217. }
  218. return fmt.Errorf("error deleting portproxy rule: %v: %s", err, out)
  219. }
  220. // DeleteIPAddress checks if the specified IP address is present and, if so, deletes it.
  221. func (runner *runner) DeleteIPAddress(args []string) error {
  222. out, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput()
  223. if err == nil {
  224. return nil
  225. }
  226. if ee, ok := err.(utilexec.ExitError); ok {
  227. // netsh uses exit(0) to indicate a success of the operation,
  228. // as compared to a malformed commandline, for example.
  229. if ee.Exited() && ee.ExitStatus() == 0 {
  230. return nil
  231. }
  232. }
  233. return fmt.Errorf("error deleting ipv4 address: %v: %s", err, out)
  234. }
  235. func (runner *runner) GetDefaultGatewayIfaceName() (string, error) {
  236. interfaces, err := runner.GetInterfaces()
  237. if err != nil {
  238. return "", err
  239. }
  240. for _, iface := range interfaces {
  241. if iface.DefaultGatewayAddress != "" {
  242. return iface.Name, nil
  243. }
  244. }
  245. // return "not found"
  246. return "", fmt.Errorf("Default interface not found")
  247. }
  248. func (runner *runner) GetInterfaceByName(name string) (Ipv4Interface, error) {
  249. interfaces, err := runner.GetInterfaces()
  250. if err != nil {
  251. return Ipv4Interface{}, err
  252. }
  253. for _, iface := range interfaces {
  254. if iface.Name == name {
  255. return iface, nil
  256. }
  257. }
  258. // return "not found"
  259. return Ipv4Interface{}, fmt.Errorf("Interface not found: %v", name)
  260. }
  261. func (runner *runner) GetInterfaceByIP(ipAddr string) (Ipv4Interface, error) {
  262. interfaces, err := runner.GetInterfaces()
  263. if err != nil {
  264. return Ipv4Interface{}, err
  265. }
  266. for _, iface := range interfaces {
  267. if iface.IpAddress == ipAddr {
  268. return iface, nil
  269. }
  270. }
  271. // return "not found"
  272. return Ipv4Interface{}, fmt.Errorf("Interface not found: %v", ipAddr)
  273. }
  274. // Restore is part of Interface.
  275. func (runner *runner) Restore(args []string) error {
  276. return nil
  277. }