plugin.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Copyright 2018-present the CoreDHCP Authors. All rights reserved
  2. // This source code is licensed under the MIT license found in the
  3. // LICENSE file in the root directory of this source tree.
  4. // Package file enables static mapping of MAC <--> IP addresses.
  5. // The mapping is stored in a text file, where each mapping is described by one line containing
  6. // two fields separated by spaces: MAC address, and IP address. For example:
  7. //
  8. // $ cat file_leases.txt
  9. // 00:11:22:33:44:55 10.0.0.1
  10. // 01:23:45:67:89:01 10.0.10.10
  11. //
  12. // To specify the plugin configuration in the server6/server4 sections of the config file, just
  13. // pass the leases file name as plugin argument, e.g.:
  14. //
  15. // $ cat config.yml
  16. //
  17. // server6:
  18. // ...
  19. // plugins:
  20. // - file: "file_leases.txt"
  21. // ...
  22. //
  23. // If the file path is not absolute, it is relative to the cwd where coredhcp is run.
  24. package file
  25. import (
  26. "bytes"
  27. "errors"
  28. "fmt"
  29. "io/ioutil"
  30. "net"
  31. "strings"
  32. "time"
  33. "github.com/coredhcp/coredhcp/handler"
  34. "github.com/coredhcp/coredhcp/logger"
  35. "github.com/coredhcp/coredhcp/plugins"
  36. "github.com/insomniacslk/dhcp/dhcpv4"
  37. "github.com/insomniacslk/dhcp/dhcpv6"
  38. )
  39. var log = logger.GetLogger("plugins/file")
  40. // Plugin wraps plugin registration information
  41. var Plugin = plugins.Plugin{
  42. Name: "file",
  43. Setup6: setup6,
  44. Setup4: setup4,
  45. }
  46. // StaticRecords holds a MAC -> IP address mapping
  47. var StaticRecords map[string]net.IP
  48. // DHCPv6Records and DHCPv4Records are mappings between MAC addresses in
  49. // form of a string, to network configurations.
  50. var (
  51. DHCPv6Records map[string]net.IP
  52. DHCPv4Records map[string]net.IP
  53. )
  54. // LoadDHCPv4Records loads the DHCPv4Records global map with records stored on
  55. // the specified file. The records have to be one per line, a mac address and an
  56. // IPv4 address.
  57. func LoadDHCPv4Records(filename string) (map[string]net.IP, error) {
  58. log.Infof("reading leases from %s", filename)
  59. data, err := ioutil.ReadFile(filename)
  60. if err != nil {
  61. return nil, err
  62. }
  63. records := make(map[string]net.IP)
  64. for _, lineBytes := range bytes.Split(data, []byte{'\n'}) {
  65. line := string(lineBytes)
  66. if len(line) == 0 {
  67. continue
  68. }
  69. tokens := strings.Fields(line)
  70. if len(tokens) != 2 {
  71. return nil, fmt.Errorf("malformed line, want 2 fields, got %d: %s", len(tokens), line)
  72. }
  73. hwaddr, err := net.ParseMAC(tokens[0])
  74. if err != nil {
  75. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  76. }
  77. ipaddr := net.ParseIP(tokens[1])
  78. if ipaddr.To4() == nil {
  79. return nil, fmt.Errorf("expected an IPv4 address, got: %v", ipaddr)
  80. }
  81. records[hwaddr.String()] = ipaddr
  82. }
  83. return records, nil
  84. }
  85. // LoadDHCPv6Records loads the DHCPv6Records global map with records stored on
  86. // the specified file. The records have to be one per line, a mac address and an
  87. // IPv6 address.
  88. func LoadDHCPv6Records(filename string) (map[string]net.IP, error) {
  89. log.Infof("reading leases from %s", filename)
  90. data, err := ioutil.ReadFile(filename)
  91. if err != nil {
  92. return nil, err
  93. }
  94. records := make(map[string]net.IP)
  95. // TODO ignore comments
  96. for _, lineBytes := range bytes.Split(data, []byte{'\n'}) {
  97. line := string(lineBytes)
  98. if len(line) == 0 {
  99. continue
  100. }
  101. tokens := strings.Fields(line)
  102. if len(tokens) != 2 {
  103. return nil, fmt.Errorf("malformed line: %s", line)
  104. }
  105. hwaddr, err := net.ParseMAC(tokens[0])
  106. if err != nil {
  107. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  108. }
  109. ipaddr := net.ParseIP(tokens[1])
  110. if ipaddr.To16() == nil {
  111. return nil, fmt.Errorf("expected an IPv6 address, got: %v", ipaddr)
  112. }
  113. records[hwaddr.String()] = ipaddr
  114. }
  115. return records, nil
  116. }
  117. // Handler6 handles DHCPv6 packets for the file plugin
  118. func Handler6(req, resp dhcpv6.DHCPv6) (dhcpv6.DHCPv6, bool) {
  119. mac, err := dhcpv6.ExtractMAC(req)
  120. if err != nil {
  121. log.Warningf("Could not find client MAC, passing")
  122. return resp, false
  123. }
  124. log.Debugf("looking up an IP address for MAC %s", mac.String())
  125. ipaddr, ok := StaticRecords[mac.String()]
  126. if !ok {
  127. log.Warningf("MAC address %s is unknown", mac.String())
  128. return resp, false
  129. }
  130. log.Debugf("found IP address %s for MAC %s", ipaddr, mac.String())
  131. resp.AddOption(&dhcpv6.OptIANA{
  132. // FIXME copy this field from the client, reject/drop if missing
  133. IaId: [4]byte{0xaa, 0xbb, 0xcc, 0xdd},
  134. Options: dhcpv6.IdentityOptions{Options: []dhcpv6.Option{
  135. &dhcpv6.OptIAAddress{
  136. IPv6Addr: ipaddr,
  137. PreferredLifetime: 3600 * time.Second,
  138. ValidLifetime: 3600 * time.Second,
  139. },
  140. }},
  141. })
  142. return resp, false
  143. }
  144. // Handler4 handles DHCPv4 packets for the file plugin
  145. func Handler4(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
  146. ipaddr, ok := StaticRecords[req.ClientHWAddr.String()]
  147. if !ok {
  148. log.Warningf("MAC address %s is unknown", req.ClientHWAddr.String())
  149. return resp, false
  150. }
  151. resp.YourIPAddr = ipaddr
  152. log.Debugf("found IP address %s for MAC %s", ipaddr, req.ClientHWAddr.String())
  153. return resp, true
  154. }
  155. func setup6(args ...string) (handler.Handler6, error) {
  156. h6, _, err := setupFile(true, args...)
  157. return h6, err
  158. }
  159. func setup4(args ...string) (handler.Handler4, error) {
  160. _, h4, err := setupFile(false, args...)
  161. return h4, err
  162. }
  163. func setupFile(v6 bool, args ...string) (handler.Handler6, handler.Handler4, error) {
  164. var err error
  165. var records map[string]net.IP
  166. if len(args) < 1 {
  167. return nil, nil, errors.New("need a file name")
  168. }
  169. filename := args[0]
  170. if filename == "" {
  171. return nil, nil, errors.New("got empty file name")
  172. }
  173. if v6 {
  174. records, err = LoadDHCPv6Records(filename)
  175. } else {
  176. records, err = LoadDHCPv4Records(filename)
  177. }
  178. if err != nil {
  179. return nil, nil, fmt.Errorf("failed to load DHCPv6 records: %v", err)
  180. }
  181. StaticRecords = records
  182. log.Infof("loaded %d leases from %s", len(records), filename)
  183. return Handler6, Handler4, nil
  184. }