summaryrefslogtreecommitdiffstats
path: root/net/udhcpsnoop/src/dhcp.c
blob: 3d27927232820aaa24cda59495d6d880f38c7914 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// SPDX-License-Identifier: GPL-2.0+
/*
 * Copyright (C) 2022 Felix Fietkau <nbd@nbd.name>
 */

#include "dhcpsnoop.h"
#include "msg.h"

const char *dhcpsnoop_parse_ipv4(const void *buf, size_t len, uint16_t port, uint32_t *expire)
{
	const struct dhcpv4_message *msg = buf;
	const uint8_t *pos, *end;
	uint32_t leasetime = 0, rebind = 0, renew = 0;
	char type = 0;

	if (port != 67 && port != 68)
		return NULL;

	if (len < sizeof(*msg))
		return NULL;

	if (ntohl(msg->magic) != DHCPV4_MAGIC)
		return NULL;

	pos = msg->options;
	end = buf + len;

	while (pos < end) {
		const uint8_t *opt = pos++;

		if (*opt == DHCPV4_OPT_END)
			break;

		if (*opt == DHCPV4_OPT_PAD)
			continue;

		if (pos >= end || 1 + *pos > end - pos)
			break;

		pos += *pos + 1;
		if (pos >= end)
			break;

		switch (*opt) {
		case DHCPV4_OPT_MSG_TYPE:
			if (!opt[1])
				continue;
			type = opt[2];
			break;
		case DHCPV4_OPT_LEASETIME:
			if (opt[1] != 4)
				continue;
			leasetime = *((uint32_t *) &opt[2]);
			break;
		case DHCPV4_OPT_REBIND:
			if (opt[1] != 4)
				continue;
			rebind = *((uint32_t *) &opt[2]);
			break;
		case DHCPV4_OPT_RENEW:
			if (opt[1] != 4)
				continue;
			renew = *((uint32_t *) &opt[2]);
			break;
		}
	}

	if (renew)
		*expire = renew;
	else if (rebind)
		*expire = rebind;
	else if (leasetime)
		*expire = leasetime;
	else
		*expire = 24 * 60 * 60;
	*expire = ntohl(*expire);

	switch(type) {
	case DHCPV4_MSG_ACK:
		return "ack";
	case DHCPV4_MSG_DISCOVER:
		return "discover";
	case DHCPV4_MSG_OFFER:
		return "offer";
	case DHCPV4_MSG_REQUEST:
		return "request";
	}

	return NULL;
}

const char *dhcpsnoop_parse_ipv6(const void *buf, size_t len, uint16_t port)
{
	const struct dhcpv6_message *msg = buf;

	if (port != 546 && port != 547)
		return NULL;

	switch(msg->msg_type) {
	case DHCPV6_MSG_SOLICIT:
		return "solicit";
	case DHCPV6_MSG_REPLY:
		return "reply";
	case DHCPV6_MSG_RENEW:
		return "renew";
	default:
		return NULL;
	}
}