diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 09:49:46 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 09:49:46 +0000 |
commit | 50b37d4a27d3295a29afca2286f1a5a086142cec (patch) | |
tree | 9212f763934ee090ef72d823f559f52ce387f268 /src/modules/proto_dhcp | |
parent | Initial commit. (diff) | |
download | freeradius-upstream/3.2.1+dfsg.tar.xz freeradius-upstream/3.2.1+dfsg.zip |
Adding upstream version 3.2.1+dfsg.upstream/3.2.1+dfsgupstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/modules/proto_dhcp')
-rw-r--r-- | src/modules/proto_dhcp/all.mk | 3 | ||||
-rw-r--r-- | src/modules/proto_dhcp/dhcp.c | 2268 | ||||
-rw-r--r-- | src/modules/proto_dhcp/dhcpclient.c | 652 | ||||
-rw-r--r-- | src/modules/proto_dhcp/dhcpclient.mk | 5 | ||||
-rw-r--r-- | src/modules/proto_dhcp/dhcpd.c | 867 | ||||
-rw-r--r-- | src/modules/proto_dhcp/libfreeradius-dhcp.mk | 3 | ||||
-rw-r--r-- | src/modules/proto_dhcp/proto_dhcp.mk | 9 | ||||
-rw-r--r-- | src/modules/proto_dhcp/rlm_dhcp.c | 203 | ||||
-rw-r--r-- | src/modules/proto_dhcp/rlm_dhcp.mk | 4 |
9 files changed, 4014 insertions, 0 deletions
diff --git a/src/modules/proto_dhcp/all.mk b/src/modules/proto_dhcp/all.mk new file mode 100644 index 0000000..12242b6 --- /dev/null +++ b/src/modules/proto_dhcp/all.mk @@ -0,0 +1,3 @@ +ifneq "$(WITH_DHCP)" "no" +SUBMAKEFILES := libfreeradius-dhcp.mk proto_dhcp.mk rlm_dhcp.mk dhcpclient.mk +endif diff --git a/src/modules/proto_dhcp/dhcp.c b/src/modules/proto_dhcp/dhcp.c new file mode 100644 index 0000000..f922d63 --- /dev/null +++ b/src/modules/proto_dhcp/dhcp.c @@ -0,0 +1,2268 @@ +/* + * dhcp.c Functions to send/receive dhcp packets. + * + * Version: $Id$ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + * + * Copyright 2008 The FreeRADIUS server project + * Copyright 2008 Alan DeKok <aland@deployingradius.com> + */ + +RCSID("$Id$") + +#include <freeradius-devel/libradius.h> +#include <freeradius-devel/udpfromto.h> +#include <freeradius-devel/dhcp.h> +#include <freeradius-devel/net.h> + +#ifndef __MINGW32__ +#include <sys/ioctl.h> +#endif + +#ifdef HAVE_SYS_SOCKET_H +#include <sys/socket.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +#ifndef __MINGW32__ +#include <net/if_arp.h> +#endif + +#define DHCP_CHADDR_LEN (16) +#define DHCP_SNAME_LEN (64) +#define DHCP_FILE_LEN (128) +#define DHCP_VEND_LEN (308) +#define DHCP_OPTION_MAGIC_NUMBER (0x63825363) + +#ifndef INADDR_BROADCAST +#define INADDR_BROADCAST INADDR_NONE +#endif + +/* @todo: this is a hack */ +# define DEBUG if (fr_debug_lvl && fr_log_fp) fr_printf_log +# define debug_pair(vp) do { if (fr_debug_lvl && fr_log_fp) { \ + vp_print(fr_log_fp, vp); \ + } \ + } while(0) + +#ifdef HAVE_LINUX_IF_PACKET_H +#define ETH_HDR_SIZE 14 +#define IP_HDR_SIZE 20 +#define UDP_HDR_SIZE 8 +#define ETH_ADDR_LEN 6 +#define ETH_TYPE_IP 0x0800 +#define ETH_P_ALL 0x0003 + +static uint8_t eth_bcast[ETH_ADDR_LEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + +/* Discard raw packets which we are not interested in. Allow to trace why we discard. */ +#define DISCARD_RP(...) { \ + if (fr_debug_lvl > 2) { \ + fprintf(stdout, "dhcpclient: discarding received packet: "); \ + fprintf(stdout, ## __VA_ARGS__); \ + fprintf(stdout, "\n"); \ + } \ + rad_free(&packet); \ + return NULL; \ +} +#endif + +#define VENDORPEC_ADSL 3561 + +typedef struct dhcp_packet_t { + uint8_t opcode; + uint8_t htype; + uint8_t hlen; + uint8_t hops; + uint32_t xid; /* 4 */ + uint16_t secs; /* 8 */ + uint16_t flags; + uint32_t ciaddr; /* 12 */ + uint32_t yiaddr; /* 16 */ + uint32_t siaddr; /* 20 */ + uint32_t giaddr; /* 24 */ + uint8_t chaddr[DHCP_CHADDR_LEN]; /* 28 */ + uint8_t sname[DHCP_SNAME_LEN]; /* 44 */ + uint8_t file[DHCP_FILE_LEN]; /* 108 */ + uint32_t option_format; /* 236 */ + uint8_t options[DHCP_VEND_LEN]; +} dhcp_packet_t; + +typedef struct dhcp_option_t { + uint8_t code; + uint8_t length; +} dhcp_option_t; + +/* + * INADDR_ANY : 68 -> INADDR_BROADCAST : 67 DISCOVER + * INADDR_BROADCAST : 68 <- SERVER_IP : 67 OFFER + * INADDR_ANY : 68 -> INADDR_BROADCAST : 67 REQUEST + * INADDR_BROADCAST : 68 <- SERVER_IP : 67 ACK + */ +static char const *dhcp_header_names[] = { + "DHCP-Opcode", + "DHCP-Hardware-Type", + "DHCP-Hardware-Address-Length", + "DHCP-Hop-Count", + "DHCP-Transaction-Id", + "DHCP-Number-of-Seconds", + "DHCP-Flags", + "DHCP-Client-IP-Address", + "DHCP-Your-IP-Address", + "DHCP-Server-IP-Address", + "DHCP-Gateway-IP-Address", + "DHCP-Client-Hardware-Address", + "DHCP-Server-Host-Name", + "DHCP-Boot-Filename", + + NULL +}; + +static char const *dhcp_message_types[] = { + "invalid", + "DHCP-Discover", + "DHCP-Offer", + "DHCP-Request", + "DHCP-Decline", + "DHCP-Ack", + "DHCP-NAK", + "DHCP-Release", + "DHCP-Inform", + "DHCP-Force-Renew", + "DHCP-Lease-Query", + "DHCP-Lease-Unassigned", + "DHCP-Lease-Unknown", + "DHCP-Lease-Active", + "DHCP-Bulk-Lease-Query", + "DHCP-Lease-Query-Done" +}; + +#define DHCP_MAX_MESSAGE_TYPE (sizeof(dhcp_message_types) / sizeof(dhcp_message_types[0])) + +static int dhcp_header_sizes[] = { + 1, 1, 1, 1, + 4, 2, 2, 4, + 4, 4, 4, + DHCP_CHADDR_LEN, + DHCP_SNAME_LEN, + DHCP_FILE_LEN +}; + + +/* + * Some clients silently ignore responses less than 300 bytes. + */ +#define MIN_PACKET_SIZE (244) +#define DEFAULT_PACKET_SIZE (300) +#define MAX_PACKET_SIZE (1500 - 40) + +#define DHCP_OPTION_FIELD (0) +#define DHCP_FILE_FIELD (1) +#define DHCP_SNAME_FIELD (2) + +static uint8_t *dhcp_get_option(dhcp_packet_t *packet, size_t packet_size, + unsigned int option) +{ + int overload = 0; + int field = DHCP_OPTION_FIELD; + size_t where, size; + uint8_t *data; + + where = 0; + size = packet_size - offsetof(dhcp_packet_t, options); + data = &packet->options[where]; + + while (where < size) { + if (data[0] == 0) { /* padding */ + where++; + continue; + } + + if (data[0] == 255) { /* end of options */ + if ((field == DHCP_OPTION_FIELD) && + (overload & DHCP_FILE_FIELD)) { + data = packet->file; + where = 0; + size = sizeof(packet->file); + field = DHCP_FILE_FIELD; + continue; + + } else if ((field == DHCP_FILE_FIELD) && + (overload & DHCP_SNAME_FIELD)) { + data = packet->sname; + where = 0; + size = sizeof(packet->sname); + field = DHCP_SNAME_FIELD; + continue; + } + + return NULL; + } + + /* + * We MUST have a real option here. + */ + if ((where + 2) > size) { + fr_strerror_printf("Options overflow field at %u", + (unsigned int) (data - (uint8_t *) packet)); + return NULL; + } + + if ((where + 2 + data[1]) > size) { + fr_strerror_printf("Option length overflows field at %u", + (unsigned int) (data - (uint8_t *) packet)); + return NULL; + } + + if (data[0] == option) return data; + + if (data[0] == 52) { /* overload sname and/or file */ + overload = data[3]; + } + + where += data[1] + 2; + data += data[1] + 2; + } + + return NULL; +} + +/* + * DHCPv4 is only for IPv4. Broadcast only works if udpfromto is + * defined. + */ +RADIUS_PACKET *fr_dhcp_recv(int sockfd) +{ + uint32_t magic; + struct sockaddr_storage src; + struct sockaddr_storage dst; + socklen_t sizeof_src; + socklen_t sizeof_dst; + RADIUS_PACKET *packet; + uint16_t port; + uint8_t *code; + ssize_t data_len; + + packet = rad_alloc(NULL, false); + if (!packet) { + fr_strerror_printf("Failed allocating packet"); + return NULL; + } + + packet->data = talloc_zero_array(packet, uint8_t, MAX_PACKET_SIZE); + if (!packet->data) { + fr_strerror_printf("Out of memory"); + rad_free(&packet); + return NULL; + } + + packet->sockfd = sockfd; + sizeof_src = sizeof(src); +#ifdef WITH_UDPFROMTO + sizeof_dst = sizeof(dst); + data_len = recvfromto(sockfd, packet->data, MAX_PACKET_SIZE, 0, + (struct sockaddr *)&src, &sizeof_src, + (struct sockaddr *)&dst, &sizeof_dst); +#else + data_len = recvfrom(sockfd, packet->data, MAX_PACKET_SIZE, 0, + (struct sockaddr *)&src, &sizeof_src); +#endif + + if (data_len <= 0) { + fr_strerror_printf("Failed reading DHCP socket: %s", fr_syserror(errno)); + rad_free(&packet); + return NULL; + } + + packet->data_len = data_len; + if (packet->data_len < MIN_PACKET_SIZE) { + fr_strerror_printf("DHCP packet is too small (%zu < %d)", + packet->data_len, MIN_PACKET_SIZE); + rad_free(&packet); + return NULL; + } + + if (packet->data_len > MAX_PACKET_SIZE) { + fr_strerror_printf("DHCP packet is too large (%zx > %d)", + packet->data_len, MAX_PACKET_SIZE); + rad_free(&packet); + return NULL; + } + + if (packet->data[1] > 1) { + fr_strerror_printf("DHCP can only receive ethernet requests, not type %02x", + packet->data[1]); + rad_free(&packet); + return NULL; + } + + if ((packet->data[2] != 0) && (packet->data[2] != 6)) { + fr_strerror_printf("Ethernet HW length is wrong length %d", + packet->data[2]); + rad_free(&packet); + return NULL; + } + + memcpy(&magic, packet->data + 236, 4); + magic = ntohl(magic); + if (magic != DHCP_OPTION_MAGIC_NUMBER) { + fr_strerror_printf("Cannot do BOOTP"); + rad_free(&packet); + return NULL; + } + + /* + * Create unique keys for the packet. + */ + memcpy(&magic, packet->data + 4, 4); + packet->id = ntohl(magic); + + code = dhcp_get_option((dhcp_packet_t *) packet->data, + packet->data_len, PW_DHCP_MESSAGE_TYPE); + if (!code) { + fr_strerror_printf("No message-type option was found in the packet"); + rad_free(&packet); + return NULL; + } + + if ((code[1] < 1) || (code[2] == 0) || (code[2] >= DHCP_MAX_MESSAGE_TYPE)) { + fr_strerror_printf("Unknown value %d for message-type option", code[2]); + rad_free(&packet); + return NULL; + } + + packet->code = code[2] | PW_DHCP_OFFSET; + + /* + * Create a unique vector from the xid and the client + * hardware address. This is a hack for the RADIUS + * infrastructure in the rest of the server. + * It is also used for de-duplicating DHCP packets + */ + memcpy(packet->vector, packet->data + 4, 4); /* xid */ + memcpy(packet->vector + 4, packet->data + 24, 4); /* giaddr */ + packet->vector[8] = packet->code & 0xff; /* message type */ + memcpy(packet->vector + 9, packet->data + 28, 6); /* chaddr is always 6 for us */ + + /* + * FIXME: for DISCOVER / REQUEST: src_port == dst_port + 1 + * FIXME: for OFFER / ACK : src_port = dst_port - 1 + */ + + sizeof_dst = sizeof(dst); + +#ifndef WITH_UDPFROMTO + /* + * This should never fail... + */ + if (getsockname(sockfd, (struct sockaddr *) &dst, &sizeof_dst) < 0) { + fr_strerror_printf("getsockname failed: %s", fr_syserror(errno)); + rad_free(&packet); + return NULL; + } +#endif + + fr_sockaddr2ipaddr(&dst, sizeof_dst, &packet->dst_ipaddr, &port); + packet->dst_port = port; + + fr_sockaddr2ipaddr(&src, sizeof_src, &packet->src_ipaddr, &port); + packet->src_port = port; + + if (fr_debug_lvl > 1) { + char type_buf[64]; + char const *name = type_buf; + char src_ip_buf[256], dst_ip_buf[256]; + + if ((packet->code >= PW_DHCP_DISCOVER) && + (packet->code < (1024 + DHCP_MAX_MESSAGE_TYPE))) { + name = dhcp_message_types[packet->code - PW_DHCP_OFFSET]; + } else { + snprintf(type_buf, sizeof(type_buf), "%d", + packet->code - PW_DHCP_OFFSET); + } + + DEBUG("Received %s of Id %08x from %s:%d to %s:%d\n", + name, (unsigned int) packet->id, + inet_ntop(packet->src_ipaddr.af, + &packet->src_ipaddr.ipaddr, + src_ip_buf, sizeof(src_ip_buf)), + packet->src_port, + inet_ntop(packet->dst_ipaddr.af, + &packet->dst_ipaddr.ipaddr, + dst_ip_buf, sizeof(dst_ip_buf)), + packet->dst_port); + } + + return packet; +} + + +/* + * Send a DHCP packet. + */ +int fr_dhcp_send(RADIUS_PACKET *packet) +{ + struct sockaddr_storage dst; + socklen_t sizeof_dst; +#ifdef WITH_UDPFROMTO + struct sockaddr_storage src; + socklen_t sizeof_src; + + fr_ipaddr2sockaddr(&packet->src_ipaddr, packet->src_port, + &src, &sizeof_src); +#endif + + fr_ipaddr2sockaddr(&packet->dst_ipaddr, packet->dst_port, + &dst, &sizeof_dst); + + if (packet->data_len == 0) { + fr_strerror_printf("No data to send"); + return -1; + } + + if (fr_debug_lvl > 1) { + char type_buf[64]; + char const *name = type_buf; +#ifdef WITH_UDPFROMTO + char src_ip_buf[INET6_ADDRSTRLEN]; +#endif + char dst_ip_buf[INET6_ADDRSTRLEN]; + + if ((packet->code >= PW_DHCP_DISCOVER) && + (packet->code < (1024 + DHCP_MAX_MESSAGE_TYPE))) { + name = dhcp_message_types[packet->code - PW_DHCP_OFFSET]; + } else { + snprintf(type_buf, sizeof(type_buf), "%d", + packet->code - PW_DHCP_OFFSET); + } + + DEBUG( +#ifdef WITH_UDPFROMTO + "Sending %s Id %08x from %s:%d to %s:%d\n", +#else + "Sending %s Id %08x to %s:%d\n", +#endif + name, (unsigned int) packet->id, +#ifdef WITH_UDPFROMTO + inet_ntop(packet->src_ipaddr.af, &packet->src_ipaddr.ipaddr, src_ip_buf, sizeof(src_ip_buf)), + packet->src_port, +#endif + inet_ntop(packet->dst_ipaddr.af, &packet->dst_ipaddr.ipaddr, dst_ip_buf, sizeof(dst_ip_buf)), + packet->dst_port); + } + +#ifndef WITH_UDPFROMTO + /* + * Assume that the packet is encoded before sending it. + */ + return sendto(packet->sockfd, packet->data, packet->data_len, 0, + (struct sockaddr *)&dst, sizeof_dst); +#else + + return sendfromto(packet->sockfd, packet->data, packet->data_len, 0, + (struct sockaddr *)&src, sizeof_src, + (struct sockaddr *)&dst, sizeof_dst); +#endif +} + +static int fr_dhcp_attr2vp(TALLOC_CTX *ctx, VALUE_PAIR **vp_p, uint8_t const *p, size_t alen); + +/** Returns the number of array members for arrays with fixed element sizes + * + */ +static int fr_dhcp_array_members(size_t *len, DICT_ATTR const *da) +{ + int num_entries = 1; + + if (!len || !da) return -1; + + /* + * Could be an array of bytes, integers, etc. + */ + if (da->flags.array) switch (da->type) { + case PW_TYPE_BYTE: + num_entries = *len; + *len = 1; + break; + + case PW_TYPE_SHORT: /* ignore any trailing data */ + num_entries = *len >> 1; + *len = 2; + break; + + case PW_TYPE_IPV4_ADDR: + case PW_TYPE_INTEGER: + case PW_TYPE_DATE: /* ignore any trailing data */ + num_entries = *len >> 2; + *len = 4; + break; + + case PW_TYPE_IPV6_ADDR: + num_entries = *len >> 4; + *len = 16; + break; + + default: + break; + } + + return num_entries; +} + +/** RFC 4243 Vendor Specific Suboptions + * + * Vendor specific suboptions are in the format. + @verbatim + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Enterprise Number 0 | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Len 0 | / + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + / Suboption Data 0 / + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Enterprise Number n | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Len n | / + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + / Suboption Data n / + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + @endverbatim + * + * So although the vendor is identified, the format of the data isn't + * specified so we can't actually resolve the suboption to an + * attribute. For now, we just convert it to an attribute of + * DHCP-Vendor-Specific-Information with raw octets contents. + */ + + +/** Decode DHCP suboptions + * + * @param[in,out] tlv to decode. *tlv will be set to the head of the list of suboptions and original will be freed. + * @param[in] ctx context to alloc new attributes in. + * @param[in] data to parse. + * @param[in] len length of data to parse. + */ +static int fr_dhcp_decode_suboption(TALLOC_CTX *ctx, VALUE_PAIR **tlv, uint8_t const *data, size_t len) +{ + uint8_t const *p, *q; + VALUE_PAIR *head, *vp; + vp_cursor_t cursor; + + /* + * TLV must already point to a VALUE_PAIR. + */ + VERIFY_VP(*tlv); + + /* + * Take a pass at parsing it. + */ + p = data; + q = data + len; + while (p < q) { + /* + * RFC 3046 is very specific about not allowing termination + * with a 255 sub-option. But it's required for decoding + * option 43, and vendors will probably screw it up + * anyway. + */ + if (*p == 0) { + p++; + continue; + } + if (*p == 255) { + q--; + break; + } + + /* + * Check if reading length would take us past the end of the buffer + */ + if (++p >= q) goto malformed; + p += p[0]; + + /* + * Check if length > the length of the buffer we have left + */ + if (p >= q) goto malformed; + p++; + } + + /* + * Got here... must be well formed. + */ + head = NULL; + fr_cursor_init(&cursor, &head); + + p = data; + while (p < q) { + uint8_t const *a_p; + size_t a_len; + int num_entries, i; + + DICT_ATTR const *da; + uint32_t attr; + + /* + * Not enough room for the option header, it's a + * bad packet. + */ + if ((p + 2) > (data + len)) { + fr_pair_list_free(&head); + return -1; + } + + /* + * Not enough room for the option header + data, + * it's a bad packet. + */ + if ((p + 2 + p[1]) > (data + len)) { + fr_pair_list_free(&head); + return -1; + } + + /* + * The initial OID string looks like: + * <iana>.0 + * + * If <iana>.0 is type TLV then we attempt to decode its contents as more + * DHCP suboptions, which gives us: + * <iana>.<attr> + * + * If <iana>.0 is not defined in the dictionary or is type octets, we leave + * the attribute as is. + */ + attr = (*tlv)->da->attr ? ((*tlv)->da->attr | (p[0] << 8)) : p[0]; + + /* + * Use the vendor of the parent TLV which is not necessarily + * DHCP_MAGIC_VENDOR. + * + * Note: This does not deal with dictionary numbering clashes. If + * the vendor uses different numbers for DHCP suboptions and RADIUS + * attributes then it's time to break out %{hex:} and regular + * expressions. + */ + da = dict_attrbyvalue(attr, (*tlv)->da->vendor); + if (!da) { + da = dict_unknown_afrom_fields(ctx, attr, (*tlv)->da->vendor); + if (!da) { + fr_pair_list_free(&head); + return -1; + } + } + + a_len = p[1]; + a_p = p + 2; + num_entries = fr_dhcp_array_members(&a_len, da); + for (i = 0; i < num_entries; i++) { + vp = fr_pair_afrom_da(ctx, da); + if (!vp) { + fr_pair_list_free(&head); + return -1; + } + vp->op = T_OP_EQ; + fr_pair_steal(ctx, vp); /* for unknown attributes hack */ + + if (fr_dhcp_attr2vp(ctx, &vp, a_p, a_len) < 0) { + dict_attr_free(&da); + fr_pair_list_free(&head); + goto malformed; + } + fr_cursor_merge(&cursor, vp); + + a_p += a_len; + } + + dict_attr_free(&da); /* for unknown attributes hack */ + + p += 2 + p[1]; /* code (1) + len (1) + suboption len (n)*/ + } + + /* + * The caller allocated a TLV, if decoding it generated + * additional attributes, we now need to free it, and write + * the HEAD of our new list of attributes in its place. + */ + if (head) { + vp_cursor_t tlv_cursor; + + /* + * Free the old TLV attribute + */ + TALLOC_FREE(*tlv); + + /* + * Cursor not necessary but means we don't have to set + * ->next directly. + */ + fr_cursor_init(&tlv_cursor, tlv); + fr_cursor_merge(&tlv_cursor, head); + } + + return 0; + +malformed: + fr_pair_to_unknown(*tlv); + fr_pair_value_memcpy(*tlv, data, len); + + return 0; +} + +/* + * Decode ONE value into a VP + */ +static int fr_dhcp_attr2vp(TALLOC_CTX *ctx, VALUE_PAIR **vp_p, uint8_t const *data, size_t len) +{ + VALUE_PAIR *vp = *vp_p; + VERIFY_VP(vp); + + switch (vp->da->type) { + case PW_TYPE_BYTE: + if (len != 1) goto raw; + vp->vp_byte = data[0]; + break; + + case PW_TYPE_SHORT: + if (len != 2) goto raw; + memcpy(&vp->vp_short, data, 2); + vp->vp_short = ntohs(vp->vp_short); + break; + + case PW_TYPE_INTEGER: + if (len != 4) goto raw; + memcpy(&vp->vp_integer, data, 4); + vp->vp_integer = ntohl(vp->vp_integer); + break; + + case PW_TYPE_IPV4_ADDR: + if (len != 4) goto raw; + /* + * Keep value in Network Order! + */ + memcpy(&vp->vp_ipaddr, data, 4); + vp->vp_length = 4; + break; + + /* + * In DHCPv4, string options which can also be arrays, + * have their values '\0' delimited. + */ + case PW_TYPE_STRING: + { + uint8_t const *p; + uint8_t const *q, *end; + vp_cursor_t cursor; + + p = data; + q = end = data + len; + + if (!vp->da->flags.array) { + fr_pair_value_bstrncpy(vp, (char const *)p, q - p); + break; + } + + /* + * Initialise the cursor as we may be inserting + * multiple additional VPs + */ + fr_cursor_init(&cursor, vp_p); + while (p < end) { + q = memchr(p, '\0', end - p); + /* Malformed but recoverable */ + if (!q) q = end; + + fr_pair_value_bstrncpy(vp, (char const *)p, q - p); + p = q + 1; + + if (p >= end) break; + + /* Need another VP for the next round */ + vp = fr_pair_afrom_da(ctx, vp->da); + if (!vp) { + fr_pair_list_free(vp_p); + return -1; + } + fr_cursor_insert(&cursor, vp); + } + } + break; + + case PW_TYPE_ETHERNET: + memcpy(vp->vp_ether, data, sizeof(vp->vp_ether)); + vp->vp_length = sizeof(vp->vp_ether); + break; + + /* + * Value doesn't match up with attribute type, overwrite the + * vp's original DICT_ATTR with an unknown one. + */ + raw: + if (fr_pair_to_unknown(vp) < 0) return -1; + /* FALL-THROUGH */ + + case PW_TYPE_OCTETS: + if (len > 255) return -1; + fr_pair_value_memcpy(vp, data, len); + break; + + /* + * For option 82 et al... + */ + case PW_TYPE_TLV: + return fr_dhcp_decode_suboption(ctx, vp_p, data, len); + + default: + fr_strerror_printf("Internal sanity check %d %d", vp->da->type, __LINE__); + return -1; + } /* switch over type */ + + vp->vp_length = len; + return 0; +} + +/** Decode DHCP options + * + * @param[in,out] out Where to write the decoded options. + * @param[in] ctx context to alloc new attributes in. + * @param[in] data to parse. + * @param[in] len of data to parse. + */ +ssize_t fr_dhcp_decode_options(TALLOC_CTX *ctx, VALUE_PAIR **out, uint8_t const *data, size_t len) +{ + VALUE_PAIR *vp; + vp_cursor_t cursor; + uint8_t const *p, *q; + + *out = NULL; + fr_cursor_init(&cursor, out); + + /* + * FIXME: This should also check sname && file fields. + * See the dhcp_get_option() function above. + */ + p = data; + q = data + len; + while (p < q) { + uint8_t const *a_p; + size_t a_len; + int num_entries, i; + + DICT_ATTR const *da; + + if (*p == 0) { /* 0x00 - Padding option */ + p++; + continue; + } + + if (*p == 255) { /* 0xff - End of options signifier */ + break; + } + + if ((p + 2) > q) break; + + a_len = p[1]; + a_p = p + 2; + + /* + * Ensure we've not been given a bad length value + */ + if ((a_p + a_len) > q) { + fr_strerror_printf("Length field value of option %u is incorrect. " + "Got %u bytes, expected <= %zu bytes", p[0], p[1], q - a_p); + fr_pair_list_free(out); + return -1; + } + + /* + * Unknown attribute, create an octets type + * attribute with the contents of the sub-option. + */ + da = dict_attrbyvalue(p[0], DHCP_MAGIC_VENDOR); + if (!da) { + da = dict_unknown_afrom_fields(ctx, p[0], DHCP_MAGIC_VENDOR); + if (!da) { + fr_pair_list_free(out); + return -1; + } + vp = fr_pair_afrom_da(ctx, da); + if (!vp) { + fr_pair_list_free(out); + return -1; + } + fr_pair_value_memcpy(vp, a_p, a_len); + fr_cursor_insert(&cursor, vp); + + goto next; + } + + /* + * Decode ADSL Forum vendor-specific options. + */ + if ((p[0] == 125) && (p[1] > 6) && (p[2] == 0) && (p[3] == 0) && (p[4] == 0x0d) && (p[5] == 0xe9) && + (p[6] + 5 == p[1])) { + da = dict_attrbyvalue(255, VENDORPEC_ADSL); + if (!da) goto normal; + + vp = fr_pair_afrom_da(ctx, da); + if (!vp) { + fr_pair_list_free(out); + return -1; + } + + (void) fr_dhcp_decode_suboption(ctx, &vp, p + 7, p[6]); + if (vp) fr_cursor_merge(&cursor, vp); + goto next; + } + + normal: + /* + * Array type sub-option create a new VALUE_PAIR + * for each array element. + */ + num_entries = fr_dhcp_array_members(&a_len, da); + for (i = 0; i < num_entries; i++) { + vp = fr_pair_afrom_da(ctx, da); + if (!vp) { + fr_pair_list_free(out); + return -1; + } + vp->op = T_OP_EQ; + + if (fr_dhcp_attr2vp(ctx, &vp, a_p, a_len) < 0) { + fr_pair_list_free(&vp); + fr_pair_list_free(out); + return -1; + } + fr_cursor_merge(&cursor, vp); + a_p += a_len; + } /* loop over array entries */ + next: + p += 2 + p[1]; /* code (1) + len (1) + option len (n)*/ + } /* loop over the entire packet */ + + return p - data; +} + +int fr_dhcp_decode(RADIUS_PACKET *packet) +{ + size_t i; + uint8_t *p; + uint32_t giaddr; + vp_cursor_t cursor; + VALUE_PAIR *head = NULL, *vp; + VALUE_PAIR *maxms, *mtu, *netaddr; + + fr_cursor_init(&cursor, &head); + p = packet->data; + + if ((fr_debug_lvl > 2) && fr_log_fp) { + for (i = 0; i < packet->data_len; i++) { + if ((i & 0x0f) == 0x00) fprintf(fr_log_fp, "%d: ", (int) i); + fprintf(fr_log_fp, "%02x ", packet->data[i]); + if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n"); + } + fprintf(fr_log_fp, "\n"); + } + + if (packet->data[1] > 1) { + fr_strerror_printf("Packet is not Ethernet: %u", + packet->data[1]); + return -1; + } + + /* + * Decode the header. + */ + for (i = 0; i < 14; i++) { + + vp = fr_pair_afrom_num(packet, 256 + i, DHCP_MAGIC_VENDOR); + if (!vp) { + char buffer[256]; + strlcpy(buffer, fr_strerror(), sizeof(buffer)); + fr_strerror_printf("Cannot decode packet due to internal error: %s", buffer); + fr_pair_list_free(&head); + return -1; + } + + /* + * If chaddr != 6 bytes it's probably not ethernet, and we should store + * it as an opaque type (octets). + */ + if (i == 11) { + /* + * Skip chaddr if it doesn't exist. + */ + if ((packet->data[1] == 0) || (packet->data[2] == 0)) continue; + + if ((packet->data[1] == 1) && (packet->data[2] != sizeof(vp->vp_ether))) { + DICT_ATTR const *da = dict_unknown_afrom_fields(packet, vp->da->attr, vp->da->vendor); + if (!da) { + return -1; + } + vp->da = da; + } + } + + switch (vp->da->type) { + case PW_TYPE_BYTE: + vp->vp_byte = p[0]; + vp->vp_length = 1; + break; + + case PW_TYPE_SHORT: + vp->vp_short = (p[0] << 8) | p[1]; + vp->vp_length = 2; + break; + + case PW_TYPE_INTEGER: + memcpy(&vp->vp_integer, p, 4); + vp->vp_integer = ntohl(vp->vp_integer); + vp->vp_length = 4; + break; + + case PW_TYPE_IPV4_ADDR: + memcpy(&vp->vp_ipaddr, p, 4); + vp->vp_length = 4; + break; + + case PW_TYPE_STRING: + /* + * According to RFC 2131, these are null terminated strings. + * We don't trust everyone to abide by the RFC, though. + */ + if (*p != '\0') { + uint8_t *end; + int len; + end = memchr(p, '\0', dhcp_header_sizes[i]); + len = end ? end - p : dhcp_header_sizes[i]; + fr_pair_value_bstrncpy(vp, p, len); + } + if (vp->vp_length == 0) fr_pair_list_free(&vp); + break; + + case PW_TYPE_OCTETS: + if (packet->data[2] == 0) break; + + fr_pair_value_memcpy(vp, p, packet->data[2]); + break; + + case PW_TYPE_ETHERNET: + memcpy(vp->vp_ether, p, sizeof(vp->vp_ether)); + vp->vp_length = sizeof(vp->vp_ether); + break; + + default: + fr_strerror_printf("BAD TYPE %d", vp->da->type); + fr_pair_list_free(&vp); + break; + } + p += dhcp_header_sizes[i]; + + if (!vp) continue; + + debug_pair(vp); + fr_cursor_insert(&cursor, vp); + } + + /* + * Loop over the options. + */ + + /* + * Nothing uses tail after this call, if it does in the future + * it'll need to find the new tail... + */ + { + VALUE_PAIR *options = NULL; + vp_cursor_t options_cursor; + + if (fr_dhcp_decode_options(packet, &options, packet->data + 240, packet->data_len - 240) < 0) { + return -1; + } + + if (options) { + for (vp = fr_cursor_init(&options_cursor, &options); + vp; + vp = fr_cursor_next(&options_cursor)) { + debug_pair(vp); + } + fr_cursor_merge(&cursor, options); + } + } + + /* + * If DHCP request, set ciaddr to zero. + */ + + /* + * Set broadcast flag for broken vendors, but only if + * giaddr isn't set. + */ + memcpy(&giaddr, packet->data + 24, sizeof(giaddr)); + if (giaddr == htonl(INADDR_ANY)) { + /* + * DHCP-Message-Type is request + */ + vp = fr_pair_find_by_num(head, 53, DHCP_MAGIC_VENDOR, TAG_ANY); + if (vp && vp->vp_byte == 3) { + /* + * Vendor is "MSFT 98" + */ + vp = fr_pair_find_by_num(head, 60, DHCP_MAGIC_VENDOR, TAG_ANY); + if (vp && (vp->vp_length >= 7) && (memcmp(vp->vp_octets, "MSFT 98", 7) == 0)) { + vp = fr_pair_find_by_num(head, 262, DHCP_MAGIC_VENDOR, TAG_ANY); + + /* + * Reply should be broadcast. + */ + if (vp) vp->vp_short |= 0x8000; + packet->data[10] |= 0x80; + } + } + } + + /* + * Determine the address to use in looking up which subnet the + * client belongs to based on packet data. The sequence here + * is based on ISC DHCP behaviour and RFCs 3527 and 3011. We + * store the found address in an internal attribute of 274 - + * DHCP-Network-Subnet. This is stored as an IPv4 prefix + * with a /32 netmask allowing "closest containing subnet" + * matching in rlm_files + */ + vp = fr_pair_afrom_num(packet, 274, DHCP_MAGIC_VENDOR); + /* + * First look for Relay-Link-Selection - option 82, suboption 5 + */ + netaddr = fr_pair_find_by_num(head, (82 | (5 << 8)), DHCP_MAGIC_VENDOR, TAG_ANY); + if (!netaddr) { + /* + * Next try Subnet-Selection-Option - option 118 + */ + netaddr = fr_pair_find_by_num(head, 118, DHCP_MAGIC_VENDOR, TAG_ANY); + } + if (!netaddr) { + if (giaddr != htonl(INADDR_ANY)) { + /* + * Gateway address is set - use that one + */ + memcpy(&vp->vp_ipv4prefix[2], packet->data + 24, 4); + } else { + /* + * else, store client address whatever it is + */ + memcpy(&vp->vp_ipv4prefix[2], packet->data + 12, 4); + } + } else { + /* + * Store whichever address we've found from options + */ + memcpy(&vp->vp_ipv4prefix[2], &netaddr->vp_ipaddr, 4); + } + /* + * Set the netmask to /32 + */ + vp->vp_ipv4prefix[0] = 0; + vp->vp_ipv4prefix[1] = 32; + + debug_pair(vp); + fr_cursor_insert(&cursor, vp); + + /* + * FIXME: Nuke attributes that aren't used in the normal + * header for discover/requests. + */ + packet->vps = head; + + /* + * Client can request a LARGER size, but not a smaller + * one. They also cannot request a size larger than MTU. + */ + maxms = fr_pair_find_by_num(packet->vps, 57, DHCP_MAGIC_VENDOR, TAG_ANY); + mtu = fr_pair_find_by_num(packet->vps, 26, DHCP_MAGIC_VENDOR, TAG_ANY); + + if (mtu && (mtu->vp_integer < DEFAULT_PACKET_SIZE)) { + fr_strerror_printf("DHCP Fatal: Client says MTU is smaller than minimum permitted by the specification"); + return -1; + } + + if (maxms && (maxms->vp_integer < DEFAULT_PACKET_SIZE)) { + fr_strerror_printf("DHCP WARNING: Client says maximum message size is smaller than minimum permitted by the specification: fixing it"); + maxms->vp_integer = DEFAULT_PACKET_SIZE; + } + + if (maxms && mtu && (maxms->vp_integer > mtu->vp_integer)) { + fr_strerror_printf("DHCP WARNING: Client says MTU is smaller than maximum message size: fixing it"); + maxms->vp_integer = mtu->vp_integer; + } + + if (fr_debug_lvl) fflush(stdout); + + return 0; +} + + +int8_t fr_dhcp_attr_cmp(void const *a, void const *b) +{ + VALUE_PAIR const *my_a = a; + VALUE_PAIR const *my_b = b; + + VERIFY_VP(my_a); + VERIFY_VP(my_b); + + /* + * ADSL Forum vendor-specific options after others to remain grouped + */ + if ((my_a->da->vendor == VENDORPEC_ADSL) && (my_b->da->vendor != VENDORPEC_ADSL)) return +1; + if ((my_a->da->vendor != VENDORPEC_ADSL) && (my_b->da->vendor == VENDORPEC_ADSL)) return -1; + + /* + * DHCP-Message-Type is first, for simplicity. + */ + if ((my_a->da->attr == PW_DHCP_MESSAGE_TYPE) && (my_b->da->attr != PW_DHCP_MESSAGE_TYPE)) return -1; + if ((my_a->da->attr != PW_DHCP_MESSAGE_TYPE) && (my_b->da->attr == PW_DHCP_MESSAGE_TYPE)) return +1; + + /* + * Relay-Agent is last + */ + if ((my_a->da->attr == PW_DHCP_OPTION_82) && (my_b->da->attr != PW_DHCP_OPTION_82)) return +1; + if ((my_a->da->attr != PW_DHCP_OPTION_82) && (my_b->da->attr == PW_DHCP_OPTION_82)) return -1; + + if (my_a->da->attr < my_b->da->attr) return -1; + if (my_a->da->attr > my_b->da->attr) return 1; + + return 0; +} + +/** Write DHCP option value into buffer + * + * Does not include DHCP option length or number. + * + * @param out where to write the DHCP option. + * @param outlen length of output buffer. + * @param vp option to encode. + * @return the length of data writen, -1 if out of buffer, -2 if unsupported type. + */ +static ssize_t fr_dhcp_vp2data(uint8_t *out, size_t outlen, VALUE_PAIR *vp) +{ + uint32_t lvalue; + uint8_t *p = out; + + if (outlen < vp->vp_length) { + return -1; + } + + switch (vp->da->type) { + case PW_TYPE_BYTE: + *p = vp->vp_byte; + break; + + case PW_TYPE_SHORT: + p[0] = (vp->vp_short >> 8) & 0xff; + p[1] = vp->vp_short & 0xff; + break; + + case PW_TYPE_INTEGER: + lvalue = htonl(vp->vp_integer); + memcpy(p, &lvalue, 4); + break; + + case PW_TYPE_IPV4_ADDR: + memcpy(p, &vp->vp_ipaddr, 4); + break; + + case PW_TYPE_ETHERNET: + memcpy(p, vp->vp_ether, 6); + break; + + case PW_TYPE_STRING: + memcpy(p, vp->vp_strvalue, vp->vp_length); + break; + + case PW_TYPE_OCTETS: + memcpy(p, vp->vp_octets, vp->vp_length); + break; + + default: + fr_strerror_printf("Unsupported option type %d", vp->da->type); + return -2; + } + + return vp->vp_length; +} + +/** Create a new TLV attribute from multiple sub options + * + * @param[in,out] out buffer to write the data + * @param[out] outlen length of the output buffer + * @param[in,out] cursor should be set to the start of the list of TLV attributes. + * Will be advanced to the first non-TLV attribute. + * @return length of data encoded, or -1 on error + */ +static ssize_t fr_dhcp_vp2data_tlv(uint8_t *out, ssize_t outlen, vp_cursor_t *cursor) +{ + ssize_t len; + unsigned int parent; /* Parent attribute of suboption */ + uint8_t attr = 0; + uint8_t *p, *opt_len; + vp_cursor_t tlv_cursor; + VALUE_PAIR *vp; + +#define SUBOPTION_PARENT(_x) (_x & 0xffff00ff) +#define SUBOPTION_ATTR(_x) ((_x & 0xff00) >> 8) + + vp = fr_cursor_current(cursor); + if (!vp) return -1; + + parent = SUBOPTION_PARENT(vp->da->attr); + + /* + * Remember where we started off. + */ + fr_cursor_copy(&tlv_cursor, cursor); + + /* + * Loop over TLVs to determine how much memory we need to allocate + * + * We advanced the tlv_cursor we were passed, so if we + * fail encoding, the tlv_cursor is at the right position + * for the next potentially encodable attr. + */ + len = 0; + for (vp = fr_cursor_current(&tlv_cursor); + vp && vp->da->flags.is_tlv && (SUBOPTION_PARENT(vp->da->attr) == parent); + vp = fr_cursor_next(&tlv_cursor)) { + if (SUBOPTION_ATTR(vp->da->attr) == 0) { + fr_strerror_printf("Invalid attribute number 0"); + return -1; + } + + /* + * If it's not an array type or is an array type, + * but is not the same as the previous attribute, + * we add 2 for the additional sub-option header + * bytes. + */ + if (!vp->da->flags.array || (SUBOPTION_ATTR(vp->da->attr) != attr)) { + attr = SUBOPTION_ATTR(vp->da->attr); + len += 2; + } + len += vp->vp_length; + } + + if (len > outlen) { + fr_strerror_printf("Insufficient room for suboption"); + return -1; + } + + attr = 0; + opt_len = NULL; + p = out; + + for (vp = fr_cursor_current(cursor); + vp && vp->da->flags.is_tlv && (SUBOPTION_PARENT(vp->da->attr) == parent); + vp = fr_cursor_next(cursor)) { + /* Don't write out the header, were packing array options */ + if (!opt_len || !vp->da->flags.array || (attr != SUBOPTION_ATTR(vp->da->attr))) { + attr = SUBOPTION_ATTR(vp->da->attr); + *p++ = attr; + opt_len = p++; + *opt_len = 0; + } + + len = fr_dhcp_vp2data(p, out + outlen - p, vp); + if ((len < 0) || (len > 255)) { + return -1; + } + + debug_pair(vp); + *opt_len += len; + p += len; + }; + + return p - out; +} + +static ssize_t fr_dhcp_encode_adsl(uint8_t *out, size_t outlen, vp_cursor_t *cursor) +{ + VALUE_PAIR *vp; + uint8_t *p; + size_t room; + + if (outlen <= (2 + 4 + 1)) return -1; + + out[0] = 125; /* Vendor-Specific */ + out[1] = 5; /* vendorpec + 1 octet of length */ + out[2] = 0; + out[3] = 0; + out[4] = 0x0d; + out[5] = 0xe9; /* ADSL forum vendorpec */ + out[6] = 0; /* vendor-specific length */ + + p = out + 7; + room = outlen - 7; + + for (vp = fr_cursor_current(cursor); + ((vp != NULL) && (vp->da->vendor == VENDORPEC_ADSL) && + (vp->da->attr > 255) && ((vp->da->attr & 0xff) == 0xff)); + vp = fr_cursor_next(cursor)) { + ssize_t length; + + /* + * Silently discard options when there isn't enough room. + */ + if (room < 2) break; + + p[0] = (vp->da->attr >> 8) & 0xff; + + length = fr_dhcp_vp2data(p + 2, room - 2, vp); + if (length < 0) break; /* not enough room */ + if (length > 255) break; /* too much data */ + + p[1] = length; + + length += 2; /* include the attribute header */ + + /* + * We don't (yet) split Vendor-Specific. So if + * there's too much data, just discard the extra + * data. + */ + if ((out[1] + length) > 255) break; + + out[1] += length; + out[6] += length; + p += length; + room -= length; + } + + /* + * Don't encode options with no data. + */ + if (out[1] == 5) return 0; + + return out[1] + 2; +} + +/** Encode a DHCP option and any sub-options. + * + * @param out Where to write encoded DHCP attributes. + * @param outlen Length of out buffer. + * @param ctx to use for any allocated memory. + * @param cursor with current VP set to the option to be encoded. Will be advanced to the next option to encode. + * @return > 0 length of data written, < 0 error, 0 not valid option (skipping). + */ +ssize_t fr_dhcp_encode_option(UNUSED TALLOC_CTX *ctx, uint8_t *out, size_t outlen, vp_cursor_t *cursor) +{ + VALUE_PAIR *vp; + DICT_ATTR const *previous; + uint8_t *opt_len, *p = out; + size_t freespace = outlen; + ssize_t len; + + vp = fr_cursor_current(cursor); + if (!vp) return -1; + + if (vp->da->vendor != DHCP_MAGIC_VENDOR) { + if ((vp->da->vendor == VENDORPEC_ADSL) && + (vp->da->attr > 255) && ((vp->da->attr & 0xff) == 0xff)) { + return fr_dhcp_encode_adsl(out, outlen, cursor); + } + goto next; /* not a DHCP option */ + } + if (vp->da->attr == PW_DHCP_MESSAGE_TYPE) goto next; /* already done */ + if ((vp->da->attr > 255) && (DHCP_BASE_ATTR(vp->da->attr) != PW_DHCP_OPTION_82)) goto next; + + if (vp->da->flags.extended) { + next: + fr_strerror_printf("Attribute \"%s\" is not a DHCP option", vp->da->name); + fr_cursor_next(cursor); + return 0; + } + + /* Write out the option number */ + *(p++) = vp->da->attr & 0xff; + + /* Pointer to the length field of the option */ + opt_len = p++; + + /* Zero out the option's length field */ + *opt_len = 0; + + /* We just consumed two bytes for the header */ + freespace -= 2; + + /* DHCP options with the same number get coalesced into a single option */ + do { + /* + * Sub-option encoder will encode the data and + * advance the cursor. + */ + if (vp->da->flags.is_tlv) { + len = fr_dhcp_vp2data_tlv(p, freespace, cursor); + previous = NULL; + + } else { + len = fr_dhcp_vp2data(p, freespace, vp); + if (len >= 0) debug_pair(vp); + fr_cursor_next(cursor); + previous = vp->da; + } + + if (len < 0) return len; + + if ((*opt_len + len) > 255) { + fr_strerror_printf("Skipping \"%s\": Option splitting not supported " + "(option > 255 bytes)", vp->da->name); + return 0; + } + + p += len; + *opt_len += len; + freespace -= len; + + } while ((vp = fr_cursor_current(cursor)) && previous && (previous == vp->da) && vp->da->flags.array); + + return p - out; +} + +int fr_dhcp_encode(RADIUS_PACKET *packet) +{ + unsigned int i; + uint8_t *p; + vp_cursor_t cursor; + VALUE_PAIR *vp; + uint32_t lvalue; + uint16_t svalue; + size_t dhcp_size; + ssize_t len; +#ifndef NDEBUG + char const *name; +# ifdef WITH_UDPFROMTO + char src_ip_buf[256]; +# endif + char dst_ip_buf[256]; +#endif + + if (packet->data) return 0; + + packet->data_len = MAX_PACKET_SIZE; + packet->data = talloc_zero_array(packet, uint8_t, packet->data_len); + + /* XXX Ugly ... should be set by the caller */ + if (packet->code == 0) packet->code = PW_DHCP_NAK; + + /* store xid */ + if ((vp = fr_pair_find_by_num(packet->vps, 260, DHCP_MAGIC_VENDOR, TAG_ANY))) { + packet->id = vp->vp_integer; + } else { + packet->id = fr_rand(); + } + +#ifndef NDEBUG + if ((packet->code >= PW_DHCP_DISCOVER) && + (packet->code < (1024 + DHCP_MAX_MESSAGE_TYPE))) { + name = dhcp_message_types[packet->code - PW_DHCP_OFFSET]; + } else { + name = "?Unknown?"; + } + + DEBUG( +# ifdef WITH_UDPFROMTO + "Encoding %s of id %08x from %s:%d to %s:%d\n", +# else + "Encoding %s of id %08x to %s:%d\n", +# endif + name, (unsigned int) packet->id, +# ifdef WITH_UDPFROMTO + inet_ntop(packet->src_ipaddr.af, + &packet->src_ipaddr.ipaddr, + src_ip_buf, sizeof(src_ip_buf)), + packet->src_port, +# endif + inet_ntop(packet->dst_ipaddr.af, + &packet->dst_ipaddr.ipaddr, + dst_ip_buf, sizeof(dst_ip_buf)), + packet->dst_port); +#endif + + p = packet->data; + + /* + * @todo: Make this work again. + */ +#if 0 + mms = DEFAULT_PACKET_SIZE; /* maximum message size */ + + /* + * Clients can request a LARGER size, but not a + * smaller one. They also cannot request a size + * larger than MTU. + */ + + /* DHCP-DHCP-Maximum-Msg-Size */ + vp = fr_pair_find_by_num(packet->vps, 57, DHCP_MAGIC_VENDOR, TAG_ANY); + if (vp && (vp->vp_integer > mms)) { + mms = vp->vp_integer; + + if (mms > MAX_PACKET_SIZE) mms = MAX_PACKET_SIZE; + } +#endif + + vp = fr_pair_find_by_num(packet->vps, 256, DHCP_MAGIC_VENDOR, TAG_ANY); + if (vp) { + *p++ = vp->vp_integer & 0xff; + } else { + *p++ = 1; /* client message */ + } + + /* DHCP-Hardware-Type */ + if ((vp = fr_pair_find_by_num(packet->vps, 257, DHCP_MAGIC_VENDOR, TAG_ANY))) { + *p++ = vp->vp_byte; + } else { + *p++ = 1; /* hardware type = ethernet */ + } + + /* DHCP-Hardware-Address-Length */ + if ((vp = fr_pair_find_by_num(packet->vps, 258, DHCP_MAGIC_VENDOR, TAG_ANY))) { + *p++ = vp->vp_byte; + } else { + *p++ = 6; /* 6 bytes of ethernet */ + } + + /* DHCP-Hop-Count */ + if ((vp = fr_pair_find_by_num(packet->vps, 259, DHCP_MAGIC_VENDOR, TAG_ANY))) { + *p = vp->vp_byte; + } + p++; + + /* DHCP-Transaction-Id */ + lvalue = htonl(packet->id); + memcpy(p, &lvalue, 4); + p += 4; + + /* DHCP-Number-of-Seconds */ + if ((vp = fr_pair_find_by_num(packet->vps, 261, DHCP_MAGIC_VENDOR, TAG_ANY))) { + svalue = htons(vp->vp_short); + memcpy(p, &svalue, 2); + } + p += 2; + + /* DHCP-Flags */ + if ((vp = fr_pair_find_by_num(packet->vps, 262, DHCP_MAGIC_VENDOR, TAG_ANY))) { + svalue = htons(vp->vp_short); + memcpy(p, &svalue, 2); + } + p += 2; + + /* DHCP-Client-IP-Address */ + if ((vp = fr_pair_find_by_num(packet->vps, 263, DHCP_MAGIC_VENDOR, TAG_ANY))) { + memcpy(p, &vp->vp_ipaddr, 4); + } + p += 4; + + /* DHCP-Your-IP-address */ + if ((vp = fr_pair_find_by_num(packet->vps, 264, DHCP_MAGIC_VENDOR, TAG_ANY))) { + lvalue = vp->vp_ipaddr; + } else { + lvalue = htonl(INADDR_ANY); + } + memcpy(p, &lvalue, 4); + p += 4; + + /* DHCP-Server-IP-Address */ + vp = fr_pair_find_by_num(packet->vps, 265, DHCP_MAGIC_VENDOR, TAG_ANY); + if (vp) { + lvalue = vp->vp_ipaddr; + } else { + lvalue = htonl(INADDR_ANY); + } + memcpy(p, &lvalue, 4); + p += 4; + + /* + * DHCP-Gateway-IP-Address + */ + if ((vp = fr_pair_find_by_num(packet->vps, 266, DHCP_MAGIC_VENDOR, TAG_ANY))) { + lvalue = vp->vp_ipaddr; + } else { + lvalue = htonl(INADDR_ANY); + } + memcpy(p, &lvalue, 4); + p += 4; + + /* DHCP-Client-Hardware-Address */ + if ((vp = fr_pair_find_by_num(packet->vps, 267, DHCP_MAGIC_VENDOR, TAG_ANY))) { + if (vp->vp_length == sizeof(vp->vp_ether)) { + /* + * Ensure that we mark the packet as being Ethernet. + * This is mainly for DHCP-Lease-Query responses. + */ + packet->data[1] = 1; + packet->data[2] = 6; + + memcpy(p, vp->vp_ether, vp->vp_length); + } /* else ignore it */ + } + p += DHCP_CHADDR_LEN; + + /* DHCP-Server-Host-Name */ + if ((vp = fr_pair_find_by_num(packet->vps, 268, DHCP_MAGIC_VENDOR, TAG_ANY))) { + if (vp->vp_length > DHCP_SNAME_LEN) { + memcpy(p, vp->vp_strvalue, DHCP_SNAME_LEN); + } else { + memcpy(p, vp->vp_strvalue, vp->vp_length); + } + } + p += DHCP_SNAME_LEN; + + /* + * Copy over DHCP-Boot-Filename. + * + * FIXME: This copy should be delayed until AFTER the options + * have been processed. If there are too many options for + * the packet, then they go into the sname && filename fields. + * When that happens, the boot filename is passed as an option, + * instead of being placed verbatim in the filename field. + */ + + /* DHCP-Boot-Filename */ + vp = fr_pair_find_by_num(packet->vps, 269, DHCP_MAGIC_VENDOR, TAG_ANY); + if (vp) { + if (vp->vp_length > DHCP_FILE_LEN) { + memcpy(p, vp->vp_strvalue, DHCP_FILE_LEN); + } else { + memcpy(p, vp->vp_strvalue, vp->vp_length); + } + } + p += DHCP_FILE_LEN; + + /* DHCP magic number */ + lvalue = htonl(DHCP_OPTION_MAGIC_NUMBER); + memcpy(p, &lvalue, 4); + p += 4; + + /* + * Print the header. + */ + if (fr_debug_lvl > 1) { + uint8_t *pp = p; + + p = packet->data; + + for (i = 0; i < 14; i++) { + char *q; + + vp = fr_pair_make(packet, NULL, + dhcp_header_names[i], NULL, T_OP_EQ); + if (!vp) { + char buffer[256]; + strlcpy(buffer, fr_strerror(), sizeof(buffer)); + fr_strerror_printf("Cannot decode packet due to internal error: %s", buffer); + return -1; + } + + switch (vp->da->type) { + case PW_TYPE_BYTE: + vp->vp_byte = p[0]; + break; + + case PW_TYPE_SHORT: + vp->vp_short = (p[0] << 8) | p[1]; + break; + + case PW_TYPE_INTEGER: + memcpy(&vp->vp_integer, p, 4); + vp->vp_integer = ntohl(vp->vp_integer); + break; + + case PW_TYPE_IPV4_ADDR: + memcpy(&vp->vp_ipaddr, p, 4); + break; + + case PW_TYPE_STRING: + vp->vp_strvalue = q = talloc_array(vp, char, dhcp_header_sizes[i] + 1); + vp->type = VT_DATA; + memcpy(q, p, dhcp_header_sizes[i]); + q[dhcp_header_sizes[i]] = '\0'; + vp->vp_length = strlen(vp->vp_strvalue); + break; + + case PW_TYPE_OCTETS: /* only for Client HW Address */ + fr_pair_value_memcpy(vp, p, packet->data[2]); + break; + + case PW_TYPE_ETHERNET: /* only for Client HW Address */ + memcpy(vp->vp_ether, p, sizeof(vp->vp_ether)); + break; + + default: + fr_strerror_printf("Internal sanity check failed %d %d", vp->da->type, __LINE__); + fr_pair_list_free(&vp); + break; + } + + p += dhcp_header_sizes[i]; + + debug_pair(vp); + fr_pair_list_free(&vp); + } + + /* + * Jump over DHCP magic number, response, etc. + */ + p = pp; + } + + p[0] = 0x35; /* DHCP-Message-Type */ + p[1] = 1; + p[2] = packet->code - PW_DHCP_OFFSET; + p += 3; + + /* + * Pre-sort attributes into contiguous blocks so that fr_dhcp_encode_option + * operates correctly. This changes the order of the list, but never mind... + */ + fr_pair_list_sort(&packet->vps, fr_dhcp_attr_cmp); + fr_cursor_init(&cursor, &packet->vps); + + /* + * Each call to fr_dhcp_encode_option will encode one complete DHCP option, + * and sub options. + */ + while ((vp = fr_cursor_current(&cursor))) { + len = fr_dhcp_encode_option(packet, p, packet->data_len - (p - packet->data), &cursor); + if (len < 0) break; + p += len; + }; + + p[0] = 0xff; /* end of option option */ + p[1] = 0x00; + p += 2; + dhcp_size = p - packet->data; + + /* + * FIXME: if (dhcp_size > mms), + * then we put the extra options into the "sname" and "file" + * fields, AND set the "end option option" in the "options" + * field. We also set the "overload option", + * and put options into the "file" field, followed by + * the "sname" field. Where each option is completely + * enclosed in the "file" and/or "sname" field, AND + * followed by the "end of option", and MUST be followed + * by padding option. + * + * Yuck. That sucks... + */ + packet->data_len = dhcp_size; + + if (packet->data_len < DEFAULT_PACKET_SIZE) { + memset(packet->data + packet->data_len, 0, + DEFAULT_PACKET_SIZE - packet->data_len); + packet->data_len = DEFAULT_PACKET_SIZE; + } + + if ((fr_debug_lvl > 2) && fr_log_fp) { + fprintf(fr_log_fp, "DHCP Sending %zu bytes\n", packet->data_len); + for (i = 0; i < packet->data_len; i++) { + if ((i & 0x0f) == 0x00) fprintf(fr_log_fp, "%d: ", (int) i); + fprintf(fr_log_fp, "%02x ", packet->data[i]); + if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n"); + } + fprintf(fr_log_fp, "\n"); + } + + return 0; +} + +#ifdef SIOCSARP +int fr_dhcp_add_arp_entry(int fd, char const *interface, + VALUE_PAIR *macaddr, VALUE_PAIR *ip) +{ + struct sockaddr_in *sin; + struct arpreq req; + + if (!interface) { + fr_strerror_printf("No interface specified. Cannot update ARP table"); + return -1; + } + + if (!fr_assert(macaddr) || + !fr_assert((macaddr->da->type == PW_TYPE_ETHERNET) || (macaddr->da->type == PW_TYPE_OCTETS))) { + fr_strerror_printf("Wrong VP type (%s) for chaddr", + fr_int2str(dict_attr_types, macaddr->da->type, "<invalid>")); + return -1; + } + + if (macaddr->vp_length > sizeof(req.arp_ha.sa_data)) { + fr_strerror_printf("arp sa_data field too small (%zu octets) to contain chaddr (%zu octets)", + sizeof(req.arp_ha.sa_data), macaddr->vp_length); + return -1; + } + + memset(&req, 0, sizeof(req)); + sin = (struct sockaddr_in *) &req.arp_pa; + sin->sin_family = AF_INET; + sin->sin_addr.s_addr = ip->vp_ipaddr; + + strlcpy(req.arp_dev, interface, sizeof(req.arp_dev)); + + if (macaddr->da->type == PW_TYPE_ETHERNET) { + memcpy(&req.arp_ha.sa_data, macaddr->vp_ether, sizeof(macaddr->vp_ether)); + } else { + memcpy(&req.arp_ha.sa_data, macaddr->vp_octets, macaddr->vp_length); + } + + req.arp_flags = ATF_COM; + if (ioctl(fd, SIOCSARP, &req) < 0) { + fr_strerror_printf("Failed to add entry in ARP cache: %s (%d)", fr_syserror(errno), errno); + return -1; + } + + return 0; +} +#else +int fr_dhcp_add_arp_entry(UNUSED int fd, UNUSED char const *interface, + UNUSED VALUE_PAIR *macaddr, UNUSED VALUE_PAIR *ip) +{ + fr_strerror_printf("Adding ARP entry is unsupported on this system"); + return -1; +} +#endif + + +#ifdef HAVE_LINUX_IF_PACKET_H +/* + * Open a packet interface raw socket. + * Bind it to the specified interface using a device independent physical layer address. + */ +int fr_socket_packet(int iface_index, struct sockaddr_ll *p_ll) +{ + int lsockfd; + + /* PF_PACKET - packet interface on device level. + using a raw socket allows packet data to be unchanged by the device driver. + */ + lsockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); + if (lsockfd < 0) { + fr_strerror_printf("cannot open socket: %s", fr_syserror(errno)); + return lsockfd; + } + + /* Set link layer parameters */ + memset(p_ll, 0, sizeof(struct sockaddr_ll)); + + p_ll->sll_family = AF_PACKET; + p_ll->sll_protocol = htons(ETH_P_ALL); + p_ll->sll_ifindex = iface_index; + p_ll->sll_hatype = ARPHRD_ETHER; + p_ll->sll_pkttype = PACKET_OTHERHOST; + p_ll->sll_halen = 6; + + if (bind(lsockfd, (struct sockaddr *)p_ll, sizeof(struct sockaddr_ll)) < 0) { + close(lsockfd); + fr_strerror_printf("cannot bind raw socket: %s", fr_syserror(errno)); + return -1; + } + + return lsockfd; +} + +/* + * Encode and send a DHCP packet on a raw packet socket. + */ +int fr_dhcp_send_raw_packet(int sockfd, struct sockaddr_ll *p_ll, RADIUS_PACKET *packet) +{ + VALUE_PAIR *vp; + u_char dhcp_packet[1518] = { 0 }; + + /* set ethernet source address to our MAC address (DHCP-Client-Hardware-Address). */ + u_char dhmac[ETH_ADDR_LEN] = { 0 }; + if ((vp = fr_pair_find_by_num(packet->vps, 267, DHCP_MAGIC_VENDOR, TAG_ANY))) { + if (vp->length == sizeof(vp->vp_ether)) { + memcpy(dhmac, vp->vp_ether, vp->length); + } + } + + /* fill in Ethernet layer (L2) */ + struct ethernet_header *ethhdr = (struct ethernet_header *)dhcp_packet; + memcpy(ethhdr->ether_dst, eth_bcast, ETH_ADDR_LEN); + memcpy(ethhdr->ether_src, dhmac, ETH_ADDR_LEN); + ethhdr->ether_type = htons(ETH_TYPE_IP); + + /* fill in IP layer (L3) */ + struct ip_header *iph = (struct ip_header *)(dhcp_packet + ETH_HDR_SIZE); + iph->ip_vhl = IP_VHL(4, 5); + iph->ip_tos = 0; + iph->ip_len = htons(IP_HDR_SIZE + UDP_HDR_SIZE + packet->data_len); + iph->ip_id = 0; + iph->ip_off = 0; + iph->ip_ttl = 64; + iph->ip_p = 17; + iph->ip_sum = 0; /* Filled later */ + + /* saddr: Packet-Src-IP-Address (default: 0.0.0.0). */ + iph->ip_src.s_addr = packet->src_ipaddr.ipaddr.ip4addr.s_addr; + + /* daddr: packet destination IP addr (should be 255.255.255.255 for broadcast). */ + iph->ip_dst.s_addr = packet->dst_ipaddr.ipaddr.ip4addr.s_addr; + + /* IP header checksum */ + iph->ip_sum = fr_iph_checksum((uint8_t const *)iph, 5); + + /* fill in UDP layer (L4) */ + udp_header_t *uh = (udp_header_t *) (dhcp_packet + ETH_HDR_SIZE + IP_HDR_SIZE); + + uh->src = htons(68); + uh->dst = htons(67); + u_int16_t l4_len = (UDP_HDR_SIZE + packet->data_len); + uh->len = htons(l4_len); + uh->checksum = 0; /* UDP checksum will be done after dhcp header */ + + /* DHCP layer (L7) */ + dhcp_packet_t *dhpointer = (dhcp_packet_t *)(dhcp_packet + ETH_HDR_SIZE + IP_HDR_SIZE + UDP_HDR_SIZE); + /* just copy what FreeRADIUS has encoded for us. */ + memcpy(dhpointer, packet->data, packet->data_len); + + /* UDP checksum is done here */ + uh->checksum = fr_udp_checksum((uint8_t const *)(dhcp_packet + ETH_HDR_SIZE + IP_HDR_SIZE), ntohs(uh->len), uh->checksum, + packet->src_ipaddr.ipaddr.ip4addr, packet->dst_ipaddr.ipaddr.ip4addr); + + if (fr_debug_lvl > 1) { + char type_buf[64]; + char const *name = type_buf; + char src_ip_buf[INET6_ADDRSTRLEN]; + char dst_ip_buf[INET6_ADDRSTRLEN]; + + if ((packet->code >= PW_DHCP_DISCOVER) && + (packet->code < (1024 + DHCP_MAX_MESSAGE_TYPE))) { + name = dhcp_message_types[packet->code - PW_DHCP_OFFSET]; + } else { + snprintf(type_buf, sizeof(type_buf), "%d", + packet->code - PW_DHCP_OFFSET); + } + + DEBUG( + "Sending %s Id %08x from %s:%d to %s:%d\n", + name, (unsigned int) packet->id, + inet_ntop(packet->src_ipaddr.af, &packet->src_ipaddr.ipaddr, src_ip_buf, sizeof(src_ip_buf)), packet->src_port, + inet_ntop(packet->dst_ipaddr.af, &packet->dst_ipaddr.ipaddr, dst_ip_buf, sizeof(dst_ip_buf)), packet->dst_port); + } + + return sendto(sockfd, dhcp_packet, + (ETH_HDR_SIZE + IP_HDR_SIZE + UDP_HDR_SIZE + packet->data_len), + 0, (struct sockaddr *) p_ll, sizeof(struct sockaddr_ll)); +} + +/* + * print an ethernet address in a buffer + */ +static char * ether_addr_print(const uint8_t *addr, char *buf) +{ + sprintf (buf, "%02x:%02x:%02x:%02x:%02x:%02x", + addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); + return buf; +} + +/* + * For a client, receive a DHCP packet from a raw packet + * socket. Make sure it matches the ongoing request. + * + * FIXME: split this into two, recv_raw_packet, and verify(packet, original) + */ +RADIUS_PACKET *fr_dhcp_recv_raw_packet(int sockfd, struct sockaddr_ll *p_ll, RADIUS_PACKET *request) +{ + VALUE_PAIR *vp; + RADIUS_PACKET *packet; + uint8_t *code; + uint32_t magic, xid; + ssize_t data_len; + + uint8_t *raw_packet; + ethernet_header_t *eth_hdr; + struct ip_header *ip_hdr; + udp_header_t *udp_hdr; + dhcp_packet_t *dhcp_hdr; + uint16_t udp_src_port; + uint16_t udp_dst_port; + size_t dhcp_data_len; + socklen_t sock_len; + + packet = rad_alloc(NULL, false); + if (!packet) { + fr_strerror_printf("Failed allocating packet"); + return NULL; + } + + raw_packet = talloc_zero_array(packet, uint8_t, MAX_PACKET_SIZE); + if (!raw_packet) { + fr_strerror_printf("Out of memory"); + rad_free(&packet); + return NULL; + } + + packet->sockfd = sockfd; + + /* a packet was received (but maybe it is not for us) */ + sock_len = sizeof(struct sockaddr_ll); + data_len = recvfrom(sockfd, raw_packet, MAX_PACKET_SIZE, 0, + (struct sockaddr *)p_ll, &sock_len); + + uint8_t data_offset = ETH_HDR_SIZE + IP_HDR_SIZE + UDP_HDR_SIZE; // DHCP data starts after Ethernet, IP, UDP. + + if (data_len <= data_offset) DISCARD_RP("Payload (%d) smaller than required for layers 2+3+4", (int)data_len); + + /* map raw packet to packet header of the different layers (Ethernet, IP, UDP) */ + eth_hdr = (ethernet_header_t *)raw_packet; + + /* a. Check Ethernet layer data (L2) */ + if (ntohs(eth_hdr->ether_type) != ETH_TYPE_IP) DISCARD_RP("Ethernet type (%d) != IP", ntohs(eth_hdr->ether_type)); + + /* If Ethernet destination is not broadcast (ff:ff:ff:ff:ff:ff) + * Check if it matches the source HW address used (DHCP-Client-Hardware-Address = 267) + */ + if ( (memcmp(ð_bcast, ð_hdr->ether_dst, ETH_ADDR_LEN) != 0) && + (vp = fr_pair_find_by_num(request->vps, 267, DHCP_MAGIC_VENDOR, TAG_ANY)) && + (vp->length == sizeof(vp->vp_ether)) && + (memcmp(vp->vp_ether, ð_hdr->ether_dst, ETH_ADDR_LEN) != 0) ) { + /* No match. */ + char eth_dest[17+1]; + char eth_req_src[17+1]; + DISCARD_RP("Ethernet destination (%s) is not broadcast and doesn't match request source (%s)", + ether_addr_print(eth_hdr->ether_dst, eth_dest), + ether_addr_print(vp->vp_ether, eth_req_src)); + } + + /* + * Ethernet is OK. Now look at IP. + */ + ip_hdr = (struct ip_header *)(raw_packet + ETH_HDR_SIZE); + + /* b. Check IPv4 layer data (L3) */ + if (ip_hdr->ip_p != IPPROTO_UDP) DISCARD_RP("IP protocol (%d) != UDP", ip_hdr->ip_p); + + /* + * note: checking the destination IP address is not + * useful (it would be the offered IP address - which we + * don't know beforehand, or the broadcast address). + */ + + /* + * Now check UDP. + */ + udp_hdr = (udp_header_t *)(raw_packet + ETH_HDR_SIZE + IP_HDR_SIZE); + + /* c. Check UDP layer data (L4) */ + udp_src_port = ntohs(udp_hdr->src); + udp_dst_port = ntohs(udp_hdr->dst); + + /* + * A DHCP server will always respond to port 68 (to a + * client) or 67 (to a relay). Just check that both + * ports are 67 or 68. + */ + if (udp_src_port != 67 && udp_src_port != 68) DISCARD_RP("UDP src port (%d) != DHCP (67 or 68)", udp_src_port); + if (udp_dst_port != 67 && udp_dst_port != 68) DISCARD_RP("UDP dst port (%d) != DHCP (67 or 68)", udp_dst_port); + + /* d. Check DHCP layer data */ + dhcp_data_len = data_len - data_offset; + + if (dhcp_data_len < MIN_PACKET_SIZE) DISCARD_RP("DHCP packet is too small (%zu < %d)", dhcp_data_len, MIN_PACKET_SIZE); + if (dhcp_data_len > MAX_PACKET_SIZE) DISCARD_RP("DHCP packet is too large (%zu > %d)", dhcp_data_len, MAX_PACKET_SIZE); + + dhcp_hdr = (dhcp_packet_t *)(raw_packet + ETH_HDR_SIZE + IP_HDR_SIZE + UDP_HDR_SIZE); + + if (dhcp_hdr->htype != 1) DISCARD_RP("DHCP hardware type (%d) != Ethernet (1)", dhcp_hdr->htype); + if (dhcp_hdr->hlen != 6) DISCARD_RP("DHCP hardware address length (%d) != 6", dhcp_hdr->hlen); + + magic = ntohl(dhcp_hdr->option_format); + + if (magic != DHCP_OPTION_MAGIC_NUMBER) DISCARD_RP("DHCP magic cookie (0x%04x) != DHCP (0x%04x)", magic, DHCP_OPTION_MAGIC_NUMBER); + + /* + * Reply transaction id must match value from request. + */ + xid = ntohl(dhcp_hdr->xid); + if (xid != (uint32_t)request->id) DISCARD_RP("DHCP transaction ID (0x%04x) != xid from request (0x%04x)", xid, request->id) + + /* all checks ok! this is a DHCP reply we're interested in. */ + packet->data_len = dhcp_data_len; + packet->data = talloc_memdup(packet, raw_packet + data_offset, dhcp_data_len); + TALLOC_FREE(raw_packet); + packet->id = xid; + + code = dhcp_get_option((dhcp_packet_t *) packet->data, + packet->data_len, PW_DHCP_MESSAGE_TYPE); + if (!code) { + fr_strerror_printf("No message-type option was found in the packet"); + rad_free(&packet); + return NULL; + } + + if ((code[1] < 1) || (code[2] == 0) || (code[2] > 8)) { + fr_strerror_printf("Unknown value for message-type option"); + rad_free(&packet); + return NULL; + } + + packet->code = code[2] | PW_DHCP_OFFSET; + + /* + * Create a unique vector from the xid and the client + * hardware address. This is a hack for the RADIUS + * infrastructure in the rest of the server. + * It is also used for de-duplicating DHCP packets + */ + memcpy(packet->vector, packet->data + 4, 4); /* xid */ + memcpy(packet->vector + 4, packet->data + 24, 4); /* giaddr */ + packet->vector[8] = packet->code & 0xff; /* message type */ + memcpy(packet->vector + 9, packet->data + 28, 6); /* chaddr is always 6 for us */ + + packet->src_port = udp_src_port; + packet->dst_port = udp_dst_port; + + packet->src_ipaddr.af = AF_INET; + packet->src_ipaddr.ipaddr.ip4addr.s_addr = ip_hdr->ip_src.s_addr; + packet->dst_ipaddr.af = AF_INET; + packet->dst_ipaddr.ipaddr.ip4addr.s_addr = ip_hdr->ip_dst.s_addr; + + if (fr_debug_lvl > 1) { + char type_buf[64]; + char const *name = type_buf; + char src_ip_buf[256], dst_ip_buf[256]; + + if ((packet->code >= PW_DHCP_DISCOVER) && + (packet->code < (1024 + DHCP_MAX_MESSAGE_TYPE))) { + name = dhcp_message_types[packet->code - PW_DHCP_OFFSET]; + } else { + snprintf(type_buf, sizeof(type_buf), "%d", packet->code - PW_DHCP_OFFSET); + } + + DEBUG("Received %s of Id %08x from %s:%d to %s:%d\n", + name, (unsigned int) packet->id, + inet_ntop(packet->src_ipaddr.af, &packet->src_ipaddr.ipaddr, src_ip_buf, sizeof(src_ip_buf)), + packet->src_port, + inet_ntop(packet->dst_ipaddr.af, &packet->dst_ipaddr.ipaddr, dst_ip_buf, sizeof(dst_ip_buf)), + packet->dst_port); + } + + return packet; +} +#endif diff --git a/src/modules/proto_dhcp/dhcpclient.c b/src/modules/proto_dhcp/dhcpclient.c new file mode 100644 index 0000000..2ae0a76 --- /dev/null +++ b/src/modules/proto_dhcp/dhcpclient.c @@ -0,0 +1,652 @@ +/* + * dhcpclient.c General radius packet debug tool. + * + * Version: $Id$ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + * + * Copyright 2000,2006 The FreeRADIUS server project + * Copyright 2000 Miquel van Smoorenburg <miquels@cistron.nl> + * Copyright 2010 Alan DeKok <aland@ox.org> + */ + +RCSID("$Id$") + +#include <freeradius-devel/libradius.h> +#include <freeradius-devel/conf.h> +#include <freeradius-devel/dhcp.h> + +#ifdef WITH_DHCP + +#include <ctype.h> + +#ifdef HAVE_GETOPT_H +# include <getopt.h> +#endif + +#include <assert.h> + +#include <net/if.h> + +static int success = 0; +static int retries = 3; +static float timeout = 5.0; +static struct timeval tv_timeout; + +static int sockfd; + +#ifdef HAVE_LINUX_IF_PACKET_H +struct sockaddr_ll ll; /* Socket address structure */ +static char *iface = NULL; +static int iface_ind = -1; + +# define DEBUG if (fr_debug_lvl && fr_log_fp) fr_printf_log +#endif + +static RADIUS_PACKET *reply = NULL; + +static bool reply_expected = true; + +#define DHCP_CHADDR_LEN (16) +#define DHCP_SNAME_LEN (64) +#define DHCP_FILE_LEN (128) + +static char const *dhcpclient_version = "dhcpclient version " RADIUSD_VERSION_STRING +#ifdef RADIUSD_VERSION_COMMIT +" (git #" STRINGIFY(RADIUSD_VERSION_COMMIT) ")" +#endif +#ifndef ENABLE_REPRODUCIBLE_BUILDS +", built on " __DATE__ " at " __TIME__ +#endif +; + +/* structure to keep track of offered IP addresses */ +typedef struct dc_offer { + uint32_t server_addr; + uint32_t offered_addr; +} dc_offer_t; + +static const FR_NAME_NUMBER request_types[] = { + { "discover", PW_DHCP_DISCOVER }, + { "request", PW_DHCP_REQUEST }, + { "decline", PW_DHCP_DECLINE }, + { "release", PW_DHCP_RELEASE }, + { "inform", PW_DHCP_INFORM }, + { "lease_query", PW_DHCP_LEASE_QUERY }, + { "auto", PW_CODE_UNDEFINED }, + { NULL, 0} +}; + +static void NEVER_RETURNS usage(void) +{ + fprintf(stderr, "Usage: dhcpclient [options] server[:port] [<command>]\n"); + fprintf(stderr, "Send a DHCP request with provided RADIUS attrs and output response.\n"); + + fprintf(stderr, " <command> One of: discover, request, decline, release, inform; or: auto.\n"); + fprintf(stderr, " -d <directory> Set the directory where the dictionaries are stored (defaults to " RADDBDIR ").\n"); + fprintf(stderr, " -D <dictdir> Set main dictionary directory (defaults to " DICTDIR ").\n"); + fprintf(stderr, " -f <file> Read packets from file, not stdin.\n"); +#ifdef HAVE_LINUX_IF_PACKET_H + fprintf(stderr, " -i <interface> Use this interface to send/receive at packet level on a raw socket.\n"); +#endif + fprintf(stderr, " -t <timeout> Wait 'timeout' seconds for a reply (may be a floating point number).\n"); + fprintf(stderr, " -v Show program version information.\n"); + fprintf(stderr, " -x Debugging mode.\n"); + + exit(1); +} + + +/* + * Initialize the request. + */ +static RADIUS_PACKET *request_init(char const *filename) +{ + FILE *fp; + vp_cursor_t cursor; + VALUE_PAIR *vp; + bool filedone = false; + RADIUS_PACKET *request; + + /* + * Determine where to read the VP's from. + */ + if (filename) { + fp = fopen(filename, "r"); + if (!fp) { + fprintf(stderr, "dhcpclient: Error opening %s: %s\n", filename, fr_syserror(errno)); + return NULL; + } + } else { + fp = stdin; + } + + request = rad_alloc(NULL, false); + /* + * Read the VP's. + */ + if (fr_pair_list_afrom_file(NULL, &request->vps, fp, &filedone) < 0) { + fr_perror("dhcpclient"); + rad_free(&request); + if (fp != stdin) fclose(fp); + return NULL; + } + + /* + * Fix / set various options + */ + for (vp = fr_cursor_init(&cursor, &request->vps); + vp; + vp = fr_cursor_next(&cursor)) { + /* + * Allow to set packet type using DHCP-Message-Type + */ + if (vp->da->vendor == DHCP_MAGIC_VENDOR && vp->da->attr == PW_DHCP_MESSAGE_TYPE) { + request->code = vp->vp_integer + PW_DHCP_OFFSET; + } else if (!vp->da->vendor) switch (vp->da->attr) { + /* + * Allow it to set the packet type in + * the attributes read from the file. + * (this takes precedence over the command argument.) + */ + case PW_PACKET_TYPE: + request->code = vp->vp_integer; + break; + + case PW_PACKET_DST_PORT: + request->dst_port = (vp->vp_integer & 0xffff); + break; + + case PW_PACKET_DST_IP_ADDRESS: + request->dst_ipaddr.af = AF_INET; + request->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + request->dst_ipaddr.prefix = 32; + break; + + case PW_PACKET_DST_IPV6_ADDRESS: + request->dst_ipaddr.af = AF_INET6; + request->dst_ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr; + request->dst_ipaddr.prefix = 128; + break; + + case PW_PACKET_SRC_PORT: + request->src_port = (vp->vp_integer & 0xffff); + break; + + case PW_PACKET_SRC_IP_ADDRESS: + request->src_ipaddr.af = AF_INET; + request->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + request->src_ipaddr.prefix = 32; + break; + + case PW_PACKET_SRC_IPV6_ADDRESS: + request->src_ipaddr.af = AF_INET6; + request->src_ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr; + request->src_ipaddr.prefix = 128; + break; + + default: + break; + } /* switch over the attribute */ + + } /* loop over the VP's we read in */ + + if (fp != stdin) fclose(fp); + + /* + * And we're done. + */ + return request; +} + +static char const *dhcp_header_names[] = { + "DHCP-Opcode", + "DHCP-Hardware-Type", + "DHCP-Hardware-Address-Length", + "DHCP-Hop-Count", + "DHCP-Transaction-Id", + "DHCP-Number-of-Seconds", + "DHCP-Flags", + "DHCP-Client-IP-Address", + "DHCP-Your-IP-Address", + "DHCP-Server-IP-Address", + "DHCP-Gateway-IP-Address", + "DHCP-Client-Hardware-Address", + "DHCP-Server-Host-Name", + "DHCP-Boot-Filename", + + NULL +}; + +static int dhcp_header_sizes[] = { + 1, 1, 1, 1, + 4, 2, 2, 4, + 4, 4, 4, + DHCP_CHADDR_LEN, + DHCP_SNAME_LEN, + DHCP_FILE_LEN +}; + + +static void print_hex(RADIUS_PACKET *packet) +{ + int i, j; + uint8_t const *p, *a; + + if (!packet->data) return; + + if (packet->data_len < 244) { + printf("Huh?\n"); + return; + } + + printf("----------------------------------------------------------------------\n"); + fflush(stdout); + + p = packet->data; + for (i = 0; i < 14; i++) { + printf("%s = 0x", dhcp_header_names[i]); + for (j = 0; j < dhcp_header_sizes[i]; j++) { + printf("%02x", p[j]); + + } + printf("\n"); + p += dhcp_header_sizes[i]; + } + + /* + * Magic number + */ + printf("%02x %02x %02x %02x\n", + p[0], p[1], p[2], p[3]); + p += 4; + + while (p < (packet->data + packet->data_len)) { + + if (*p == 0) break; + if (*p == 255) break; /* end of options signifier */ + if ((p + 2) > (packet->data + packet->data_len)) break; + + printf("%02x %02x ", p[0], p[1]); + a = p + 2; + + for (i = 0; i < p[1]; i++) { + if ((i > 0) && ((i & 0x0f) == 0x00)) + printf("\t\t"); + printf("%02x ", a[i]); + if ((i & 0x0f) == 0x0f) printf("\n"); + } + + if ((p[1] & 0x0f) != 0x00) printf("\n"); + + p += p[1] + 2; + } + printf("\n----------------------------------------------------------------------\n"); + fflush(stdout); +} + +static void send_with_socket(RADIUS_PACKET *request) +{ + request->sockfd = sockfd; + + if (fr_dhcp_send(request) < 0) { + fprintf(stderr, "dhcpclient: failed sending: %s\n", + fr_syserror(errno)); + fr_exit_now(1); + } + + if (!reply_expected) return; + + reply = fr_dhcp_recv(sockfd); + if (!reply) { + fprintf(stderr, "dhcpclient: Error receiving reply: %s\n", fr_strerror()); + fr_exit_now(1); + } + + + if (fr_debug_lvl) print_hex(reply); + + if (fr_dhcp_decode(reply) < 0) { + fprintf(stderr, "dhcpclient: failed decoding\n"); + fr_exit_now(1); + } +} + + +#ifdef HAVE_LINUX_IF_PACKET_H +/* + * Loop waiting for DHCP replies until timer expires. + * Note that there may be more than one reply: multiple DHCP servers can respond to a broadcast discover. + * A real client would pick one of the proposed replies. + * We'll just return the first eligible reply, and display the others. + */ +static RADIUS_PACKET *fr_dhcp_recv_raw_loop(int sockfd_r, struct sockaddr_ll *p_ll, RADIUS_PACKET *request_p) +{ + struct timeval tval; + RADIUS_PACKET *reply_p = NULL; + RADIUS_PACKET *cur_reply_p = NULL; + int num_replies = 0; + int num_offers = 0; + dc_offer_t *offer_list = NULL; + fd_set read_fd; + int retval; + + memcpy(&tval, &tv_timeout, sizeof(struct timeval)); + + /* Loop waiting for DHCP replies until timer expires */ + while (timerisset(&tval)) { + if ((!reply_p) || (cur_reply_p)) { // only debug at start and each time we get a valid DHCP reply on raw socket + DEBUG("Waiting for%sDHCP replies for: %d.%06d\n", + (num_replies>0)?" additional ":" ", (int)tval.tv_sec, (int)tval.tv_usec); + } + + cur_reply_p = NULL; + FD_ZERO(&read_fd); + FD_SET(sockfd_r, &read_fd); + retval = select(sockfd_r + 1, &read_fd, NULL, NULL, &tval); + + if (retval < 0) { + fr_strerror_printf("Select on DHCP socket failed: %s", fr_syserror(errno)); + return NULL; + } + + if ( retval > 0 && FD_ISSET(sockfd_r, &read_fd)) { + /* There is something to read on our socket */ + cur_reply_p = fr_dhcp_recv_raw_packet(sockfd_r, p_ll, request_p); + } + + if (cur_reply_p) { + num_replies ++; + + if (fr_debug_lvl) print_hex(cur_reply_p); + + if (fr_dhcp_decode(cur_reply_p) < 0) { + fprintf(stderr, "dhcpclient: failed decoding reply\n"); + return NULL; + } + + if (!reply_p) reply_p = cur_reply_p; + + if (cur_reply_p->code == PW_DHCP_OFFER) { + VALUE_PAIR *vp1 = fr_pair_find_by_num(cur_reply_p->vps, 54, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-DHCP-Server-Identifier */ + VALUE_PAIR *vp2 = fr_pair_find_by_num(cur_reply_p->vps, 264, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Your-IP-address */ + + if (vp1 && vp2) { + num_offers ++; + offer_list = talloc_realloc(request_p, offer_list, dc_offer_t, num_offers); + offer_list[num_offers-1].server_addr = vp1->vp_ipaddr; + offer_list[num_offers-1].offered_addr = vp2->vp_ipaddr; + } + } + } + } + + if (!num_replies) { + fr_strerror_printf("No valid DHCP reply received"); + return NULL; + } + + /* display offer(s) received */ + if (num_offers > 0 ) { + DEBUG("Received %d DHCP Offer(s):\n", num_offers); + int i; + for (i = 0; i < num_replies; i++) { + char server_addr_buf[INET6_ADDRSTRLEN]; + char offered_addr_buf[INET6_ADDRSTRLEN]; + + DEBUG("IP address: %s offered by DHCP server: %s\n", + inet_ntop(AF_INET, &offer_list[i].offered_addr, offered_addr_buf, sizeof(offered_addr_buf)), + inet_ntop(AF_INET, &offer_list[i].server_addr, server_addr_buf, sizeof(server_addr_buf)) + ); + } + } + + return reply_p; +} +#endif + + +int main(int argc, char **argv) +{ + static uint16_t server_port = 0; + static int packet_code = 0; + static fr_ipaddr_t server_ipaddr; + static fr_ipaddr_t client_ipaddr; + + int c; + char const *radius_dir = RADDBDIR; + char const *dict_dir = DICTDIR; + char const *filename = NULL; + DICT_ATTR const *da; + RADIUS_PACKET *request = NULL; + +#ifdef HAVE_LINUX_IF_PACKET_H + bool raw_mode = false; +#endif + + fr_debug_lvl = 0; + + while ((c = getopt(argc, argv, "d:D:f:hr:t:vx" +#ifdef HAVE_LINUX_IF_PACKET_H + "i:" +#endif + )) != EOF) switch(c) { + case 'D': + dict_dir = optarg; + break; + + case 'd': + radius_dir = optarg; + break; + case 'f': + filename = optarg; + break; +#ifdef HAVE_LINUX_IF_PACKET_H + case 'i': + iface = optarg; + break; +#endif + case 'r': + if (!isdigit((int) *optarg)) + usage(); + retries = atoi(optarg); + if ((retries == 0) || (retries > 1000)) usage(); + break; + case 't': + if (!isdigit((int) *optarg)) + usage(); + timeout = atof(optarg); + break; + case 'v': + printf("%s\n", dhcpclient_version); + exit(0); + + case 'x': + fr_debug_lvl++; + fr_log_fp = stdout; + break; + case 'h': + default: + usage(); + } + argc -= (optind - 1); + argv += (optind - 1); + + if (argc < 2) usage(); + + /* convert timeout to a struct timeval */ +#define USEC 1000000 + tv_timeout.tv_sec = timeout; + tv_timeout.tv_usec = ((timeout - (float) tv_timeout.tv_sec) * USEC); + + if (dict_init(dict_dir, RADIUS_DICTIONARY) < 0) { + fr_perror("radclient"); + return 1; + } + + if (dict_read(radius_dir, RADIUS_DICTIONARY) == -1) { + fr_perror("radclient"); + return 1; + } + fr_strerror(); /* Clear the error buffer */ + + /* + * Ensure that dictionary.dhcp is loaded. + */ + da = dict_attrbyname("DHCP-Message-Type"); + if (!da) { + if (dict_read(dict_dir, "dictionary.dhcp") < 0) { + fprintf(stderr, "Failed reading dictionary.dhcp: %s\n", fr_strerror()); + return -1; + } + } + + /* + * Resolve hostname. + */ + server_ipaddr.af = AF_INET; + if (strcmp(argv[1], "-") != 0) { + if (fr_pton_port(&server_ipaddr, &server_port, argv[1], -1, AF_INET, true) < 0) { + fprintf(stderr, "dhcpclient: Failed parsing IP:port - %s", fr_strerror()); + exit(1); + } + + client_ipaddr.af = server_ipaddr.af; + } + + /* + * See what kind of request we want to send. + */ + if (argc >= 3) { + if (!isdigit((int) argv[2][0])) { + packet_code = fr_str2int(request_types, argv[2], -2); + if (packet_code == -2) { + fprintf(stderr, "Unknown packet type: %s\n", argv[2]); + usage(); + } + } else { + packet_code = atoi(argv[2]); + } + } + if (!server_port) server_port = 67; + +#ifdef HAVE_LINUX_IF_PACKET_H + /* + * set "raw mode" if an interface is specified and if destination + * IP address is the broadcast address. + */ + if (iface) { + iface_ind = if_nametoindex(iface); + if (iface_ind <= 0) { + fprintf(stderr, "dhcpclient: unknown interface: %s\n", iface); + fr_exit_now(1); + } + + if (server_ipaddr.ipaddr.ip4addr.s_addr == 0xFFFFFFFF) { + DEBUG("dhcpclient: Using interface: %s (index: %d) in raw packet mode\n", iface, iface_ind); + raw_mode = true; + } + } + + if (raw_mode) { + sockfd = fr_socket_packet(iface_ind, &ll); + } else +#endif + { + sockfd = fr_socket(&client_ipaddr, server_port + 1); + } + + if (sockfd < 0) { + fprintf(stderr, "dhcpclient: socket: %s\n", fr_strerror()); + fr_exit_now(1); + } + + /* + * Set option 'receive timeout' on socket. + * Note: in case of a timeout, the error will be "Resource temporarily unavailable". + */ + if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv_timeout,sizeof(struct timeval)) == -1) { + fprintf(stderr, "dhcpclient: failed setting socket timeout: %s\n", + fr_syserror(errno)); + fr_exit_now(1); + } + + request = request_init(filename); + if (!request || !request->vps) { + fprintf(stderr, "dhcpclient: Nothing to send.\n"); + fr_exit_now(1); + } + + /* + * Set defaults if they weren't specified via pairs + */ + if (request->src_port == 0) request->src_port = server_port + 1; + if (request->dst_port == 0) request->dst_port = server_port; + if (request->src_ipaddr.af == AF_UNSPEC) request->src_ipaddr = client_ipaddr; + if (request->dst_ipaddr.af == AF_UNSPEC) request->dst_ipaddr = server_ipaddr; + if (!request->code) request->code = packet_code; + + /* + * Sanity check. + */ + if (!request->code) { + fprintf(stderr, "dhcpclient: Command was %s, and request did not contain DHCP-Message-Type nor Packet-Type.\n", + (argc >= 3) ? "'auto'" : "unspecified"); + exit(1); + } + + if ((request->code == PW_DHCP_RELEASE) || (request->code == PW_DHCP_DECLINE)) { + /* These kind of packets do not get a reply, so don't wait for one. */ + reply_expected = false; + } + + /* + * Encode the packet + */ + if (fr_dhcp_encode(request) < 0) { + fprintf(stderr, "dhcpclient: failed encoding: %s\n", fr_strerror()); + fr_exit_now(1); + } + if (fr_debug_lvl) print_hex(request); + +#ifdef HAVE_LINUX_IF_PACKET_H + if (raw_mode) { + if (fr_dhcp_send_raw_packet(sockfd, &ll, request) < 0) { + fprintf(stderr, "dhcpclient: failed sending (fr_dhcp_send_raw_packet): %s\n", + fr_syserror(errno)); + fr_exit_now(1); + } + + if (reply_expected) { + reply = fr_dhcp_recv_raw_loop(sockfd, &ll, request); + if (!reply) { + fprintf(stderr, "dhcpclient: Error receiving reply (fr_dhcp_recv_raw_loop)\n"); + fr_exit_now(1); + } + } + } else +#endif + { + send_with_socket(request); + } + + dict_free(); + + if (success) return 0; + + return 1; +} + +#endif /* WITH_DHCP */ diff --git a/src/modules/proto_dhcp/dhcpclient.mk b/src/modules/proto_dhcp/dhcpclient.mk new file mode 100644 index 0000000..4266670 --- /dev/null +++ b/src/modules/proto_dhcp/dhcpclient.mk @@ -0,0 +1,5 @@ +TARGET := dhcpclient +SOURCES := dhcpclient.c dhcp.c + +TGT_PREREQS := libfreeradius-radius.a +TGT_LDLIBS := $(LIBS) diff --git a/src/modules/proto_dhcp/dhcpd.c b/src/modules/proto_dhcp/dhcpd.c new file mode 100644 index 0000000..4cafd56 --- /dev/null +++ b/src/modules/proto_dhcp/dhcpd.c @@ -0,0 +1,867 @@ +/* + * dhcp.c DHCP processing. + * + * Version: $Id$ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + * + * Copyright 2008 The FreeRADIUS server project + * Copyright 2008,2011 Alan DeKok <aland@deployingradius.com> + */ + +/* + * Standard sequence: + * INADDR_ANY : 68 -> INADDR_BROADCAST : 67 DISCOVER + * CLIENT_IP : 68 <- DHCP_SERVER_IP : 67 OFFER + * INADDR_ANY : 68 -> INADDR_BROADCAST : 67 REQUEST + * CLIENT_IP : 68 <- DHCP_SERVER_IP : 67 ACK + * + * Relay sequence: + * INADDR_ANY : 68 -> INADDR_BROADCAST : 67 DISCOVER + * RELAY_IP : 67 -> NEXT_SERVER_IP : 67 DISCOVER + * (NEXT_SERVER_IP can be a relay itself) + * FIRST_RELAY_IP : 67 <- DHCP_SERVER_IP : 67 OFFER + * CLIENT_IP : 68 <- FIRST_RELAY_IP : 67 OFFER + * INADDR_ANY : 68 -> INADDR_BROADCAST : 67 REQUEST + * RELAY_IP : 67 -> NEXT_SERVER_IP : 67 REQUEST + * (NEXT_SERVER_IP can be a relay itself) + * FIRST_RELAY_IP : 67 <- DHCP_SERVER_IP : 67 ACK + * CLIENT_IP : 68 <- FIRST_RELAY_IP : 67 ACK + * + * Note: NACK are broadcasted, rest is unicast, unless client asked + * for a broadcast + */ + + +#include <freeradius-devel/radiusd.h> +#include <freeradius-devel/modules.h> +#include <freeradius-devel/protocol.h> +#include <freeradius-devel/process.h> +#include <freeradius-devel/dhcp.h> +#include <freeradius-devel/rad_assert.h> + +#ifndef __MINGW32__ +#include <sys/ioctl.h> +#endif + +/* + * Same contents as listen_socket_t. + */ +typedef struct dhcp_socket_t { + listen_socket_t lsock; + + /* + * DHCP-specific additions. + */ + bool suppress_responses; + RADCLIENT dhcp_client; + char const *src_interface; + fr_ipaddr_t src_ipaddr; +} dhcp_socket_t; + +#ifdef WITH_UDPFROMTO +static int dhcprelay_process_client_request(REQUEST *request) +{ + int rcode; + uint8_t maxhops = 16; + VALUE_PAIR *vp, *giaddr; + dhcp_socket_t *sock; + RADIUS_PACKET *packet; + + rad_assert(request->packet->data[0] == 1); + + /* + * Do the forward by ourselves, do not rely on dhcp_socket_send() + */ + request->reply->code = 0; + + /* + * It's invalid to have giaddr=0 AND a relay option + */ + giaddr = fr_pair_find_by_num(request->packet->vps, 266, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Gateway-IP-Address */ + if (giaddr && (giaddr->vp_ipaddr == htonl(INADDR_ANY)) && + fr_pair_find_by_num(request->packet->vps, 82, DHCP_MAGIC_VENDOR, TAG_ANY)) { /* DHCP-Relay-Agent-Information */ + DEBUG("DHCP: Received packet with giaddr = 0 and containing relay option: Discarding packet\n"); + return 1; + } + + /* + * RFC 1542 (BOOTP), page 15 + * + * Drop requests if hop-count > 16 or admin specified another value + */ + if ((vp = fr_pair_find_by_num(request->config, 271, DHCP_MAGIC_VENDOR, TAG_ANY))) { /* DHCP-Relay-Max-Hop-Count */ + maxhops = vp->vp_integer; + } + vp = fr_pair_find_by_num(request->packet->vps, 259, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Hop-Count */ + rad_assert(vp != NULL); + if (vp->vp_byte > maxhops) { + DEBUG("DHCP: Number of hops is greater than %d: not relaying\n", maxhops); + return 1; + } else { + /* Increment hop count */ + vp->vp_byte++; + } + + sock = request->listener->data; + + /* + * Don't muck with the original request packet. That's + * bad form. Plus, dhcp_encode() does nothing if + * packet->data is already set. + */ + packet = rad_alloc(request, false); + + /* + * Forward the request to the next server using the + * incoming request as a template. + */ + packet->code = request->packet->code; + packet->sockfd = request->packet->sockfd; + + /* + * Forward the request to the next server using the + * incoming request as a template. + */ + /* set SRC ipaddr/port to the listener ipaddr/port */ + packet->src_ipaddr.af = AF_INET; + packet->src_ipaddr.ipaddr.ip4addr.s_addr = sock->lsock.my_ipaddr.ipaddr.ip4addr.s_addr; + packet->src_port = sock->lsock.my_port; + + vp = fr_pair_find_by_num(request->config, 270, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Relay-To-IP-Address */ + rad_assert(vp != NULL); + + /* set DEST ipaddr/port to the next server ipaddr/port */ + packet->dst_ipaddr.af = AF_INET; + packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + packet->dst_port = sock->lsock.my_port; + + packet->vps = request->packet->vps; /* hackity hack */ + + if (fr_dhcp_encode(packet) < 0) { + packet->vps = NULL; + talloc_free(packet); + DEBUG("dhcprelay_process_client_request: ERROR in fr_dhcp_encode\n"); + return -1; + } + + rcode = fr_dhcp_send(packet); + packet->vps = NULL; + talloc_free(packet); + + return rcode; +} + + +/* + * We've seen a reply from a server. + * i.e. we're a relay. + */ +static int dhcprelay_process_server_reply(REQUEST *request) +{ + int rcode; + VALUE_PAIR *vp, *giaddr; + dhcp_socket_t *sock; + RADIUS_PACKET *packet; + + rad_assert(request->packet->data[0] == 2); + + /* + * Do the forward by ourselves, do not rely on dhcp_socket_send() + */ + request->reply->code = 0; + + sock = request->listener->data; + + /* + * Check that packet is for us. + */ + giaddr = fr_pair_find_by_num(request->packet->vps, 266, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Gateway-IP-Address */ + + /* --with-udpfromto is needed just for the following test */ + if (!giaddr || giaddr->vp_ipaddr != request->packet->dst_ipaddr.ipaddr.ip4addr.s_addr) { + DEBUG("DHCP: Packet received from server was not for us (was for 0x%x). Discarding packet", + ntohl(request->packet->dst_ipaddr.ipaddr.ip4addr.s_addr)); + return 1; + } + + /* + * Don't muck with the original request packet. That's + * bad form. Plus, dhcp_encode() does nothing if + * packet->data is already set. + */ + packet = rad_alloc(request, false); + rcode = -1; + + /* + * Forward the request to the next server using the + * incoming request as a template. + */ + packet->code = request->packet->code; + packet->sockfd = request->packet->sockfd; + + /* set SRC ipaddr/port to the listener ipaddr/port */ + packet->src_ipaddr.af = AF_INET; + packet->src_port = sock->lsock.my_port; + + /* set DEST ipaddr/port to clientip/68 or broadcast in specific cases */ + packet->dst_ipaddr.af = AF_INET; + + /* + * We're a relay, figure out where to send the packet. + */ + packet->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_BROADCAST); + packet->dst_port = request->packet->dst_port; /* server port */ + + /* + * Unicast the response to another relay if requested. + */ + vp = fr_pair_find_by_num(request->config, 270, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Relay-To-IP-Address */ + if (vp) { + RDEBUG("DHCP: response will be relayed to previous gateway"); + packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + giaddr->vp_ipaddr = vp->vp_ipaddr; + + } else if ((packet->code == PW_DHCP_NAK) || + !sock->src_interface || + ((vp = fr_pair_find_by_num(request->packet->vps, 262, DHCP_MAGIC_VENDOR, TAG_ANY)) /* DHCP-Flags */ && + (vp->vp_integer & 0x8000) && + ((vp = fr_pair_find_by_num(request->packet->vps, 263, DHCP_MAGIC_VENDOR, TAG_ANY)) /* DHCP-Client-IP-Address */ && + (vp->vp_ipaddr == htonl(INADDR_ANY))))) { + /* + * RFC 2131, page 23 + * + * Broadcast on + * - DHCPNAK + * or + * - Broadcast flag is set up and ciaddr == NULL + */ + RDEBUG("DHCP: response will be broadcast"); + packet->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_BROADCAST); + + } else if ((vp = fr_pair_find_by_num(request->packet->vps, 263, DHCP_MAGIC_VENDOR, TAG_ANY)) /* DHCP-Client-IP-Address */ && + (vp->vp_ipaddr != htonl(INADDR_ANY))) { + /* + * RFC 2131, page 23 + * + * Unicast to + * - ciaddr if present + * otherwise to yiaddr + */ + packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + } else { + vp = fr_pair_find_by_num(request->packet->vps, 264, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Your-IP-Address */ + if (!vp) { + DEBUG("DHCP: Failed to find IP Address for request"); + goto error; + } + + RDEBUG("DHCP: response will be unicast to your-ip-address"); + packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + + /* + * When sending a DHCP_OFFER, make sure our ARP table + * contains an entry for the client IP address, or else + * packet may not be forwarded if it was the first time + * the client was requesting an IP address. + */ + if (packet->code == PW_DHCP_OFFER) { + VALUE_PAIR *hwvp = fr_pair_find_by_num(request->packet->vps, 267, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Client-Hardware-Address */ + if (hwvp == NULL) { + DEBUG("DHCP: DHCP_OFFER packet received with " + "no Client Hardware Address. Discarding packet"); + goto error; + } + if (fr_dhcp_add_arp_entry(packet->sockfd, sock->src_interface, hwvp, vp) < 0) { + DEBUG("Failed adding ARP entry: %s", fr_strerror()); + goto error; + } + } + } + + packet->vps = request->packet->vps; /* hackity hack */ + + if (fr_dhcp_encode(packet) < 0) { + DEBUG("dhcprelay_process_server_reply: ERROR in fr_dhcp_encode\n"); + goto error; + } + + rcode = fr_dhcp_send(packet); + +error: + packet->vps = NULL; + talloc_free(packet); + return rcode; +} +#else /* WITH_UDPFROMTO */ +static int dhcprelay_process_server_reply(UNUSED REQUEST *request) +{ + WARN("DHCP Relaying requires the server to be configured with UDPFROMTO"); + return -1; +} + +static int dhcprelay_process_client_request(UNUSED REQUEST *request) +{ + WARN("DHCP Relaying requires the server to be configured with UDPFROMTO"); + return -1; +} + +#endif /* WITH_UDPFROMTO */ + +static const uint32_t attrnums[] = { + 57, /* DHCP-DHCP-Maximum-Msg-Size */ + 256, /* DHCP-Opcode */ + 257, /* DHCP-Hardware-Type */ + 258, /* DHCP-Hardware-Address-Length */ + 259, /* DHCP-Hop-Count */ + 260, /* DHCP-Transaction-Id */ + 262, /* DHCP-Flags */ + 263, /* DHCP-Client-IP-Address */ + 266, /* DHCP-Gateway-IP-Address */ + 267 /* DHCP-Client-Hardware-Address */ +}; + +static int dhcp_process(REQUEST *request) +{ + int rcode; + unsigned int i; + VALUE_PAIR *vp; + dhcp_socket_t *sock; + + /* + * If there's a giaddr, save it as the Relay-IP-Address + * in the response. That way the later code knows where + * to send the reply. + */ + vp = fr_pair_find_by_num(request->packet->vps, 266, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Gateway-IP-Address */ + if (vp && (vp->vp_ipaddr != htonl(INADDR_ANY))) { + VALUE_PAIR *relay; + + /* DHCP-Relay-IP-Address */ + relay = radius_pair_create(request->reply, &request->reply->vps, + 272, DHCP_MAGIC_VENDOR); + if (relay) relay->vp_ipaddr = vp->vp_ipaddr; + } + + /* + * RFC 6842: If there's a DHCP-Client-Identifier ("uid") in the + * request then echo this in the reply. + */ + vp = fr_pair_find_by_num(request->packet->vps, 61, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Client-Identifier */ + if (vp && !fr_pair_find_by_num(request->reply->vps, 61, DHCP_MAGIC_VENDOR, TAG_ANY)) { + fr_pair_add(&request->reply->vps, fr_pair_copy(request->reply, vp)); + } + + vp = fr_pair_find_by_num(request->packet->vps, 53, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Message-Type */ + if (vp) { + DICT_VALUE *dv = dict_valbyattr(53, DHCP_MAGIC_VENDOR, vp->vp_byte); + DEBUG("Trying sub-section dhcp %s {...}", + dv ? dv->name : "<unknown>"); + rcode = process_post_auth(vp->vp_byte, request); + } else { + DEBUG("DHCP: Failed to find DHCP-Message-Type in packet!"); + rcode = RLM_MODULE_FAIL; + } + + vp = fr_pair_find_by_num(request->reply->vps, 53, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Message-Type */ + if (vp) { + request->reply->code = vp->vp_byte; + if ((request->reply->code != 0) && + (request->reply->code < PW_DHCP_OFFSET)) { + request->reply->code += PW_DHCP_OFFSET; + } + } + else switch (rcode) { + case RLM_MODULE_OK: + case RLM_MODULE_UPDATED: + if (request->packet->code == PW_DHCP_DISCOVER) { + request->reply->code = PW_DHCP_OFFER; + break; + + } else if (request->packet->code == PW_DHCP_REQUEST) { + request->reply->code = PW_DHCP_ACK; + break; + } + request->reply->code = PW_DHCP_NAK; + break; + + default: + case RLM_MODULE_REJECT: + case RLM_MODULE_FAIL: + case RLM_MODULE_INVALID: + case RLM_MODULE_NOOP: + case RLM_MODULE_NOTFOUND: + if (request->packet->code == PW_DHCP_DISCOVER) { + request->reply->code = 0; /* ignore the packet */ + } else { + request->reply->code = PW_DHCP_NAK; + } + break; + + case RLM_MODULE_HANDLED: + request->reply->code = 0; /* ignore the packet */ + break; + } + + /* + * TODO: Handle 'output' of RLM_MODULE when acting as a + * DHCP relay We may want to not forward packets in + * certain circumstances. + */ + + /* + * Handle requests when acting as a DHCP relay + */ + vp = fr_pair_find_by_num(request->packet->vps, 256, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Opcode */ + if (!vp) { + RDEBUG("FAILURE: Someone deleted the DHCP-Opcode!"); + return 1; + } + + /* BOOTREPLY received on port 67 (i.e. from a server) */ + if (vp->vp_byte == 2) { + if (request->reply->code == 0) { + return 1; + } + return dhcprelay_process_server_reply(request); + } + + /* + * If it's not BOOTREQUEST, we ignore it. + */ + if (vp->vp_byte != 1) { + REDEBUG("Ignoring invalid packet code %u", vp->vp_byte); + return 1; + } + + /* Packet from client, and we have DHCP-Relay-To-IP-Address */ + if (fr_pair_find_by_num(request->config, 270, DHCP_MAGIC_VENDOR, TAG_ANY)) { + return dhcprelay_process_client_request(request); + } + + sock = request->listener->data; + + /* + * Handle requests when acting as a DHCP server + */ + + /* + * Releases don't get replies. + */ + if (request->packet->code == PW_DHCP_RELEASE) { + request->reply->code = 0; + } + + if (request->reply->code == 0) { + return 1; + } + + request->reply->sockfd = request->packet->sockfd; + + /* + * Copy specific fields from packet to reply, if they + * don't already exist + */ + for (i = 0; i < sizeof(attrnums) / sizeof(attrnums[0]); i++) { + uint32_t attr = attrnums[i]; + + if (fr_pair_find_by_num(request->reply->vps, attr, DHCP_MAGIC_VENDOR, TAG_ANY)) continue; + + vp = fr_pair_find_by_num(request->packet->vps, attr, DHCP_MAGIC_VENDOR, TAG_ANY); + if (vp) { + fr_pair_add(&request->reply->vps, fr_pair_copy(request->reply, vp)); + } + } + + vp = fr_pair_find_by_num(request->reply->vps, 256, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Opcode */ + rad_assert(vp != NULL); + vp->vp_byte = 2; /* BOOTREPLY */ + + /* + * Allow NAKs to be delayed for a short period of time. + */ + if (request->reply->code == PW_DHCP_NAK) { + vp = fr_pair_find_by_num(request->reply->vps, PW_FREERADIUS_RESPONSE_DELAY, 0, TAG_ANY); + if (vp) { + if (vp->vp_integer <= 10) { + request->response_delay.tv_sec = vp->vp_integer; + request->response_delay.tv_usec = 0; + } else { + request->response_delay.tv_sec = 10; + request->response_delay.tv_usec = 0; + } + } else { +#define USEC 1000000 + vp = fr_pair_find_by_num(request->reply->vps, PW_FREERADIUS_RESPONSE_DELAY_USEC, 0, TAG_ANY); + if (vp) { + if (vp->vp_integer <= 10 * USEC) { + request->response_delay.tv_sec = vp->vp_integer / USEC; + request->response_delay.tv_usec = vp->vp_integer % USEC; + } else { + request->response_delay.tv_sec = 10; + request->response_delay.tv_usec = 0; + } + } + } + } + + /* + * Prepare the reply packet for sending through dhcp_socket_send() + */ + request->reply->dst_ipaddr.af = AF_INET; + request->reply->src_ipaddr.af = AF_INET; + request->reply->src_ipaddr.prefix = 32; + + /* + * Packet-Src-IP-Address has highest precedence + */ + vp = fr_pair_find_by_num(request->reply->vps, PW_PACKET_SRC_IP_ADDRESS, 0, TAG_ANY); + if (vp) { + request->reply->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + /* + * The request was unicast (via a relay) + */ + } else if (request->packet->dst_ipaddr.ipaddr.ip4addr.s_addr != htonl(INADDR_BROADCAST) && + request->packet->dst_ipaddr.ipaddr.ip4addr.s_addr != htonl(INADDR_ANY)) { + request->reply->src_ipaddr.ipaddr.ip4addr.s_addr = request->packet->dst_ipaddr.ipaddr.ip4addr.s_addr; + /* + * The listener was bound to an IP address, or we determined + * the address automatically, as it was the only address bound + * to the interface, and we bound to the interface. + */ + } else if (sock->src_ipaddr.ipaddr.ip4addr.s_addr != htonl(INADDR_ANY)) { + request->reply->src_ipaddr.ipaddr.ip4addr.s_addr = sock->src_ipaddr.ipaddr.ip4addr.s_addr; + /* + * There's a Server-Identification attribute + */ + } else if ((vp = fr_pair_find_by_num(request->reply->vps, 54, DHCP_MAGIC_VENDOR, TAG_ANY))) { + request->reply->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + } else { + REDEBUG("Unable to determine correct src_ipaddr for response"); + return -1; + } + request->reply->dst_port = request->packet->src_port; + request->reply->src_port = request->packet->dst_port; + + /* + * Answer to client's nearest DHCP relay. + * + * Which may be different than the giaddr given in the + * packet to the client. i.e. the relay may have a + * public IP, but the gateway a private one. + */ + vp = fr_pair_find_by_num(request->reply->vps, 272, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Relay-IP-Address */ + if (vp && (vp->vp_ipaddr != ntohl(INADDR_ANY))) { + RDEBUG("DHCP: Reply will be unicast to giaddr from original packet"); + request->reply->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + request->reply->dst_port = request->packet->dst_port; + + vp = fr_pair_find_by_num(request->reply->vps, PW_PACKET_DST_PORT, 0, TAG_ANY); + if (vp) request->reply->dst_port = vp->vp_integer; + + return 1; + } + + /* + * Answer to client's nearest DHCP gateway. In this + * case, the client can reach the gateway, as can the + * server. + * + * We also use *our* source port as the destination port. + * Gateways are servers, and listen on the server port, + * not the client port. + */ + vp = fr_pair_find_by_num(request->reply->vps, 266, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Gateway-IP-Address */ + if (vp && (vp->vp_ipaddr != htonl(INADDR_ANY))) { + RDEBUG("DHCP: Reply will be unicast to giaddr"); + request->reply->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + request->reply->dst_port = request->packet->dst_port; + return 1; + } + + /* + * If it's a NAK, or the broadcast flag was set, ond + * there's no client-ip-address, send a broadcast. + */ + if ((request->reply->code == PW_DHCP_NAK) || + ((vp = fr_pair_find_by_num(request->reply->vps, 262, DHCP_MAGIC_VENDOR, TAG_ANY)) && /* DHCP-Flags */ + (vp->vp_integer & 0x8000) && + ((vp = fr_pair_find_by_num(request->reply->vps, 263, DHCP_MAGIC_VENDOR, TAG_ANY)) && /* DHCP-Client-IP-Address */ + (vp->vp_ipaddr == htonl(INADDR_ANY))))) { + /* + * RFC 2131, page 23 + * + * Broadcast on + * - DHCPNAK + * or + * - Broadcast flag is set up and ciaddr == NULL + */ + RDEBUG("DHCP: Reply will be broadcast"); + request->reply->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_BROADCAST); + return 1; + } + + /* + * RFC 2131, page 23 + * + * Unicast to ciaddr if present, otherwise to yiaddr. + */ + if ((vp = fr_pair_find_by_num(request->reply->vps, 263, DHCP_MAGIC_VENDOR, TAG_ANY)) && /* DHCP-Client-IP-Address */ + (vp->vp_ipaddr != htonl(INADDR_ANY))) { + RDEBUG("DHCP: Reply will be sent unicast to client-ip-address"); + request->reply->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + return 1; + } + + vp = fr_pair_find_by_num(request->reply->vps, 264, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Your-IP-Address */ + if (!vp) { + RDEBUG("DHCP: Failed to find DHCP-Client-IP-Address or DHCP-Your-IP-Address for request; " + "not responding"); + /* + * There is nowhere to send the response to, so don't bother. + */ + request->reply->code = 0; + return -1; + } + +#ifdef SIOCSARP + /* + * The system is configured to listen for broadcast + * packets, which means we'll need to send unicast + * replies, to IPs which haven't yet been assigned. + * Therefore, we need to update the ARP table. + * + * However, they haven't specified a interface. So we + * can't update the ARP table. And we must send a + * broadcast response. + */ + if (sock->lsock.broadcast && !sock->src_interface) { + WARN("You MUST set \"interface\" if you have \"broadcast = yes\""); + RDEBUG("DHCP: Reply will be broadcast as no interface was defined"); + request->reply->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_BROADCAST); + return 1; + } + + RDEBUG("DHCP: Reply will be unicast to your-ip-address"); + request->reply->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr; + + /* + * When sending a DHCP_OFFER, make sure our ARP table + * contains an entry for the client IP address. + * Otherwise the packet may not be sent to the client, as + * the OS has no ARP entry for it. + * + * This is a cute hack to avoid us having to create a raw + * socket to send DHCP packets. + */ + if (request->reply->code == PW_DHCP_OFFER) { + VALUE_PAIR *hwvp = fr_pair_find_by_num(request->reply->vps, 267, DHCP_MAGIC_VENDOR, TAG_ANY); /* DHCP-Client-Hardware-Address */ + + if (!hwvp) return -1; + + if (fr_dhcp_add_arp_entry(request->reply->sockfd, sock->src_interface, hwvp, vp) < 0) { + RDEBUG("Failed adding ARP entry: %s", fr_strerror()); + return -1; + } + } +#else + if (request->packet->src_ipaddr.ipaddr.ip4addr.s_addr != ntohl(INADDR_NONE)) { + RDEBUG("DHCP: Request will be unicast to the unicast source IP address"); + request->reply->dst_ipaddr.ipaddr.ip4addr.s_addr = request->packet->src_ipaddr.ipaddr.ip4addr.s_addr; + } else { + RDEBUG("DHCP: Reply will be broadcast as this system does not support ARP updates"); + request->reply->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_BROADCAST); + } +#endif + + return 1; +} + +static int dhcp_socket_parse(CONF_SECTION *cs, rad_listen_t *this) +{ + int rcode, broadcast = 1; + int on = 1; + dhcp_socket_t *sock; + RADCLIENT *client; + CONF_PAIR *cp; + + /* + * Set if before parsing, so the user can forcibly turn + * it off later. + */ + this->nodup = true; + + rcode = common_socket_parse(cs, this); + if (rcode != 0) return rcode; + + if (check_config) return 0; + + sock = this->data; + + if (!sock->lsock.interface) { + WARN("No \"interface\" setting is defined. Only unicast DHCP will work"); + } + + /* + * See whether or not we enable broadcast packets. + */ + cp = cf_pair_find(cs, "broadcast"); + if (cp) { + char const *value = cf_pair_value(cp); + if (value && (strcmp(value, "no") == 0)) { + broadcast = 0; + } + } + + if (broadcast) { + if (setsockopt(this->fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) { + ERROR("Can't set broadcast option: %s\n", + fr_syserror(errno)); + return -1; + } + } + + if (setsockopt(this->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) { + ERROR("Can't set re-use address option: %s\n", + fr_syserror(errno)); + return -1; + } + + /* + * Undocumented extension for testing without + * destroying your network! + */ + sock->suppress_responses = false; + cp = cf_pair_find(cs, "suppress_responses"); + if (cp) { + rcode = cf_item_parse(cs, "suppress_responses", FR_ITEM_POINTER(PW_TYPE_BOOLEAN, &sock->suppress_responses), NULL); + if (rcode < 0) return -1; + } + + cp = cf_pair_find(cs, "src_interface"); + if (cp) { + rcode = cf_item_parse(cs, "src_interface", FR_ITEM_POINTER(PW_TYPE_STRING, &sock->src_interface), NULL); + if (rcode < 0) return -1; + } else { + sock->src_interface = sock->lsock.interface; + } + + if (!sock->src_interface && sock->lsock.interface) { + sock->src_interface = talloc_typed_strdup(sock, sock->lsock.interface); + } + + cp = cf_pair_find(cs, "src_ipaddr"); + if (cp) { + memset(&sock->src_ipaddr, 0, sizeof(sock->src_ipaddr)); + sock->src_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE); + rcode = cf_item_parse(cs, "src_ipaddr", FR_ITEM_POINTER(PW_TYPE_IPV4_ADDR, &sock->src_ipaddr), NULL); + if (rcode < 0) return -1; + + sock->src_ipaddr.af = AF_INET; + } else { + memcpy(&sock->src_ipaddr, &sock->lsock.my_ipaddr, sizeof(sock->src_ipaddr)); + } + + /* + * Initialize the fake client. + */ + client = &sock->dhcp_client; + memset(client, 0, sizeof(*client)); + client->ipaddr.af = AF_INET; + client->ipaddr.ipaddr.ip4addr.s_addr = ntohl(INADDR_NONE); + client->ipaddr.prefix = 0; + client->longname = client->shortname = "dhcp"; + client->secret = client->shortname; + client->nas_type = talloc_typed_strdup(sock, "none"); + + return 0; +} + + +/* + * Check if an incoming request is "ok" + * + * It takes packets, not requests. It sees if the packet looks + * OK. If so, it does a number of sanity checks on it. + */ +static int dhcp_socket_recv(rad_listen_t *listener) +{ + RADIUS_PACKET *packet; + dhcp_socket_t *sock; + + packet = fr_dhcp_recv(listener->fd); + if (!packet) { + ERROR("%s", fr_strerror()); + return 0; + } + + sock = listener->data; + if (!request_receive(NULL, listener, packet, &sock->dhcp_client, dhcp_process)) { + rad_free(&packet); + return 0; + } + + return 1; +} + + +/* + * Send an authentication response packet + */ +static int dhcp_socket_send(rad_listen_t *listener, REQUEST *request) +{ + dhcp_socket_t *sock; + + rad_assert(request->listener == listener); + rad_assert(listener->send == dhcp_socket_send); + + if (request->reply->code == 0) return 0; /* don't reply */ + + if (fr_dhcp_encode(request->reply) < 0) { + DEBUG("dhcp_socket_send: ERROR\n"); + return -1; + } + + sock = listener->data; + if (sock->suppress_responses) return 0; + + return fr_dhcp_send(request->reply); +} + + +static int dhcp_socket_encode(UNUSED rad_listen_t *listener, UNUSED REQUEST *request) +{ + DEBUG2("NO ENCODE!"); + return 0; +} + + +static int dhcp_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request) +{ + return fr_dhcp_decode(request->packet); +} + +extern fr_protocol_t proto_dhcp; +fr_protocol_t proto_dhcp = { + .magic = RLM_MODULE_INIT, + .name = "dhcp", + .inst_size = sizeof(dhcp_socket_t), + .parse = dhcp_socket_parse, + .recv = dhcp_socket_recv, + .send = dhcp_socket_send, + .print = common_socket_print, + .encode = dhcp_socket_encode, + .decode = dhcp_socket_decode +}; diff --git a/src/modules/proto_dhcp/libfreeradius-dhcp.mk b/src/modules/proto_dhcp/libfreeradius-dhcp.mk new file mode 100644 index 0000000..ab2cfc4 --- /dev/null +++ b/src/modules/proto_dhcp/libfreeradius-dhcp.mk @@ -0,0 +1,3 @@ +TARGET := libfreeradius-dhcp.a + +SOURCES := dhcp.c diff --git a/src/modules/proto_dhcp/proto_dhcp.mk b/src/modules/proto_dhcp/proto_dhcp.mk new file mode 100644 index 0000000..c0baeca --- /dev/null +++ b/src/modules/proto_dhcp/proto_dhcp.mk @@ -0,0 +1,9 @@ +TARGETNAME := proto_dhcp + +ifneq "$(TARGETNAME)" "" +TARGET := $(TARGETNAME).a +endif + +SOURCES := dhcpd.c + +TGT_PREREQS := libfreeradius-dhcp.a diff --git a/src/modules/proto_dhcp/rlm_dhcp.c b/src/modules/proto_dhcp/rlm_dhcp.c new file mode 100644 index 0000000..1cd73ff --- /dev/null +++ b/src/modules/proto_dhcp/rlm_dhcp.c @@ -0,0 +1,203 @@ +/* + * This program is is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or (at + * your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + */ + +/** + * $Id$ + * @file rlm_dhcp.c + * @brief Will contain dhcp listener code. + * + * @copyright 2012 The FreeRADIUS server project + */ +RCSID("$Id$") + +#include <freeradius-devel/libradius.h> + +#include <freeradius-devel/radiusd.h> +#include <freeradius-devel/modules.h> +#include <freeradius-devel/dhcp.h> + +#include <ctype.h> + +#define PW_DHCP_PARAMETER_REQUEST_LIST 55 + +/* + * Define a structure for our module configuration. + * + * These variables do not need to be in a structure, but it's + * a lot cleaner to do so, and a pointer to the structure can + * be used as the instance handle. + */ +typedef struct rlm_dhcp_t { + int nothing; +} rlm_dhcp_t; + + +/* + * Allow single attribute values to be retrieved from the dhcp. + */ +static ssize_t dhcp_options_xlat(UNUSED void *instance, REQUEST *request, + char const *fmt, char *out, size_t freespace) +{ + vp_cursor_t cursor, src_cursor; + vp_tmpl_t src; + VALUE_PAIR *vp, *head = NULL; + int decoded = 0; + ssize_t slen; + + while (isspace((int) *fmt)) fmt++; + + slen = tmpl_from_attr_str(&src, fmt, REQUEST_CURRENT, PAIR_LIST_REQUEST, false, false); + if (slen <= 0) { + REMARKER(fmt, slen, fr_strerror()); + error: + *out = '\0'; + return -1; + } + + if (src.type != TMPL_TYPE_ATTR) { + REDEBUG("dhcp_options cannot operate on a %s", fr_int2str(tmpl_names, src.type, "<INVALID>")); + goto error; + } + + if (src.tmpl_da->type != PW_TYPE_OCTETS) { + REDEBUG("dhcp_options got a %s attribute needed octets", + fr_int2str(dict_attr_types, src.tmpl_da->type, "<INVALID>")); + goto error; + } + + for (vp = tmpl_cursor_init(NULL, &src_cursor, request, &src); + vp; + vp = tmpl_cursor_next(&src_cursor, &src)) { + /* + * @fixme: we should pass in a cursor, then decoding multiple + * source attributes can be made atomic. + */ + if ((fr_dhcp_decode_options(request->packet, &head, vp->vp_octets, vp->vp_length) < 0) || (!head)) { + RWDEBUG("DHCP option decoding failed: %s", fr_strerror()); + goto error; + } + + for (vp = fr_cursor_init(&cursor, &head); + vp; + vp = fr_cursor_next(&cursor)) { + rdebug_pair(L_DBG_LVL_2, request, vp, "dhcp_options: "); + decoded++; + } + + fr_pair_list_move(request->packet, &(request->packet->vps), &head, T_OP_ADD); + + /* Free any unmoved pairs */ + fr_pair_list_free(&head); + } + + snprintf(out, freespace, "%i", decoded); + + return strlen(out); +} + +static ssize_t dhcp_xlat(UNUSED void *instance, REQUEST *request, char const *fmt, char *out, size_t freespace) +{ + vp_cursor_t cursor; + VALUE_PAIR *head = NULL, *vp; + uint8_t binbuf[1024]; + uint8_t *p = binbuf, *end = p + sizeof(binbuf); + ssize_t slen; + + while (isspace((int) *fmt)) fmt++; + + if ((radius_copy_vp(request, &head, request, fmt) < 0) || !head) { + *out = '\0'; + return 0; + } + fr_cursor_init(&cursor, &head); + + while ((vp = fr_cursor_current(&cursor))) { + slen = fr_dhcp_encode_option(request, p, end - p, &cursor); + talloc_free(vp); + if (slen <= 0) { + REDEBUG("DHCP option encoding failed: %s", fr_strerror()); + + return -1; + } + p += (size_t)slen; + } + + if ((size_t)(((p - binbuf) * 2) + 1) > freespace) { + REDEBUG("DHCP option encoding failed: Output buffer exhausted, needed %zd bytes, have %zd bytes", + ((p - binbuf) * 2) + 1, freespace); + + return -1; + } + + return fr_bin2hex(out, binbuf, (p - binbuf)); +} + + +/* + * Instantiate the module. + */ +static int mod_bootstrap(UNUSED CONF_SECTION *conf, void *instance) +{ + rlm_dhcp_t *inst = instance; + DICT_ATTR const *da; + + xlat_register("dhcp_options", dhcp_options_xlat, NULL, inst); + xlat_register("dhcp", dhcp_xlat, NULL, inst); + + /* + * Fixup dictionary entry for DHCP-Paramter-Request-List adding all the options + */ + da = dict_attrbyvalue(PW_DHCP_PARAMETER_REQUEST_LIST, DHCP_MAGIC_VENDOR); + if (da) { + DICT_ATTR const *value; + int i; + + /* No padding or termination options */ + DEBUG3("Adding values for %s", da->name); + for (i = 1; i < 255; i++) { + value = dict_attrbyvalue(i, DHCP_MAGIC_VENDOR); + if (!value) { + DEBUG3("No DHCP RFC space attribute at %i", i); + continue; + } + + DEBUG3("Adding %s value %i %s", da->name, i, value->name); + if (dict_addvalue(value->name, da->name, i) < 0) { + DEBUG3("Failed adding value: %s", fr_strerror()); + } + } + } + + return 0; +} + + +/* + * The module name should be the only globally exported symbol. + * That is, everything else should be 'static'. + * + * If the module needs to temporarily modify it's instantiation + * data, the type should be changed to RLM_TYPE_THREAD_UNSAFE. + * The server will then take care of ensuring that the module + * is single-threaded. + */ +extern module_t rlm_dhcp; +module_t rlm_dhcp = { + .magic = RLM_MODULE_INIT, + .name = "dhcp", + .inst_size = sizeof(rlm_dhcp_t), + .bootstrap = mod_bootstrap, +}; diff --git a/src/modules/proto_dhcp/rlm_dhcp.mk b/src/modules/proto_dhcp/rlm_dhcp.mk new file mode 100644 index 0000000..9cd33c4 --- /dev/null +++ b/src/modules/proto_dhcp/rlm_dhcp.mk @@ -0,0 +1,4 @@ +TARGET := rlm_dhcp.a +SOURCES := rlm_dhcp.c + +TGT_PREREQS := libfreeradius-dhcp.a |