summaryrefslogtreecommitdiffhomepage
path: root/dhcpv4
diff options
context:
space:
mode:
Diffstat (limited to 'dhcpv4')
-rw-r--r--dhcpv4/bsdp/bsdp.go336
-rw-r--r--dhcpv4/bsdp/bsdp_test.go362
-rw-r--r--dhcpv4/bsdp/client.go117
-rw-r--r--dhcpv4/bsdp/types.go68
-rw-r--r--dhcpv4/client.go15
-rw-r--r--dhcpv4/dhcpv4.go76
-rw-r--r--dhcpv4/dhcpv4_test.go3
-rw-r--r--dhcpv4/options.go43
-rw-r--r--dhcpv4/types.go15
9 files changed, 1012 insertions, 23 deletions
diff --git a/dhcpv4/bsdp/bsdp.go b/dhcpv4/bsdp/bsdp.go
new file mode 100644
index 0000000..6c8d00f
--- /dev/null
+++ b/dhcpv4/bsdp/bsdp.go
@@ -0,0 +1,336 @@
+// +build darwin
+
+package bsdp
+
+// Implements Apple's netboot protocol BSDP (Boot Service Discovery Protocol).
+// Canonical implementation is defined here:
+// http://opensource.apple.com/source/bootp/bootp-198.1/Documentation/BSDP.doc
+
+import (
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "log"
+ "net"
+ "syscall"
+
+ "github.com/insomniacslk/dhcp/dhcpv4"
+)
+
+// MaxDHCPMessageSize is the size set in DHCP option 57 (DHCP Maximum Message Size).
+// BSDP includes its own sub-option (12) to indicate to NetBoot servers that the
+// client can support larger message sizes, and modern NetBoot servers will
+// prefer this BSDP-specific option over the DHCP standard option.
+const MaxDHCPMessageSize = 1500
+
+// BootImageID describes a boot image ID - whether it's an install image and
+// what kind of boot image (e.g. OS 9, macOS, hardware diagnostics)
+type BootImageID struct {
+ IsInstall bool
+ ImageType BootImageType
+ Index uint16
+}
+
+// ToBytes serializes a BootImageID to network-order bytes.
+func (b BootImageID) ToBytes() []byte {
+ bytes := make([]byte, 4)
+ if b.IsInstall {
+ bytes[0] |= 0x80
+ }
+ bytes[0] |= byte(b.ImageType)
+ binary.BigEndian.PutUint16(bytes[2:], b.Index)
+ return bytes
+}
+
+// BootImageIDFromBytes deserializes a collection of 4 bytes to a BootImageID.
+func BootImageIDFromBytes(bytes []byte) (*BootImageID, error) {
+ if len(bytes) < 4 {
+ return nil, fmt.Errorf("not enough bytes to serialize BootImageID")
+ }
+ return &BootImageID{
+ IsInstall: bytes[0]&0x80 != 0,
+ ImageType: BootImageType(bytes[0] & 0x7f),
+ Index: binary.BigEndian.Uint16(bytes[2:]),
+ }, nil
+}
+
+// BootImage describes a boot image - contains the boot image ID and the name.
+type BootImage struct {
+ ID BootImageID
+ Name string
+}
+
+// ToBytes converts a BootImage to a slice of bytes.
+func (b *BootImage) ToBytes() []byte {
+ bytes := b.ID.ToBytes()
+ bytes = append(bytes, byte(len(b.Name)))
+ bytes = append(bytes, []byte(b.Name)...)
+ return bytes
+}
+
+// BootImageFromBytes returns a deserialized BootImage struct from bytes.
+func BootImageFromBytes(bytes []byte) (*BootImage, error) {
+ // Should at least contain 4 bytes of BootImageID + byte for length of
+ // boot image name.
+ if len(bytes) < 5 {
+ return nil, fmt.Errorf("not enough bytes to serialize BootImage")
+ }
+ imageID, err := BootImageIDFromBytes(bytes[:4])
+ if err != nil {
+ return nil, err
+ }
+ nameLength := int(bytes[4])
+ if 5+nameLength > len(bytes) {
+ return nil, fmt.Errorf("not enough bytes for BootImage")
+ }
+ name := string(bytes[5 : 5+nameLength])
+ return &BootImage{ID: *imageID, Name: name}, nil
+}
+
+// makeVendorClassIdentifier calls the sysctl syscall on macOS to get the
+// platform model.
+func makeVendorClassIdentifier() (string, error) {
+ // Fetch hardware model for class ID.
+ hwModel, err := syscall.Sysctl("hw.model")
+ if err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("AAPLBSDPC/i386/%s", hwModel), nil
+}
+
+// ParseBootImagesFromOption parses data from the BSDPOptionBootImageList
+// option and returns a list of BootImages.
+func ParseBootImagesFromOption(data []byte) ([]BootImage, error) {
+ // Should at least have the # bytes of boot images.
+ if len(data) < 4 {
+ return nil, fmt.Errorf("invalid length boot image list")
+ }
+
+ var (
+ readByteCount = 0
+ start = data
+ bootImages []BootImage
+ )
+ for {
+ bootImage, err := BootImageFromBytes(start)
+ if err != nil {
+ return nil, err
+ }
+ bootImages = append(bootImages, *bootImage)
+ // Read BootImageID + name length + name
+ readByteCount += 4 + 1 + len(bootImage.Name)
+ if readByteCount+1 >= len(data) {
+ break
+ }
+ start = start[readByteCount:]
+ }
+
+ return bootImages, nil
+}
+
+// ParseVendorOptionsFromOptions extracts the sub-options list of the vendor-
+// specific options from the larger DHCP options list.
+// TODO: Implement options.GetOneOption for dhcpv4.
+func ParseVendorOptionsFromOptions(options []dhcpv4.Option) []dhcpv4.Option {
+ var (
+ vendorOpts []dhcpv4.Option
+ err error
+ )
+ for _, opt := range options {
+ if opt.Code == dhcpv4.OptionVendorSpecificInformation {
+ vendorOpts, err = dhcpv4.OptionsFromBytesWithoutMagicCookie(opt.Data)
+ if err != nil {
+ log.Println("Warning: could not parse vendor options in DHCP options")
+ return []dhcpv4.Option{}
+ }
+ break
+ }
+ }
+ return vendorOpts
+}
+
+// ParseBootImageListFromAck parses the list of boot images presented in the
+// ACK[LIST] packet and returns them as a list of BootImages.
+func ParseBootImageListFromAck(ack dhcpv4.DHCPv4) ([]BootImage, error) {
+ var bootImages []BootImage
+ for _, opt := range ParseVendorOptionsFromOptions(ack.Options()) {
+ if opt.Code == OptionBootImageList {
+ images, err := ParseBootImagesFromOption(opt.Data)
+ if err != nil {
+ return nil, err
+ }
+ bootImages = append(bootImages, images...)
+ }
+ }
+
+ return bootImages, nil
+}
+
+func needsReplyPort(replyPort uint16) bool {
+ return replyPort != 0 && replyPort != dhcpv4.ClientPort
+}
+
+func serializeReplyPort(replyPort uint16) []byte {
+ bytes := make([]byte, 2)
+ binary.BigEndian.PutUint16(bytes, replyPort)
+ return bytes
+}
+
+// NewInformListForInterface creates a new INFORM packet for interface ifname
+// with configuration options specified by config.
+func NewInformListForInterface(iface string, replyPort uint16) (*dhcpv4.DHCPv4, error) {
+ d, err := dhcpv4.NewInformForInterface(iface /* needsBroadcast = */, false)
+ if err != nil {
+ return nil, err
+ }
+
+ // Validate replyPort first
+ if needsReplyPort(replyPort) && replyPort >= 1024 {
+ return nil, errors.New("replyPort must be a privileged port")
+ }
+
+ // These are vendor-specific options used to pass along BSDP information.
+ vendorOpts := []dhcpv4.Option{
+ dhcpv4.Option{
+ Code: OptionMessageType,
+ Data: []byte{byte(MessageTypeList)},
+ },
+ dhcpv4.Option{
+ Code: OptionVersion,
+ Data: Version1_1,
+ },
+ }
+
+ if needsReplyPort(replyPort) {
+ vendorOpts = append(vendorOpts,
+ dhcpv4.Option{
+ Code: OptionReplyPort,
+ Data: serializeReplyPort(replyPort),
+ },
+ )
+ }
+ d.AddOption(dhcpv4.Option{
+ Code: dhcpv4.OptionVendorSpecificInformation,
+ Data: dhcpv4.OptionsToBytesWithoutMagicCookie(vendorOpts),
+ })
+
+ d.AddOption(dhcpv4.Option{
+ Code: dhcpv4.OptionParameterRequestList,
+ Data: []byte{
+ dhcpv4.OptionVendorSpecificInformation,
+ dhcpv4.OptionClassIdentifier,
+ },
+ })
+
+ u16 := make([]byte, 2)
+ binary.BigEndian.PutUint16(u16, MaxDHCPMessageSize)
+ d.AddOption(dhcpv4.Option{
+ Code: dhcpv4.OptionMaximumDHCPMessageSize,
+ Data: u16,
+ })
+
+ vendorClassID, err := makeVendorClassIdentifier()
+ if err != nil {
+ return nil, err
+ }
+ d.AddOption(dhcpv4.Option{
+ Code: dhcpv4.OptionClassIdentifier,
+ Data: []byte(vendorClassID),
+ })
+
+ d.AddOption(dhcpv4.Option{Code: dhcpv4.OptionEnd})
+ return d, nil
+}
+
+// InformSelectForAck constructs an INFORM[SELECT] packet given an ACK to the
+// previously-sent INFORM[LIST] with Config config.
+func InformSelectForAck(ack dhcpv4.DHCPv4, replyPort uint16, selectedImage BootImage) (*dhcpv4.DHCPv4, error) {
+ d, err := dhcpv4.New()
+ if err != nil {
+ return nil, err
+ }
+
+ if needsReplyPort(replyPort) && replyPort >= 1024 {
+ return nil, errors.New("replyPort must be a privilegded port")
+ }
+ d.SetOpcode(dhcpv4.OpcodeBootRequest)
+ d.SetHwType(ack.HwType())
+ d.SetHwAddrLen(ack.HwAddrLen())
+ clientHwAddr := ack.ClientHwAddr()
+ d.SetClientHwAddr(clientHwAddr[:])
+ d.SetTransactionID(ack.TransactionID())
+ if ack.IsBroadcast() {
+ d.SetBroadcast()
+ } else {
+ d.SetUnicast()
+ }
+
+ // Data for OptionSelectedBootImageID
+ vendorOpts := []dhcpv4.Option{
+ dhcpv4.Option{
+ Code: OptionMessageType,
+ Data: []byte{byte(MessageTypeSelect)},
+ },
+ dhcpv4.Option{
+ Code: OptionVersion,
+ Data: Version1_1,
+ },
+ dhcpv4.Option{
+ Code: OptionSelectedBootImageID,
+ Data: selectedImage.ID.ToBytes(),
+ },
+ }
+
+ // Find server IP address
+ var serverIP net.IP
+ // TODO replace this loop with `ack.GetOneOption(OptionBootImageList)`
+ for _, opt := range ack.Options() {
+ if opt.Code == dhcpv4.OptionServerIdentifier {
+ serverIP = net.IP(opt.Data)
+ }
+ }
+ if serverIP.To4() == nil {
+ return nil, fmt.Errorf("could not parse server identifier from ACK")
+ }
+ vendorOpts = append(vendorOpts, dhcpv4.Option{
+ Code: OptionServerIdentifier,
+ Data: serverIP,
+ })
+
+ // Validate replyPort if requested.
+ if needsReplyPort(replyPort) {
+ vendorOpts = append(vendorOpts, dhcpv4.Option{
+ Code: OptionReplyPort,
+ Data: serializeReplyPort(replyPort),
+ })
+ }
+
+ vendorClassID, err := makeVendorClassIdentifier()
+ if err != nil {
+ return nil, err
+ }
+ d.AddOption(dhcpv4.Option{
+ Code: dhcpv4.OptionClassIdentifier,
+ Data: []byte(vendorClassID),
+ })
+ d.AddOption(dhcpv4.Option{
+ Code: dhcpv4.OptionParameterRequestList,
+ Data: []byte{
+ dhcpv4.OptionSubnetMask,
+ dhcpv4.OptionRouter,
+ dhcpv4.OptionBootfileName,
+ dhcpv4.OptionVendorSpecificInformation,
+ dhcpv4.OptionClassIdentifier,
+ },
+ })
+ d.AddOption(dhcpv4.Option{
+ Code: dhcpv4.OptionDHCPMessageType,
+ Data: []byte{byte(dhcpv4.MessageTypeInform)},
+ })
+ d.AddOption(dhcpv4.Option{
+ Code: dhcpv4.OptionVendorSpecificInformation,
+ Data: dhcpv4.OptionsToBytesWithoutMagicCookie(vendorOpts),
+ })
+ d.AddOption(dhcpv4.Option{Code: dhcpv4.OptionEnd})
+ return d, nil
+}
diff --git a/dhcpv4/bsdp/bsdp_test.go b/dhcpv4/bsdp/bsdp_test.go
new file mode 100644
index 0000000..b66efbc
--- /dev/null
+++ b/dhcpv4/bsdp/bsdp_test.go
@@ -0,0 +1,362 @@
+package bsdp
+
+import (
+ "testing"
+
+ "github.com/insomniacslk/dhcp/dhcpv4"
+ "github.com/stretchr/testify/assert"
+)
+
+/*
+ * BootImageID
+ */
+func TestBootImageIDToBytes(t *testing.T) {
+ b := BootImageID{
+ IsInstall: true,
+ ImageType: BootImageTypeMacOSX,
+ Index: 0x1000,
+ }
+ actual := b.ToBytes()
+ expected := []byte{0x81, 0, 0x10, 0}
+ assert.Equal(t, actual, expected, "serialized BootImageID should be equal")
+
+ b.IsInstall = false
+ actual = b.ToBytes()
+ expected = []byte{0x01, 0, 0x10, 0}
+ assert.Equal(t, actual, expected, "serialized BootImageID should be equal")
+}
+
+func TestBootImageIDFromBytes(t *testing.T) {
+ b := BootImageID{
+ IsInstall: false,
+ ImageType: BootImageTypeMacOSX,
+ Index: 0x1000,
+ }
+ newBootImage, err := BootImageIDFromBytes(b.ToBytes())
+ assert.Nil(t, err, "error from BootImageIDFromBytes")
+ assert.Equal(t, b, *newBootImage, "deserialized BootImage should be equal")
+
+ b = BootImageID{
+ IsInstall: true,
+ ImageType: BootImageTypeMacOSX,
+ Index: 0x1011,
+ }
+ newBootImage, err = BootImageIDFromBytes(b.ToBytes())
+ assert.Nil(t, err, "error from BootImageIDFromBytes")
+ assert.Equal(t, b, *newBootImage, "deserialized BootImage should be equal")
+}
+
+func TestBootImageIDFromBytesFail(t *testing.T) {
+ serialized := []byte{0x81, 0, 0x10} // intentionally left short
+ deserialized, err := BootImageIDFromBytes(serialized)
+ assert.Nil(t, deserialized, "BootImageIDFromBytes should return nil on failed deserialization")
+ assert.NotNil(t, err, "BootImageIDFromBytes should return err on failed deserialization")
+}
+
+/*
+ * BootImage
+ */
+func TestBootImageToBytes(t *testing.T) {
+ b := BootImage{
+ ID: BootImageID{
+ IsInstall: true,
+ ImageType: BootImageTypeMacOSX,
+ Index: 0x1000,
+ },
+ Name: "bsdp-1",
+ }
+ expected := []byte{
+ 0x81, 0, 0x10, 0, // boot image ID
+ 6, // len(Name)
+ 98, 115, 100, 112, 45, 49, // byte-encoding of Name
+ }
+ actual := b.ToBytes()
+ assert.Equal(t, actual, expected, "serialized BootImage should be equal")
+
+ b = BootImage{
+ ID: BootImageID{
+ IsInstall: false,
+ ImageType: BootImageTypeMacOSX,
+ Index: 0x1010,
+ },
+ Name: "bsdp-21",
+ }
+ expected = []byte{
+ 0x1, 0, 0x10, 0x10, // boot image ID
+ 7, // len(Name)
+ 98, 115, 100, 112, 45, 50, 49, // byte-encoding of Name
+ }
+ actual = b.ToBytes()
+ assert.Equal(t, actual, expected, "serialized BootImage should be equal")
+}
+
+func TestBootImageFromBytes(t *testing.T) {
+ input := []byte{
+ 0x1, 0, 0x10, 0x10, // boot image ID
+ 7, // len(Name)
+ 98, 115, 100, 112, 45, 50, 49, // byte-encoding of Name
+ }
+ b, err := BootImageFromBytes(input)
+ assert.Nil(t, err, "error while marshalling BootImage")
+ expectedBootImage := BootImage{
+ ID: BootImageID{
+ IsInstall: false,
+ ImageType: BootImageTypeMacOSX,
+ Index: 0x1010,
+ },
+ Name: "bsdp-21",
+ }
+ assert.Equal(t, *b, expectedBootImage, "invalid marshalling of BootImage")
+}
+
+func TestBootImageFromBytesOnlyBootImageID(t *testing.T) {
+ // Only a BootImageID, nothing else.
+ input := []byte{0x1, 0, 0x10, 0x10}
+ b, err := BootImageFromBytes(input)
+ assert.Nil(t, b, "short bytestream should return nil BootImageID")
+ assert.NotNil(t, err, "short bytestream should return error")
+}
+
+func TestBootImageFromBytesShortBootImage(t *testing.T) {
+ input := []byte{
+ 0x1, 0, 0x10, 0x10, // boot image ID
+ 7, // len(Name)
+ 98, 115, 100, 112, 45, 50, // Name bytes (intentionally off-by-one)
+ }
+ b, err := BootImageFromBytes(input)
+ assert.Nil(t, b, "short bytestream should return nil BootImageID")
+ assert.NotNil(t, err, "short bytestream should return error")
+}
+
+func TestParseBootImageSingleBootImage(t *testing.T) {
+ input := []byte{
+ 0x1, 0, 0x10, 0x10, // boot image ID
+ 7, // len(Name)
+ 98, 115, 100, 112, 45, 50, 49, // byte-encoding of Name
+ }
+ bs, err := ParseBootImagesFromOption(input)
+ assert.Nil(t, err, "parsing single boot image should not return error")
+ assert.Equal(t, len(bs), 1, "parsing single boot image should return 1")
+ b := bs[0]
+ expectedBootImage := BootImageID{
+ IsInstall: false,
+ ImageType: BootImageTypeMacOSX,
+ Index: 0x1010,
+ }
+ assert.Equal(t, b.ID, expectedBootImage, "parsed BootImageIDs should be equal")
+ assert.Equal(t, b.Name, "bsdp-21", "BootImage name should be equal")
+}
+
+func TestParseBootImageMultipleBootImage(t *testing.T) {
+ input := []byte{
+ // boot image 1
+ 0x1, 0, 0x10, 0x10, // boot image ID
+ 7, // len(Name)
+ 98, 115, 100, 112, 45, 50, 49, // byte-encoding of Name
+
+ // boot image 2
+ 0x82, 0, 0x11, 0x22, // boot image ID
+ 8, // len(Name)
+ 98, 115, 100, 112, 45, 50, 50, 50, // byte-encoding of Name
+ }
+ bs, err := ParseBootImagesFromOption(input)
+ assert.Nil(t, err, "parsing multiple BootImages should not return error")
+ assert.Equal(t, len(bs), 2, "parsing 2 BootImages should return 2")
+ b1 := bs[0]
+ b2 := bs[1]
+ expectedID1 := BootImageID{
+ IsInstall: false,
+ ImageType: BootImageTypeMacOSX,
+ Index: 0x1010,
+ }
+ expectedID2 := BootImageID{
+ IsInstall: true,
+ ImageType: BootImageTypeMacOSXServer,
+ Index: 0x1122,
+ }
+ assert.Equal(t, b1.ID, expectedID1, "first BootImageID should be equal")
+ assert.Equal(t, b2.ID, expectedID2, "second BootImageID should be equal")
+ assert.Equal(t, b1.Name, "bsdp-21", "first BootImage name should be equal")
+ assert.Equal(t, b2.Name, "bsdp-222", "second BootImage name should be equal")
+}
+
+func TestParseBootImageFail(t *testing.T) {
+ _, err := ParseBootImagesFromOption([]byte{})
+ assert.NotNil(t, err, "parseBootImages with empty arg")
+
+ _, err = ParseBootImagesFromOption([]byte{1, 2, 3})
+ assert.NotNil(t, err, "parseBootImages with short arg")
+
+ _, err = ParseBootImagesFromOption([]byte{
+ // boot image 1
+ 0x1, 0, 0x10, 0x10, // boot image ID
+ 7, // len(Name)
+ 98, 115, 100, 112, 45, 50, // byte-encoding of Name (intentionally shorter)
+
+ // boot image 2
+ 0x82, 0, 0x11, 0x22, // boot image ID
+ 8, // len(Name)
+ 98, 115, 100, 112, 45, 50, 50, 50, // byte-encoding of Name
+ })
+ assert.NotNil(t, err, "parseBootImages with short arg")
+}
+
+/*
+ * ParseVendorOptionsFromOptions
+ */
+func TestParseVendorOptions(t *testing.T) {
+ vendorOpts := []dhcpv4.Option{
+ dhcpv4.Option{
+ Code: OptionMessageType,
+ Data: []byte{byte(MessageTypeList)},
+ },
+ dhcpv4.Option{
+ Code: OptionVersion,
+ Data: Version1_0,
+ },
+ }
+ recvOpts := []dhcpv4.Option{
+ dhcpv4.Option{
+ Code: dhcpv4.OptionDHCPMessageType,
+ Data: []byte{byte(dhcpv4.MessageTypeAck)},
+ },
+ dhcpv4.Option{
+ Code: dhcpv4.OptionBroadcastAddress,
+ Data: []byte{0xff, 0xff, 0xff, 0xff},
+ },
+ dhcpv4.Option{
+ Code: dhcpv4.OptionVendorSpecificInformation,
+ Data: dhcpv4.OptionsToBytesWithoutMagicCookie(vendorOpts),
+ },
+ }
+ opts := ParseVendorOptionsFromOptions(recvOpts)
+ assert.Equal(t, opts, vendorOpts, "Parsed vendorOpts should be the same")
+}
+
+func TestParseVendorOptionsFromOptionsNotPresent(t *testing.T) {
+ recvOpts := []dhcpv4.Option{
+ dhcpv4.Option{
+ Code: dhcpv4.OptionDHCPMessageType,
+ Data: []byte{byte(dhcpv4.MessageTypeAck)},
+ },
+ dhcpv4.Option{
+ Code: dhcpv4.OptionBroadcastAddress,
+ Data: []byte{0xff, 0xff, 0xff, 0xff},
+ },
+ }
+ opts := ParseVendorOptionsFromOptions(recvOpts)
+ assert.Empty(t, opts, "vendor opts should be empty if not present in input")
+}
+
+func TestParseVendorOptionsFromOptionsEmpty(t *testing.T) {
+ options := ParseVendorOptionsFromOptions([]dhcpv4.Option{})
+ assert.Empty(t, options, "vendor opts should be empty if given an empty input")
+}
+
+func TestParseVendorOptionsFromOptionsFail(t *testing.T) {
+ opts := []dhcpv4.Option{
+ dhcpv4.Option{
+ Code: dhcpv4.OptionVendorSpecificInformation,
+ Data: []byte{
+ 0x1, 0x1, 0x1, // Option 1: LIST
+ 0x2, 0x2, 0x01, // Option 2: Version (intentionally left short)
+ },
+ },
+ }
+ vendorOpts := ParseVendorOptionsFromOptions(opts)
+ assert.Empty(t, vendorOpts, "vendor opts should be empty on parse error")
+}
+
+/*
+ * ParseBootImageListFromAck
+ */
+func TestParseBootImageListFromAck(t *testing.T) {
+ bootImages := []BootImage{
+ BootImage{
+ ID: BootImageID{
+ IsInstall: true,
+ ImageType: BootImageTypeMacOSX,
+ Index: 0x1010,
+ },
+ Name: "bsdp-1",
+ },
+ BootImage{
+ ID: BootImageID{
+ IsInstall: false,
+ ImageType: BootImageTypeMacOS9,
+ Index: 0x1111,
+ },
+ Name: "bsdp-2",
+ },
+ }
+ var bootImageBytes []byte
+ for _, image := range bootImages {
+ bootImageBytes = append(bootImageBytes, image.ToBytes()...)
+ }
+ ack, _ := dhcpv4.New()
+ ack.AddOption(dhcpv4.Option{
+ Code: dhcpv4.OptionVendorSpecificInformation,
+ Data: dhcpv4.OptionsToBytesWithoutMagicCookie([]dhcpv4.Option{
+ dhcpv4.Option{
+ Code: OptionBootImageList,
+ Data: bootImageBytes,
+ },
+ }),
+ })
+
+ images, err := ParseBootImageListFromAck(*ack)
+ assert.Nil(t, err, "error from ParseBootImageListFromAck")
+ assert.NotNil(t, images, "parsed boot images from ack")
+ assert.Equal(t, images, bootImages, "should get same BootImages")
+}
+
+func TestParseBootImageListFromAckNoVendorOption(t *testing.T) {
+ ack, _ := dhcpv4.New()
+ ack.AddOption(dhcpv4.Option{
+ Code: OptionMessageType,
+ Data: []byte{byte(dhcpv4.MessageTypeAck)},
+ })
+ images, err := ParseBootImageListFromAck(*ack)
+ assert.Nil(t, err, "no vendor extensions should not return error")
+ assert.Empty(t, images, "should not get images from ACK without Vendor extensions")
+}
+
+func TestParseBootImageListFromAckFail(t *testing.T) {
+ ack, _ := dhcpv4.New()
+ ack.AddOption(dhcpv4.Option{
+ Code: OptionMessageType,
+ Data: []byte{byte(dhcpv4.MessageTypeAck)},
+ })
+ ack.AddOption(dhcpv4.Option{
+ Code: dhcpv4.OptionVendorSpecificInformation,
+ Data: dhcpv4.OptionsToBytesWithoutMagicCookie([]dhcpv4.Option{
+ dhcpv4.Option{
+ Code: OptionBootImageList,
+ Data: []byte{
+ // boot image 1
+ 0x1, 0, 0x10, 0x10, // boot image ID
+ 7, // len(Name)
+ 98, 115, 100, 112, 45, 49, // byte-encoding of Name (intentionally short)
+
+ // boot image 2
+ 0x82, 0, 0x11, 0x22, // boot image ID
+ 8, // len(Name)
+ 98, 115, 100, 112, 45, 50, 50, 50, // byte-encoding of Name
+ },
+ },
+ }),
+ })
+
+ images, err := ParseBootImageListFromAck(*ack)
+ assert.Nil(t, images, "should get nil on parse error")
+ assert.NotNil(t, err, "should get error on parse error")
+}
+
+/*
+ * Private funcs
+ */
+func TestNeedsReplyPort(t *testing.T) {
+ assert.True(t, needsReplyPort(123), "")
+ assert.False(t, needsReplyPort(0), "")
+ assert.False(t, needsReplyPort(dhcpv4.ClientPort), "")
+}
diff --git a/dhcpv4/bsdp/client.go b/dhcpv4/bsdp/client.go
new file mode 100644
index 0000000..c2e8ae0
--- /dev/null
+++ b/dhcpv4/bsdp/client.go
@@ -0,0 +1,117 @@
+package bsdp
+
+import (
+ "fmt"
+ "net"
+ "syscall"
+
+ "github.com/insomniacslk/dhcp/dhcpv4"
+)
+
+// Client is a BSDP-specific client suitable for performing BSDP exchanges.
+type Client dhcpv4.Client
+
+// Exchange runs a full BSDP exchange (Inform[list], Ack, Inform[select],
+// Ack). Returns a list of DHCPv4 structures representing the exchange.
+func (c *Client) Exchange(ifname string, informList *dhcpv4.DHCPv4) ([]dhcpv4.DHCPv4, error) {
+ conversation := make([]dhcpv4.DHCPv4, 1)
+ var err error
+
+ // INFORM[LIST]
+ if informList == nil {
+ informList, err = NewInformListForInterface(ifname, dhcpv4.ClientPort)
+ if err != nil {
+ return conversation, err
+ }
+ }
+ conversation[0] = *informList
+
+ // TODO: deduplicate with code in dhcpv4/client.go
+ fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_RAW)
+ if err != nil {
+ return conversation, err
+ }
+ err = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
+ if err != nil {
+ return conversation, err
+ }
+ err = syscall.SetsockoptInt(fd, syscall.IPPROTO_IP, syscall.IP_HDRINCL, 1)
+ if err != nil {
+ return conversation, err
+ }
+ err = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1)
+ if err != nil {
+ return conversation, err
+ }
+ err = dhcpv4.BindToInterface(fd, ifname)
+ if err != nil {
+ return conversation, err
+ }
+
+ bcast := [4]byte{}
+ copy(bcast[:], net.IPv4bcast)
+ daddr := syscall.SockaddrInet4{Port: dhcpv4.ClientPort, Addr: bcast}
+ packet, err := dhcpv4.MakeRawBroadcastPacket(informList.ToBytes())
+ if err != nil {
+ return conversation, err
+ }
+ err = syscall.Sendto(fd, packet, 0, &daddr)
+ if err != nil {
+ return conversation, err
+ }
+
+ // ACK 1
+ conn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: dhcpv4.ClientPort})
+ if err != nil {
+ return conversation, err
+ }
+ defer conn.Close()
+
+ buf := make([]byte, dhcpv4.MaxUDPReceivedPacketSize)
+ oobdata := []byte{} // ignoring oob data
+ n, _, _, _, err := conn.ReadMsgUDP(buf, oobdata)
+ ack1, err := dhcpv4.FromBytes(buf[:n])
+ if err != nil {
+ return conversation, err
+ }
+ // TODO match the packet content
+ // TODO check that the peer address matches the declared server IP and port
+ conversation = append(conversation, *ack1)
+
+ // Parse boot images sent back by server
+ bootImages, err := ParseBootImageListFromAck(*ack1)
+ if err != nil {
+ return conversation, err
+ }
+ if len(bootImages) == 0 {
+ return conversation, fmt.Errorf("Got no BootImages from server")
+ }
+
+ // INFORM[SELECT]
+ informSelect, err := InformSelectForAck(*ack1, dhcpv4.ClientPort, bootImages[0])
+ if err != nil {
+ return conversation, err
+ }
+ conversation = append(conversation, *informSelect)
+ packet, err = dhcpv4.MakeRawBroadcastPacket(informSelect.ToBytes())
+ if err != nil {
+ return conversation, err
+ }
+ err = syscall.Sendto(fd, packet, 0, &daddr)
+ if err != nil {
+ return conversation, err
+ }
+
+ // ACK 2
+ buf = make([]byte, dhcpv4.MaxUDPReceivedPacketSize)
+ n, _, _, _, err = conn.ReadMsgUDP(buf, oobdata)
+ ack2, err := dhcpv4.FromBytes(buf[:n])
+ if err != nil {
+ return conversation, err
+ }
+ // TODO match the packet content
+ // TODO check that the peer address matches the declared server IP and port
+ conversation = append(conversation, *ack2)
+
+ return conversation, nil
+}
diff --git a/dhcpv4/bsdp/types.go b/dhcpv4/bsdp/types.go
new file mode 100644
index 0000000..54f38e2
--- /dev/null
+++ b/dhcpv4/bsdp/types.go
@@ -0,0 +1,68 @@
+package bsdp
+
+import "github.com/insomniacslk/dhcp/dhcpv4"
+
+// Options (occur as sub-options of DHCP option 43).
+const (
+ OptionMessageType dhcpv4.OptionCode = iota + 1
+ OptionVersion
+ OptionServerIdentifier
+ OptionServerPriority
+ OptionReplyPort
+ OptionBootImageListPath // Not used
+ OptionDefaultBootImageID
+ OptionSelectedBootImageID
+ OptionBootImageList
+ OptionNetboot1_0Firmware
+ OptionBootImageAttributesFilterList
+ OptionShadowMountPath dhcpv4.OptionCode = 128
+ OptionShadowFilePath dhcpv4.OptionCode = 129
+ OptionMachineName dhcpv4.OptionCode = 130
+)
+
+// Versions
+var (
+ Version1_0 = []byte{1, 0}
+ Version1_1 = []byte{1, 1}
+)
+
+// MessageType represents the different BSDP message types.
+type MessageType byte
+
+// BSDP Message types - e.g. LIST, SELECT, FAILED
+const (
+ MessageTypeList MessageType = iota + 1
+ MessageTypeSelect
+ MessageTypeFailed
+)
+
+// BootImageType represents the different BSDP boot image types.
+type BootImageType byte
+
+// Different types of BootImages - e.g. for different flavors of macOS.
+const (
+ BootImageTypeMacOS9 BootImageType = iota
+ BootImageTypeMacOSX
+ BootImageTypeMacOSXServer
+ BootImageTypeHardwareDiagnostics
+ // 0x4 - 0x7f are reserved for future use.
+)
+
+// OptionCodeToString maps BSDP OptionCodes to human-readable strings
+// describing what they are.
+var OptionCodeToString = map[dhcpv4.OptionCode]string{
+ OptionMessageType: " Message Type",
+ OptionVersion: " Version",
+ OptionServerIdentifier: " Server Identifier",
+ OptionServerPriority: " Server Priority",
+ OptionReplyPort: " Reply Port",
+ OptionBootImageListPath: "", // Not used
+ OptionDefaultBootImageID: " Default Boot Image ID",
+ OptionSelectedBootImageID: " Selected Boot Image ID",
+ OptionBootImageList: " Boot Image List",
+ OptionNetboot1_0Firmware: " Netboot 1.0 Firmware",
+ OptionBootImageAttributesFilterList: " Boot Image Attributes Filter List",
+ OptionShadowMountPath: " Shadow Mount Path",
+ OptionShadowFilePath: " Shadow File Path",
+ OptionMachineName: " Machine Name",
+}
diff --git a/dhcpv4/client.go b/dhcpv4/client.go
index 55f303d..3d91b84 100644
--- a/dhcpv4/client.go
+++ b/dhcpv4/client.go
@@ -2,14 +2,15 @@ package dhcpv4
import (
"encoding/binary"
- "golang.org/x/net/ipv4"
"net"
"syscall"
"time"
+
+ "golang.org/x/net/ipv4"
)
const (
- maxUDPReceivedPacketSize = 8192 // arbitrary size. Theoretically could be up to 65kb
+ MaxUDPReceivedPacketSize = 8192 // arbitrary size. Theoretically could be up to 65kb
)
type Client struct {
@@ -18,7 +19,7 @@ type Client struct {
Timeout time.Duration
}
-func makeRawBroadcastPacket(payload []byte) ([]byte, error) {
+func MakeRawBroadcastPacket(payload []byte) ([]byte, error) {
udp := make([]byte, 8)
binary.BigEndian.PutUint16(udp[:2], ClientPort)
binary.BigEndian.PutUint16(udp[2:4], ServerPort)
@@ -81,7 +82,7 @@ func (c *Client) Exchange(ifname string, d *DHCPv4) ([]DHCPv4, error) {
}
daddr := syscall.SockaddrInet4{Port: ClientPort, Addr: [4]byte{255, 255, 255, 255}}
- packet, err := makeRawBroadcastPacket(d.ToBytes())
+ packet, err := MakeRawBroadcastPacket(d.ToBytes())
if err != nil {
return conversation, err
}
@@ -97,7 +98,7 @@ func (c *Client) Exchange(ifname string, d *DHCPv4) ([]DHCPv4, error) {
}
defer conn.Close()
- buf := make([]byte, maxUDPReceivedPacketSize)
+ buf := make([]byte, MaxUDPReceivedPacketSize)
oobdata := []byte{} // ignoring oob data
n, _, _, _, err := conn.ReadMsgUDP(buf, oobdata)
offer, err := FromBytes(buf[:n])
@@ -114,7 +115,7 @@ func (c *Client) Exchange(ifname string, d *DHCPv4) ([]DHCPv4, error) {
return conversation, err
}
conversation = append(conversation, *request)
- packet, err = makeRawBroadcastPacket(request.ToBytes())
+ packet, err = MakeRawBroadcastPacket(request.ToBytes())
if err != nil {
return conversation, err
}
@@ -124,7 +125,7 @@ func (c *Client) Exchange(ifname string, d *DHCPv4) ([]DHCPv4, error) {
}
// Acknowledge
- buf = make([]byte, maxUDPReceivedPacketSize)
+ buf = make([]byte, MaxUDPReceivedPacketSize)
n, _, _, _, err = conn.ReadMsgUDP(buf, oobdata)
acknowledge, err := FromBytes(buf[:n])
if err != nil {
diff --git a/dhcpv4/dhcpv4.go b/dhcpv4/dhcpv4.go
index 49eeae1..182d4a4 100644
--- a/dhcpv4/dhcpv4.go
+++ b/dhcpv4/dhcpv4.go
@@ -5,10 +5,11 @@ import (
"encoding/binary"
"errors"
"fmt"
- "github.com/insomniacslk/dhcp/iana"
"log"
"net"
"strings"
+
+ "github.com/insomniacslk/dhcp/iana"
)
// HeaderSize is the DHCPv4 header size in bytes.
@@ -37,6 +38,35 @@ type DHCPv4 struct {
options []Option
}
+// IPv4AddrsForInterface obtains the currently-configured, non-loopback IPv4
+// addresses for iface.
+func IPv4AddrsForInterface(iface *net.Interface) ([]net.IP, error) {
+ addrs, err := iface.Addrs()
+ var v4addrs []net.IP
+ if err != nil {
+ return v4addrs, err
+ }
+ for _, addr := range addrs {
+ var ip net.IP
+ switch v := addr.(type) {
+ case *net.IPAddr:
+ ip = v.IP
+ case *net.IPNet:
+ ip = v.IP
+ }
+
+ if ip == nil || ip.IsLoopback() {
+ continue
+ }
+ ip = ip.To4()
+ if ip == nil {
+ continue
+ }
+ v4addrs = append(v4addrs, ip)
+ }
+ return v4addrs, nil
+}
+
// GenerateTransactionID generates a random 32-bits number suitable for use as
// TransactionID
func GenerateTransactionID() (*uint32, error) {
@@ -105,7 +135,7 @@ func NewDiscoveryForInterface(ifname string) (*DHCPv4, error) {
d.SetBroadcast()
d.AddOption(Option{
Code: OptionDHCPMessageType,
- Data: []byte{1},
+ Data: []byte{byte(MessageTypeDiscover)},
})
d.AddOption(Option{
Code: OptionParameterRequestList,
@@ -116,6 +146,46 @@ func NewDiscoveryForInterface(ifname string) (*DHCPv4, error) {
return d, nil
}
+// NewInformForInterface builds a new DHCPv4 Informational message with default
+// Ethernet HW type and the hardware address obtained from the specified
+// interface. It does NOT put a DHCP End option at the end.
+func NewInformForInterface(ifname string, needsBroadcast bool) (*DHCPv4, error) {
+ d, err := New()
+ if err != nil {
+ return nil, err
+ }
+
+ // get hw addr
+ iface, err := net.InterfaceByName(ifname)
+ if err != nil {
+ return nil, err
+ }
+ d.SetOpcode(OpcodeBootRequest)
+ d.SetHwType(iana.HwTypeEthernet)
+ d.SetHwAddrLen(uint8(len(iface.HardwareAddr)))
+ d.SetClientHwAddr(iface.HardwareAddr)
+
+ if needsBroadcast {
+ d.SetBroadcast()
+ } else {
+ d.SetUnicast()
+ }
+
+ // Set Client IP as iface's currently-configured IP.
+ localIPs, err := IPv4AddrsForInterface(iface)
+ if err != nil || len(localIPs) == 0 {
+ return nil, fmt.Errorf("could not get local IPs for iface %s", ifname)
+ }
+ d.SetClientIPAddr(localIPs[0])
+
+ d.AddOption(Option{
+ Code: OptionDHCPMessageType,
+ Data: []byte{byte(MessageTypeInform)},
+ })
+
+ return d, nil
+}
+
// RequestFromOffer builds a DHCPv4 request from an offer.
func RequestFromOffer(offer DHCPv4) (*DHCPv4, error) {
d, err := New()
@@ -147,7 +217,7 @@ func RequestFromOffer(offer DHCPv4) (*DHCPv4, error) {
d.SetServerIPAddr(serverIP)
d.AddOption(Option{
Code: OptionDHCPMessageType,
- Data: []byte{3},
+ Data: []byte{byte(MessageTypeRequest)},
})
d.AddOption(Option{
Code: OptionRequestedIPAddress,
diff --git a/dhcpv4/dhcpv4_test.go b/dhcpv4/dhcpv4_test.go
index 5a12207..0d569c8 100644
--- a/dhcpv4/dhcpv4_test.go
+++ b/dhcpv4/dhcpv4_test.go
@@ -2,9 +2,10 @@ package dhcpv4
import (
"bytes"
- "github.com/insomniacslk/dhcp/iana"
"net"
"testing"
+
+ "github.com/insomniacslk/dhcp/iana"
)
// NOTE: if one of the following Assert* fails where expected and got values are
diff --git a/dhcpv4/options.go b/dhcpv4/options.go
index 59f2c83..6576c05 100644
--- a/dhcpv4/options.go
+++ b/dhcpv4/options.go
@@ -10,6 +10,7 @@ type OptionCode byte
var MagicCookie = []byte{99, 130, 83, 99}
+// TODO: implement Option as an interface similar to dhcpv6.
type Option struct {
Code OptionCode
Data []byte
@@ -38,18 +39,29 @@ func ParseOption(dataStart []byte) (*Option, error) {
}
}
+// OptionsFromBytes parses a sequence of bytes until the end and builds a list
+// of options from it. The sequence must contain the Magic Cookie. Returns an
+// error if any invalid option or length is found.
func OptionsFromBytes(data []byte) ([]Option, error) {
- // Parse a sequence of bytes until the end and build a list of options from
- // it. The sequence must contain the Magic Cookie.
- // Returns an error if any invalid option or length is found.
- if len(data) < 4 {
+ if len(data) < len(MagicCookie) {
return nil, errors.New("Invalid options: shorter than 4 bytes")
}
- if !bytes.Equal(data[:4], MagicCookie) {
- return nil, errors.New(fmt.Sprintf("Invalid Magic Cookie: %v", data[:4]))
+ if !bytes.Equal(data[:len(MagicCookie)], MagicCookie) {
+ return nil, fmt.Errorf("Invalid Magic Cookie: %v", data[:len(MagicCookie)])
}
+ opts, err := OptionsFromBytesWithoutMagicCookie(data[len(MagicCookie):])
+ if err != nil {
+ return nil, err
+ }
+ return opts, nil
+}
+
+// OptionsFromBytesWithoutMagicCookie parses a sequence of bytes until the end
+// and builds a list of options from it. The sequence should not contain the
+// DHCP magic cookie. Returns an error if any invalid option or length is found.
+func OptionsFromBytesWithoutMagicCookie(data []byte) ([]Option, error) {
options := make([]Option, 0, 10)
- idx := 4
+ idx := 0
for {
if idx == len(data) {
break
@@ -64,9 +76,10 @@ func OptionsFromBytes(data []byte) ([]Option, error) {
return nil, err
}
options = append(options, *opt)
+
+ // Options with zero length have no length byte, so here we handle the
+ // ones with nonzero length
if len(opt.Data) > 0 {
- // options with zero length have no length byte, so here we handle the ones with
- // nonzero length
idx++
}
idx += len(opt.Data)
@@ -74,10 +87,16 @@ func OptionsFromBytes(data []byte) ([]Option, error) {
return options, nil
}
+// OptionsToBytes converts a list of options to a wire-format representation
+// with the DHCP magic cookie prepended.
func OptionsToBytes(options []Option) []byte {
- // Convert a list of options to a wire-format representation. This will
- // include the Magic Cookie
- ret := MagicCookie
+ return append(MagicCookie, OptionsToBytesWithoutMagicCookie(options)...)
+}
+
+// OptionsToBytesWithoutMagicCookie converts a list of options to a wire-format
+// representation.
+func OptionsToBytesWithoutMagicCookie(options []Option) []byte {
+ ret := []byte{}
for _, opt := range options {
ret = append(ret, opt.ToBytes()...)
}
diff --git a/dhcpv4/types.go b/dhcpv4/types.go
index e8a71f5..6ec4d9b 100644
--- a/dhcpv4/types.go
+++ b/dhcpv4/types.go
@@ -3,6 +3,21 @@ package dhcpv4
// values from http://www.networksorcery.com/enp/protocol/dhcp.htm and
// http://www.networksorcery.com/enp/protocol/bootp/options.htm
+// MessageType represents the possible DHCP message types - DISCOVER, OFFER, etc
+type MessageType byte
+
+// DHCP message types
+const (
+ MessageTypeDiscover MessageType = iota + 1
+ MessageTypeOffer
+ MessageTypeRequest
+ MessageTypeDecline
+ MessageTypeAck
+ MessageTypeNak
+ MessageTypeRelease
+ MessageTypeInform
+)
+
// OpcodeType represents a DHCPv4 opcode.
type OpcodeType uint8