1 /*
2  * Copyright (c) 2016 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef _DNS_PACK_H_
8 #define _DNS_PACK_H_
9 
10 #include <net/net_ip.h>
11 #include <net/buf.h>
12 
13 #include <zephyr/types.h>
14 #include <stddef.h>
15 #include <errno.h>
16 
17 /* See RFC 1035, 4.1.1 Header section format
18  * DNS Message Header is always 12 bytes
19  */
20 #define DNS_MSG_HEADER_SIZE	12
21 
22 /* This is the label's length octet, see 4.1.2. Question section format */
23 #define DNS_LABEL_LEN_SIZE	1
24 #define DNS_POINTER_SIZE	2
25 #define DNS_LABEL_MIN_SIZE	1
26 #define DNS_LABEL_MAX_SIZE	63
27 #define DNS_NAME_MAX_SIZE       255
28 #define DNS_ANSWER_MIN_SIZE	12
29 #define DNS_COMMON_UINT_SIZE	2
30 
31 #define DNS_HEADER_ID_LEN	2
32 #define DNS_HEADER_FLAGS_LEN	2
33 #define DNS_QTYPE_LEN		2
34 #define DNS_QCLASS_LEN		2
35 #define DNS_QDCOUNT_LEN		2
36 #define DNS_ANCOUNT_LEN		2
37 #define DNS_NSCOUNT_LEN		2
38 #define DNS_ARCOUNT_LEN		2
39 #define DNS_TTL_LEN		4
40 #define DNS_RDLENGTH_LEN	2
41 
42 #define NS_CMPRSFLGS    0xc0   /* DNS name compression */
43 
44 /* RFC 1035 '4.1.1. Header section format' defines the following flags:
45  * QR, Opcode, AA, TC, RD, RA, Z and RCODE.
46  * This implementation only uses RD (Recursion Desired).
47  */
48 #define DNS_RECURSION		1
49 
50 /* These two defines represent the 3rd and 4th bytes of the DNS msg header.
51  * See RFC 1035, 4.1.1. Header section format.
52  */
53 #define DNS_FLAGS1		DNS_RECURSION	/* QR, Opcode, AA, and TC = 0 */
54 #define DNS_FLAGS2		0		/* RA, Z and RCODE = 0 */
55 
56 /**
57  * DNS message structure for DNS responses
58  *
59  * Structure that points to the buffer containing the DNS message. It also
60  * contains some decodified message's properties that can not be recovered
61  * easily:
62  * - cname_offset
63  * - query_offset
64  * - answer_offset:
65  *     + response_type: It indicates the response's content type. It could be
66  *       an IP address, a CNAME with IP (two answers), a CNAME with no IP
67  *       address. See enum dns_response_type for more details.
68  *     + response_position: this is an offset. It holds the starting byte of
69  *       the field containing the desired info. For example an IPv4 address.
70  *     + response_length: this is an offset. It holds the response's length.
71  */
72 struct dns_msg_t {
73 	uint8_t *msg;
74 
75 	int response_type;
76 	uint16_t response_position;
77 	uint16_t response_length;
78 
79 	uint16_t query_offset;
80 	uint16_t answer_offset;
81 	uint16_t msg_size;
82 };
83 
84 #define DNS_MSG_INIT(b, s)	{.msg = b, .msg_size = s,	\
85 				 .response_type = -EINVAL}
86 
87 
88 enum dns_rr_type {
89 	DNS_RR_TYPE_INVALID = 0,
90 	DNS_RR_TYPE_A	= 1,		/* IPv4  */
91 	DNS_RR_TYPE_CNAME = 5,		/* CNAME */
92 	DNS_RR_TYPE_PTR = 12,		/* PTR   */
93 	DNS_RR_TYPE_TXT = 16,		/* TXT   */
94 	DNS_RR_TYPE_AAAA = 28,		/* IPv6  */
95 	DNS_RR_TYPE_SRV = 33,		/* SRV   */
96 };
97 
98 enum dns_response_type {
99 	DNS_RESPONSE_INVALID = -EINVAL,
100 	DNS_RESPONSE_IP,
101 	DNS_RESPONSE_CNAME_WITH_IP,
102 	DNS_RESPONSE_CNAME_NO_IP
103 };
104 
105 enum dns_class {
106 	DNS_CLASS_INVALID = 0,
107 	DNS_CLASS_IN,
108 	DNS_CLASS_FLUSH = BIT(15)
109 };
110 
111 enum dns_msg_type {
112 	DNS_QUERY = 0,
113 	DNS_RESPONSE
114 };
115 
116 enum dns_header_rcode {
117 	DNS_HEADER_NOERROR = 0,
118 	DNS_HEADER_FORMATERROR,
119 	DNS_HEADER_SERVERFAILURE,
120 	DNS_HEADER_NAMEERROR,
121 	DNS_HEADER_NOTIMPLEMENTED,
122 	DNS_HEADER_REFUSED
123 };
124 
125 struct dns_header {
126 	/** Transaction ID */
127 	uint16_t id;
128 	/**
129 	 * | Name | Bit Position | Width | Description |
130 	 * |------|--------------|-------|-------------|
131 	 * | RCODE | 0 | 4 | Response / Error code |
132 	 * | CD | 4 | 1 | |
133 	 * | AD | 5 | 1 | Authenticated Data. 0 := Unacceptable, 1 := Acceptable |
134 	 * | Z | 6 | 1 | Reserved (WZ/RAZ) |
135 	 * | RA | 7 | 1 | Recursion Available. 0 := Unavailable, 1 := Available |
136 	 * | RD | 8 | 1 | Recursion Desired. 0 := No Recursion, 1 := Recursion |
137 	 * | TC | 9 | 1 | 0 := Not Truncated, 1 := Truncated |
138 	 * | AA | 10 | 1 | Answer Authenticated / Answer Authoritative. 0 := Not Authenticated, 1 := Authenticated|
139 	 * | Opcode | 11 | 4 | See @ref dns_opcode |
140 	 * | QR | 15 | 1 | 0 := Query, 1 := Response |
141 	 */
142 	uint16_t flags;
143 	/** Query count */
144 	uint16_t qdcount;
145 	/** Answer count */
146 	uint16_t ancount;
147 	/** Authority count */
148 	uint16_t nscount;
149 	/** Additional information count */
150 	uint16_t arcount;
151 	/** Flexible array member for records */
152 	uint8_t data[];
153 } __packed;
154 
155 struct dns_query {
156 	uint16_t type;
157 	uint16_t class_;
158 } __packed;
159 
160 struct dns_rr {
161 	uint16_t type;
162 	uint16_t class_;
163 	uint32_t ttl;
164 	uint16_t rdlength;
165 	uint8_t rdata[];
166 } __packed;
167 
168 struct dns_srv_rdata {
169 	uint16_t priority;
170 	uint16_t weight;
171 	uint16_t port;
172 } __packed;
173 
174 struct dns_a_rdata {
175 	uint32_t address;
176 } __packed;
177 
178 struct dns_aaaa_rdata {
179 	uint8_t address[16];
180 } __packed;
181 
182 /** It returns the ID field in the DNS msg header	*/
dns_header_id(uint8_t * header)183 static inline int dns_header_id(uint8_t *header)
184 {
185 	return htons(UNALIGNED_GET((uint16_t *)(header)));
186 }
187 
188 /* inline unpack routines are used to unpack data from network
189  * order to cpu. Similar routines without the unpack prefix are
190  * used for cpu to network order.
191  */
dns_unpack_header_id(uint8_t * header)192 static inline int dns_unpack_header_id(uint8_t *header)
193 {
194 	return ntohs(UNALIGNED_GET((uint16_t *)(header)));
195 }
196 
197 /** It returns the QR field in the DNS msg header	*/
dns_header_qr(uint8_t * header)198 static inline int dns_header_qr(uint8_t *header)
199 {
200 	return ((*(header + 2)) & 0x80) ? 1 : 0;
201 }
202 
203 /** It returns the OPCODE field in the DNS msg header	*/
dns_header_opcode(uint8_t * header)204 static inline int dns_header_opcode(uint8_t *header)
205 {
206 	return ((*(header + 2)) & 0x70) >> 1;
207 }
208 
209 /** It returns the AA field in the DNS msg header	*/
dns_header_aa(uint8_t * header)210 static inline int dns_header_aa(uint8_t *header)
211 {
212 	return ((*(header + 2)) & 0x04) ? 1 : 0;
213 }
214 
215 /** It returns the TC field in the DNS msg header	*/
dns_header_tc(uint8_t * header)216 static inline int dns_header_tc(uint8_t *header)
217 {
218 	return ((*(header + 2)) & 0x02) ? 1 : 0;
219 }
220 
221 /** It returns the RD field in the DNS msg header	*/
dns_header_rd(uint8_t * header)222 static inline int dns_header_rd(uint8_t *header)
223 {
224 	return ((*(header + 2)) & 0x01) ? 1 : 0;
225 }
226 
227 /** It returns the RA field in the DNS msg header	*/
dns_header_ra(uint8_t * header)228 static inline int dns_header_ra(uint8_t *header)
229 {
230 	return ((*(header + 3)) & 0x80) >> 7;
231 }
232 
233 /** It returns the Z field in the DNS msg header	*/
dns_header_z(uint8_t * header)234 static inline int dns_header_z(uint8_t *header)
235 {
236 	return ((*(header + 3)) & 0x70) >> 4;
237 }
238 
239 /** It returns the RCODE field in the DNS msg header	*/
dns_header_rcode(uint8_t * header)240 static inline int dns_header_rcode(uint8_t *header)
241 {
242 	return ((*(header + 3)) & 0x0F);
243 }
244 
245 /** It returns the QDCOUNT field in the DNS msg header	*/
dns_header_qdcount(uint8_t * header)246 static inline int dns_header_qdcount(uint8_t *header)
247 {
248 	return htons(UNALIGNED_GET((uint16_t *)(header + 4)));
249 }
250 
dns_unpack_header_qdcount(uint8_t * header)251 static inline int dns_unpack_header_qdcount(uint8_t *header)
252 {
253 	return ntohs(UNALIGNED_GET((uint16_t *)(header + 4)));
254 }
255 
256 /** It returns the ANCOUNT field in the DNS msg header	*/
dns_header_ancount(uint8_t * header)257 static inline int dns_header_ancount(uint8_t *header)
258 {
259 	return htons(UNALIGNED_GET((uint16_t *)(header + 6)));
260 }
261 
dns_unpack_header_ancount(uint8_t * header)262 static inline int dns_unpack_header_ancount(uint8_t *header)
263 {
264 	return ntohs(UNALIGNED_GET((uint16_t *)(header + 6)));
265 }
266 
267 /** It returns the NSCOUNT field in the DNS msg header	*/
dns_header_nscount(uint8_t * header)268 static inline int dns_header_nscount(uint8_t *header)
269 {
270 	return htons(UNALIGNED_GET((uint16_t *)(header + 8)));
271 }
272 
273 /** It returns the ARCOUNT field in the DNS msg header	*/
dns_header_arcount(uint8_t * header)274 static inline int dns_header_arcount(uint8_t *header)
275 {
276 	return htons(UNALIGNED_GET((uint16_t *)(header + 10)));
277 }
278 
dns_query_qtype(uint8_t * question)279 static inline int dns_query_qtype(uint8_t *question)
280 {
281 	return htons(UNALIGNED_GET((uint16_t *)(question + 0)));
282 }
283 
dns_unpack_query_qtype(const uint8_t * question)284 static inline int dns_unpack_query_qtype(const uint8_t *question)
285 {
286 	return ntohs(UNALIGNED_GET((uint16_t *)(question + 0)));
287 }
288 
dns_query_qclass(uint8_t * question)289 static inline int dns_query_qclass(uint8_t *question)
290 {
291 	return htons(UNALIGNED_GET((uint16_t *)(question + 2)));
292 }
293 
dns_unpack_query_qclass(const uint8_t * question)294 static inline int dns_unpack_query_qclass(const uint8_t *question)
295 {
296 	return ntohs(UNALIGNED_GET((uint16_t *)(question + 2)));
297 }
298 
dns_answer_type(uint16_t dname_size,uint8_t * answer)299 static inline int dns_answer_type(uint16_t dname_size, uint8_t *answer)
300 {
301 	/* 4.1.3. Resource record format */
302 	return ntohs(UNALIGNED_GET((uint16_t *)(answer + dname_size + 0)));
303 }
304 
dns_answer_class(uint16_t dname_size,uint8_t * answer)305 static inline int dns_answer_class(uint16_t dname_size, uint8_t *answer)
306 {
307 	/* 4.1.3. Resource record format */
308 	return ntohs(UNALIGNED_GET((uint16_t *)(answer + dname_size + 2)));
309 }
310 
dns_answer_ttl(uint16_t dname_size,uint8_t * answer)311 static inline int dns_answer_ttl(uint16_t dname_size, uint8_t *answer)
312 {
313 	return ntohl(UNALIGNED_GET((uint32_t *)(answer + dname_size + 4)));
314 }
315 
dns_answer_rdlength(uint16_t dname_size,uint8_t * answer)316 static inline int dns_answer_rdlength(uint16_t dname_size,
317 					     uint8_t *answer)
318 {
319 	return ntohs(UNALIGNED_GET((uint16_t *)(answer + dname_size + 8)));
320 }
321 
322 /**
323  * @brief Packs a QNAME
324  *
325  * @param len Bytes used by this function
326  * @param buf Buffer
327  * @param sizeof Buffer's size
328  * @param domain_name Something like www.example.com
329  * @retval 0 on success
330  * @retval -ENOMEM if there is no enough space to store the resultant QNAME
331  * @retval -EINVAL if an invalid parameter was passed as an argument
332  */
333 int dns_msg_pack_qname(uint16_t *len, uint8_t *buf, uint16_t size,
334 		       const char *domain_name);
335 
336 /**
337  * @brief Unpacks an answer message
338  *
339  * @param dns_msg Structure
340  * @param dname_ptr An index to the previous CNAME. For example for the
341  *        first answer, ptr must be 0x0c, the DNAME at the question.
342  * @param ttl TTL answer parameter.
343  * @param type Answer type parameter.
344  * @retval 0 on success
345  * @retval -ENOMEM on error
346  */
347 int dns_unpack_answer(struct dns_msg_t *dns_msg, int dname_ptr, uint32_t *ttl,
348 		      enum dns_rr_type *type);
349 
350 /**
351  * @brief Unpacks the header's response.
352  *
353  * @param msg Structure containing the response.
354  * @param src_id Transaction id, it must match the id used in the query
355  *        datagram sent to the DNS server.
356  * @retval 0 on success
357  * @retval -ENOMEM if the buffer in msg has no enough space to store the header.
358  *         The header is always 12 bytes length.
359  * @retval -EINVAL if the src_id does not match the header's id, or if the
360  *         header's QR value is not DNS_RESPONSE or if the header's OPCODE
361  *         value is not DNS_QUERY, or if the header's Z value is not 0 or if
362  *         the question counter is not 1 or the answer counter is less than 1.
363  * @retval RFC 1035 RCODEs (> 0) 1 Format error, 2 Server failure, 3 Name Error,
364  *         4 Not Implemented and 5 Refused.
365  */
366 int dns_unpack_response_header(struct dns_msg_t *msg, int src_id);
367 
368 /**
369  * @brief Packs the query message
370  *
371  * @param buf Buffer that will contain the resultant query
372  * @param len Number of bytes used to encode the query
373  * @param size Buffer size
374  * @param qname Domain name represented as a sequence of labels.
375  *        See RFC 1035, 4.1.2. Question section format.
376  * @param qname_len Number of octets in qname.
377  * @param id Transaction Identifier
378  * @param qtype Query type: AA, AAAA. See enum dns_rr_type
379  * @retval 0 on success
380  * @retval On error, a negative value is returned.
381  *         See: dns_msg_pack_query_header and  dns_msg_pack_qname.
382  */
383 int dns_msg_pack_query(uint8_t *buf, uint16_t *len, uint16_t size,
384 		       uint8_t *qname, uint16_t qname_len, uint16_t id,
385 		       enum dns_rr_type qtype);
386 
387 /**
388  * @brief Unpacks the response's query.
389  *
390  * @details RFC 1035 states that the response's query comes after the first
391  *          12 bytes i.e., after the message's header. This function computes
392  *          the answer_offset field.
393  *
394  * @param dns_msg Structure containing the message.
395  * @retval 0 on success
396  * @retval -ENOMEM if the null label is not found after traversing the buffer
397  *         or if QCLASS and QTYPE are not found.
398  * @retval -EINVAL if QTYPE is not "A" (IPv4) or "AAAA" (IPv6) or if QCLASS
399  *         is not "IN".
400  */
401 int dns_unpack_response_query(struct dns_msg_t *dns_msg);
402 
403 /**
404  * @brief Copies the qname from dns_msg to buf
405  *
406  * @details This routine implements the algorithm described in RFC 1035, 4.1.4.
407  *          Message compression to copy the qname (perhaps containing pointers
408  *          with offset) to the linear buffer buf. Pointers are removed and
409  *          only the "true" labels are copied.
410  *
411  * @param buf Output buffer
412  * @param len Output buffer's length
413  * @param size Output buffer's size
414  * @param dns_msg Structure containing the message
415  * @param pos QNAME's position in dns_msg->msg
416  * @retval 0 on success
417  * @retval -EINVAL if an invalid parameter was passed as an argument
418  * @retval -ENOMEM if the label's size is corrupted
419  */
420 int dns_copy_qname(uint8_t *buf, uint16_t *len, uint16_t size,
421 		   struct dns_msg_t *dns_msg, uint16_t pos);
422 
423 /**
424  * @brief Unpacks the mDNS query. This is special version for multicast DNS
425  *        as it skips checks to various fields as described in RFC 6762
426  *        chapter 18.
427  *
428  * @param msg Structure containing the response.
429  * @param src_id Transaction id, this is returned to the caller.
430  * @retval 0 on success, <0 if error
431  * @retval -ENOMEM if the buffer in msg has no enough space to store the header.
432  *         The header is always 12 bytes length.
433  * @retval -EINVAL if the src_id does not match the header's id, or if the
434  *         header's QR value is not DNS_RESPONSE or if the header's OPCODE
435  *         value is not DNS_QUERY, or if the header's Z value is not 0 or if
436  *         the question counter is not 1 or the answer counter is less than 1.
437  * @retval RFC 1035 RCODEs (> 0) 1 Format error, 2 Server failure, 3 Name Error,
438  *         4 Not Implemented and 5 Refused.
439  */
440 int mdns_unpack_query_header(struct dns_msg_t *msg, uint16_t *src_id);
441 
llmnr_unpack_query_header(struct dns_msg_t * msg,uint16_t * src_id)442 static inline int llmnr_unpack_query_header(struct dns_msg_t *msg,
443 					    uint16_t *src_id)
444 {
445 	return mdns_unpack_query_header(msg, src_id);
446 }
447 
448 /**
449  * @brief Unpacks the query.
450  *
451  * @param dns_msg Structure containing the message.
452  * @param buf Result buf
453  * @param qtype Query type is returned to caller
454  * @param qclass Query class is returned to caller
455  * @retval 0 on success
456  * @retval -ENOMEM if the null label is not found after traversing the buffer
457  *         or if QCLASS and QTYPE are not found.
458  * @retval -EINVAL if QTYPE is not "A" (IPv4) or "AAAA" (IPv6) or if QCLASS
459  *         is not "IN".
460  */
461 int dns_unpack_query(struct dns_msg_t *dns_msg, struct net_buf *buf,
462 		     enum dns_rr_type *qtype,
463 		     enum dns_class *qclass);
464 
465 #endif
466