plugin.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. "github.com/coredhcp/coredhcp/handler"
  33. "github.com/coredhcp/coredhcp/logger"
  34. "github.com/coredhcp/coredhcp/plugins"
  35. "github.com/insomniacslk/dhcp/dhcpv4"
  36. "github.com/insomniacslk/dhcp/dhcpv6"
  37. )
  38. var log = logger.GetLogger("plugins/file")
  39. func init() {
  40. plugins.RegisterPlugin("file", setupFile6, setupFile4)
  41. }
  42. // StaticRecords holds a MAC -> IP address mapping
  43. var StaticRecords map[string]net.IP
  44. // DHCPv6Records and DHCPv4Records are mappings between MAC addresses in
  45. // form of a string, to network configurations.
  46. var (
  47. DHCPv6Records map[string]net.IP
  48. DHCPv4Records map[string]net.IP
  49. )
  50. // LoadDHCPv4Records loads the DHCPv4Records global map with records stored on
  51. // the specified file. The records have to be one per line, a mac address and an
  52. // IPv4 address.
  53. func LoadDHCPv4Records(filename string) (map[string]net.IP, error) {
  54. log.Printf("reading leases from %s", filename)
  55. data, err := ioutil.ReadFile(filename)
  56. if err != nil {
  57. return nil, err
  58. }
  59. records := make(map[string]net.IP)
  60. for _, lineBytes := range bytes.Split(data, []byte{'\n'}) {
  61. line := string(lineBytes)
  62. if len(line) == 0 {
  63. continue
  64. }
  65. tokens := strings.Fields(line)
  66. if len(tokens) != 2 {
  67. return nil, fmt.Errorf("malformed line, want 2 fields, got %d: %s", len(tokens), line)
  68. }
  69. hwaddr, err := net.ParseMAC(tokens[0])
  70. if err != nil {
  71. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  72. }
  73. ipaddr := net.ParseIP(tokens[1])
  74. if ipaddr.To4() == nil {
  75. return nil, fmt.Errorf("expected an IPv4 address, got: %v", ipaddr)
  76. }
  77. records[hwaddr.String()] = ipaddr
  78. }
  79. return records, nil
  80. }
  81. // LoadDHCPv6Records loads the DHCPv6Records global map with records stored on
  82. // the specified file. The records have to be one per line, a mac address and an
  83. // IPv6 address.
  84. func LoadDHCPv6Records(filename string) (map[string]net.IP, error) {
  85. log.Printf("reading leases from %s", filename)
  86. data, err := ioutil.ReadFile(filename)
  87. if err != nil {
  88. return nil, err
  89. }
  90. records := make(map[string]net.IP)
  91. // TODO ignore comments
  92. for _, lineBytes := range bytes.Split(data, []byte{'\n'}) {
  93. line := string(lineBytes)
  94. if len(line) == 0 {
  95. continue
  96. }
  97. tokens := strings.Fields(line)
  98. if len(tokens) != 2 {
  99. return nil, fmt.Errorf("malformed line: %s", line)
  100. }
  101. hwaddr, err := net.ParseMAC(tokens[0])
  102. if err != nil {
  103. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  104. }
  105. ipaddr := net.ParseIP(tokens[1])
  106. if ipaddr.To16() == nil {
  107. return nil, fmt.Errorf("expected an IPv6 address, got: %v", ipaddr)
  108. }
  109. records[hwaddr.String()] = ipaddr
  110. }
  111. return records, nil
  112. }
  113. // Handler6 handles DHCPv6 packets for the file plugin
  114. func Handler6(req, resp dhcpv6.DHCPv6) (dhcpv6.DHCPv6, bool) {
  115. mac, err := dhcpv6.ExtractMAC(req)
  116. if err != nil {
  117. log.Warningf("Could not find client MAC, passing")
  118. return resp, false
  119. }
  120. log.Printf("looking up an IP address for MAC %s", mac.String())
  121. ipaddr, ok := StaticRecords[mac.String()]
  122. if !ok {
  123. log.Warningf("MAC address %s is unknown", mac.String())
  124. return resp, false
  125. }
  126. log.Printf("found IP address %s for MAC %s", ipaddr, mac.String())
  127. resp.AddOption(&dhcpv6.OptIANA{
  128. // FIXME copy this field from the client, reject/drop if missing
  129. IaId: [4]byte{0xaa, 0xbb, 0xcc, 0xdd},
  130. Options: []dhcpv6.Option{
  131. &dhcpv6.OptIAAddress{
  132. IPv6Addr: ipaddr,
  133. PreferredLifetime: 3600,
  134. ValidLifetime: 3600,
  135. },
  136. },
  137. })
  138. decap, err := req.GetInnerMessage()
  139. if err != nil {
  140. log.Errorf("Could not decapsulate: %v", err)
  141. return nil, true
  142. }
  143. if oro := decap.GetOption(dhcpv6.OptionORO); len(oro) > 0 {
  144. for _, code := range oro[0].(*dhcpv6.OptRequestedOption).RequestedOptions() {
  145. if code == dhcpv6.OptionBootfileURL {
  146. // bootfile URL is requested
  147. // FIXME this field should come from the configuration, not
  148. // being hardcoded
  149. resp.AddOption(
  150. &dhcpv6.OptBootFileURL{BootFileURL: []byte("http://[2001:db8::0:1]/nbp")},
  151. )
  152. }
  153. }
  154. }
  155. // XXX: We should maybe allow other plugins to run after this to add other options/handle non-IANA requests
  156. return resp, true
  157. }
  158. // Handler4 handles DHCPv4 packets for the file plugin
  159. func Handler4(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
  160. ipaddr, ok := StaticRecords[req.ClientHWAddr.String()]
  161. if !ok {
  162. log.Warningf("MAC address %s is unknown", req.ClientHWAddr.String())
  163. return resp, false
  164. }
  165. resp.YourIPAddr = ipaddr
  166. log.Printf("found IP address %s for MAC %s", ipaddr, req.ClientHWAddr.String())
  167. return resp, true
  168. }
  169. func setupFile6(args ...string) (handler.Handler6, error) {
  170. h6, _, err := setupFile(true, args...)
  171. return h6, err
  172. }
  173. func setupFile4(args ...string) (handler.Handler4, error) {
  174. _, h4, err := setupFile(false, args...)
  175. return h4, err
  176. }
  177. func setupFile(v6 bool, args ...string) (handler.Handler6, handler.Handler4, error) {
  178. var err error
  179. var records map[string]net.IP
  180. if len(args) < 1 {
  181. return nil, nil, errors.New("need a file name")
  182. }
  183. filename := args[0]
  184. if filename == "" {
  185. return nil, nil, errors.New("got empty file name")
  186. }
  187. if v6 {
  188. records, err = LoadDHCPv6Records(filename)
  189. } else {
  190. records, err = LoadDHCPv4Records(filename)
  191. }
  192. if err != nil {
  193. return nil, nil, fmt.Errorf("failed to load DHCPv6 records: %v", err)
  194. }
  195. StaticRecords = records
  196. log.Printf("loaded %d leases from %s", len(records), filename)
  197. return Handler6, Handler4, nil
  198. }