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 <zephyr/net/net_ip.h>
11 #include <zephyr/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 	DNS_RR_TYPE_ANY = 0xff,		/* ANY (all records)   */
97 };
98 
99 enum dns_response_type {
100 	DNS_RESPONSE_INVALID = -EINVAL,
101 	DNS_RESPONSE_IP,
102 	DNS_RESPONSE_CNAME_WITH_IP,
103 	DNS_RESPONSE_CNAME_NO_IP
104 };
105 
106 enum dns_class {
107 	DNS_CLASS_INVALID = 0,
108 	DNS_CLASS_IN,
109 	DNS_CLASS_FLUSH = BIT(15)
110 };
111 
112 enum dns_msg_type {
113 	DNS_QUERY = 0,
114 	DNS_RESPONSE
115 };
116 
117 enum dns_header_rcode {
118 	DNS_HEADER_NOERROR = 0,
119 	DNS_HEADER_FORMATERROR,
120 	DNS_HEADER_SERVERFAILURE,
121 	DNS_HEADER_NAMEERROR,
122 	DNS_HEADER_NOTIMPLEMENTED,
123 	DNS_HEADER_REFUSED
124 };
125 
126 struct dns_header {
127 	/** Transaction ID */
128 	uint16_t id;
129 	/**
130 	 * | Name | Bit Position | Width | Description |
131 	 * |------|--------------|-------|-------------|
132 	 * | RCODE | 0 | 4 | Response / Error code |
133 	 * | CD | 4 | 1 | |
134 	 * | AD | 5 | 1 | Authenticated Data. 0 := Unacceptable, 1 := Acceptable |
135 	 * | Z | 6 | 1 | Reserved (WZ/RAZ) |
136 	 * | RA | 7 | 1 | Recursion Available. 0 := Unavailable, 1 := Available |
137 	 * | RD | 8 | 1 | Recursion Desired. 0 := No Recursion, 1 := Recursion |
138 	 * | TC | 9 | 1 | 0 := Not Truncated, 1 := Truncated |
139 	 * | AA | 10 | 1 | Answer Authenticated / Answer Authoritative. 0 := Not Authenticated, 1 := Authenticated|
140 	 * | Opcode | 11 | 4 | See @ref dns_opcode |
141 	 * | QR | 15 | 1 | 0 := Query, 1 := Response |
142 	 */
143 	uint16_t flags;
144 	/** Query count */
145 	uint16_t qdcount;
146 	/** Answer count */
147 	uint16_t ancount;
148 	/** Authority count */
149 	uint16_t nscount;
150 	/** Additional information count */
151 	uint16_t arcount;
152 	/** Flexible array member for records */
153 	uint8_t data[];
154 } __packed;
155 
156 struct dns_query {
157 	uint16_t type;
158 	uint16_t class_;
159 } __packed;
160 
161 struct dns_rr {
162 	uint16_t type;
163 	uint16_t class_;
164 	uint32_t ttl;
165 	uint16_t rdlength;
166 	uint8_t rdata[];
167 } __packed;
168 
169 struct dns_srv_rdata {
170 	uint16_t priority;
171 	uint16_t weight;
172 	uint16_t port;
173 } __packed;
174 
175 struct dns_a_rdata {
176 	uint32_t address;
177 } __packed;
178 
179 struct dns_aaaa_rdata {
180 	uint8_t address[16];
181 } __packed;
182 
183 /** It returns the ID field in the DNS msg header	*/
dns_header_id(uint8_t * header)184 static inline int dns_header_id(uint8_t *header)
185 {
186 	return htons(UNALIGNED_GET((uint16_t *)(header)));
187 }
188 
189 /* inline unpack routines are used to unpack data from network
190  * order to cpu. Similar routines without the unpack prefix are
191  * used for cpu to network order.
192  */
dns_unpack_header_id(uint8_t * header)193 static inline int dns_unpack_header_id(uint8_t *header)
194 {
195 	return ntohs(UNALIGNED_GET((uint16_t *)(header)));
196 }
197 
198 /** It returns the QR field in the DNS msg header	*/
dns_header_qr(uint8_t * header)199 static inline int dns_header_qr(uint8_t *header)
200 {
201 	return ((*(header + 2)) & 0x80) ? 1 : 0;
202 }
203 
204 /** It returns the OPCODE field in the DNS msg header	*/
dns_header_opcode(uint8_t * header)205 static inline int dns_header_opcode(uint8_t *header)
206 {
207 	return ((*(header + 2)) & 0x70) >> 1;
208 }
209 
210 /** It returns the AA field in the DNS msg header	*/
dns_header_aa(uint8_t * header)211 static inline int dns_header_aa(uint8_t *header)
212 {
213 	return ((*(header + 2)) & 0x04) ? 1 : 0;
214 }
215 
216 /** It returns the TC field in the DNS msg header	*/
dns_header_tc(uint8_t * header)217 static inline int dns_header_tc(uint8_t *header)
218 {
219 	return ((*(header + 2)) & 0x02) ? 1 : 0;
220 }
221 
222 /** It returns the RD field in the DNS msg header	*/
dns_header_rd(uint8_t * header)223 static inline int dns_header_rd(uint8_t *header)
224 {
225 	return ((*(header + 2)) & 0x01) ? 1 : 0;
226 }
227 
228 /** It returns the RA field in the DNS msg header	*/
dns_header_ra(uint8_t * header)229 static inline int dns_header_ra(uint8_t *header)
230 {
231 	return ((*(header + 3)) & 0x80) >> 7;
232 }
233 
234 /** It returns the Z field in the DNS msg header	*/
dns_header_z(uint8_t * header)235 static inline int dns_header_z(uint8_t *header)
236 {
237 	return ((*(header + 3)) & 0x70) >> 4;
238 }
239 
240 /** It returns the RCODE field in the DNS msg header	*/
dns_header_rcode(uint8_t * header)241 static inline int dns_header_rcode(uint8_t *header)
242 {
243 	return ((*(header + 3)) & 0x0F);
244 }
245 
246 /** It returns the QDCOUNT field in the DNS msg header	*/
dns_header_qdcount(uint8_t * header)247 static inline int dns_header_qdcount(uint8_t *header)
248 {
249 	return htons(UNALIGNED_GET((uint16_t *)(header + 4)));
250 }
251 
dns_unpack_header_qdcount(uint8_t * header)252 static inline int dns_unpack_header_qdcount(uint8_t *header)
253 {
254 	return ntohs(UNALIGNED_GET((uint16_t *)(header + 4)));
255 }
256 
257 /** It returns the ANCOUNT field in the DNS msg header	*/
dns_header_ancount(uint8_t * header)258 static inline int dns_header_ancount(uint8_t *header)
259 {
260 	return htons(UNALIGNED_GET((uint16_t *)(header + 6)));
261 }
262 
dns_unpack_header_ancount(uint8_t * header)263 static inline int dns_unpack_header_ancount(uint8_t *header)
264 {
265 	return ntohs(UNALIGNED_GET((uint16_t *)(header + 6)));
266 }
267 
268 /** It returns the NSCOUNT field in the DNS msg header	*/
dns_header_nscount(uint8_t * header)269 static inline int dns_header_nscount(uint8_t *header)
270 {
271 	return htons(UNALIGNED_GET((uint16_t *)(header + 8)));
272 }
273 
274 /** It returns the ARCOUNT field in the DNS msg header	*/
dns_header_arcount(uint8_t * header)275 static inline int dns_header_arcount(uint8_t *header)
276 {
277 	return htons(UNALIGNED_GET((uint16_t *)(header + 10)));
278 }
279 
dns_query_qtype(uint8_t * question)280 static inline int dns_query_qtype(uint8_t *question)
281 {
282 	return htons(UNALIGNED_GET((uint16_t *)(question + 0)));
283 }
284 
dns_unpack_query_qtype(const uint8_t * question)285 static inline int dns_unpack_query_qtype(const uint8_t *question)
286 {
287 	return ntohs(UNALIGNED_GET((uint16_t *)(question + 0)));
288 }
289 
dns_query_qclass(uint8_t * question)290 static inline int dns_query_qclass(uint8_t *question)
291 {
292 	return htons(UNALIGNED_GET((uint16_t *)(question + 2)));
293 }
294 
dns_unpack_query_qclass(const uint8_t * question)295 static inline int dns_unpack_query_qclass(const uint8_t *question)
296 {
297 	return ntohs(UNALIGNED_GET((uint16_t *)(question + 2)));
298 }
299 
dns_answer_type(uint16_t dname_size,uint8_t * answer)300 static inline int dns_answer_type(uint16_t dname_size, uint8_t *answer)
301 {
302 	/* 4.1.3. Resource record format */
303 	return ntohs(UNALIGNED_GET((uint16_t *)(answer + dname_size + 0)));
304 }
305 
dns_answer_class(uint16_t dname_size,uint8_t * answer)306 static inline int dns_answer_class(uint16_t dname_size, uint8_t *answer)
307 {
308 	/* 4.1.3. Resource record format */
309 	return ntohs(UNALIGNED_GET((uint16_t *)(answer + dname_size + 2)));
310 }
311 
dns_answer_ttl(uint16_t dname_size,uint8_t * answer)312 static inline int dns_answer_ttl(uint16_t dname_size, uint8_t *answer)
313 {
314 	return ntohl(UNALIGNED_GET((uint32_t *)(answer + dname_size + 4)));
315 }
316 
dns_answer_rdlength(uint16_t dname_size,uint8_t * answer)317 static inline int dns_answer_rdlength(uint16_t dname_size,
318 					     uint8_t *answer)
319 {
320 	return ntohs(UNALIGNED_GET((uint16_t *)(answer + dname_size + 8)));
321 }
322 
323 /**
324  * @brief Packs a QNAME
325  *
326  * @param len Bytes used by this function
327  * @param buf Buffer
328  * @param sizeof Buffer's size
329  * @param domain_name Something like www.example.com
330  * @retval 0 on success
331  * @retval -ENOMEM if there is no enough space to store the resultant QNAME
332  * @retval -EINVAL if an invalid parameter was passed as an argument
333  */
334 int dns_msg_pack_qname(uint16_t *len, uint8_t *buf, uint16_t size,
335 		       const char *domain_name);
336 
337 /**
338  * @brief Unpacks an answer message
339  *
340  * @param dns_msg Structure
341  * @param dname_ptr An index to the previous CNAME. For example for the
342  *        first answer, ptr must be 0x0c, the DNAME at the question.
343  * @param ttl TTL answer parameter.
344  * @param type Answer type parameter.
345  * @retval 0 on success
346  * @retval -ENOMEM on error
347  */
348 int dns_unpack_answer(struct dns_msg_t *dns_msg, int dname_ptr, uint32_t *ttl,
349 		      enum dns_rr_type *type);
350 
351 /**
352  * @brief Unpacks the header's response.
353  *
354  * @param msg Structure containing the response.
355  * @param src_id Transaction id, it must match the id used in the query
356  *        datagram sent to the DNS server.
357  * @retval 0 on success
358  * @retval -ENOMEM if the buffer in msg has no enough space to store the header.
359  *         The header is always 12 bytes length.
360  * @retval -EINVAL if the src_id does not match the header's id, or if the
361  *         header's QR value is not DNS_RESPONSE or if the header's OPCODE
362  *         value is not DNS_QUERY, or if the header's Z value is not 0 or if
363  *         the question counter is not 1 or the answer counter is less than 1.
364  * @retval RFC 1035 RCODEs (> 0) 1 Format error, 2 Server failure, 3 Name Error,
365  *         4 Not Implemented and 5 Refused.
366  */
367 int dns_unpack_response_header(struct dns_msg_t *msg, int src_id);
368 
369 /**
370  * @brief Packs the query message
371  *
372  * @param buf Buffer that will contain the resultant query
373  * @param len Number of bytes used to encode the query
374  * @param size Buffer size
375  * @param qname Domain name represented as a sequence of labels.
376  *        See RFC 1035, 4.1.2. Question section format.
377  * @param qname_len Number of octets in qname.
378  * @param id Transaction Identifier
379  * @param qtype Query type: AA, AAAA. See enum dns_rr_type
380  * @retval 0 on success
381  * @retval On error, a negative value is returned.
382  *         See: dns_msg_pack_query_header and  dns_msg_pack_qname.
383  */
384 int dns_msg_pack_query(uint8_t *buf, uint16_t *len, uint16_t size,
385 		       uint8_t *qname, uint16_t qname_len, uint16_t id,
386 		       enum dns_rr_type qtype);
387 
388 /**
389  * @brief Unpacks the response's query.
390  *
391  * @details RFC 1035 states that the response's query comes after the first
392  *          12 bytes i.e., after the message's header. This function computes
393  *          the answer_offset field.
394  *
395  * @param dns_msg Structure containing the message.
396  * @retval 0 on success
397  * @retval -ENOMEM if the null label is not found after traversing the buffer
398  *         or if QCLASS and QTYPE are not found.
399  * @retval -EINVAL if QTYPE is not "A" (IPv4) or "AAAA" (IPv6) or if QCLASS
400  *         is not "IN".
401  */
402 int dns_unpack_response_query(struct dns_msg_t *dns_msg);
403 
404 /**
405  * @brief Copies the qname from dns_msg to buf
406  *
407  * @details This routine implements the algorithm described in RFC 1035, 4.1.4.
408  *          Message compression to copy the qname (perhaps containing pointers
409  *          with offset) to the linear buffer buf. Pointers are removed and
410  *          only the "true" labels are copied.
411  *
412  * @param buf Output buffer
413  * @param len Output buffer's length
414  * @param size Output buffer's size
415  * @param dns_msg Structure containing the message
416  * @param pos QNAME's position in dns_msg->msg
417  * @retval 0 on success
418  * @retval -EINVAL if an invalid parameter was passed as an argument
419  * @retval -ENOMEM if the label's size is corrupted
420  */
421 int dns_copy_qname(uint8_t *buf, uint16_t *len, uint16_t size,
422 		   struct dns_msg_t *dns_msg, uint16_t pos);
423 
424 /**
425  * @brief Unpacks the mDNS query. This is special version for multicast DNS
426  *        as it skips checks to various fields as described in RFC 6762
427  *        chapter 18.
428  *
429  * @param msg Structure containing the response.
430  * @param src_id Transaction id, this is returned to the caller.
431  * @retval 0 on success, <0 if error
432  * @retval -ENOMEM if the buffer in msg has no enough space to store the header.
433  *         The header is always 12 bytes length.
434  * @retval -EINVAL if the src_id does not match the header's id, or if the
435  *         header's QR value is not DNS_RESPONSE or if the header's OPCODE
436  *         value is not DNS_QUERY, or if the header's Z value is not 0 or if
437  *         the question counter is not 1 or the answer counter is less than 1.
438  * @retval RFC 1035 RCODEs (> 0) 1 Format error, 2 Server failure, 3 Name Error,
439  *         4 Not Implemented and 5 Refused.
440  */
441 int mdns_unpack_query_header(struct dns_msg_t *msg, uint16_t *src_id);
442 
llmnr_unpack_query_header(struct dns_msg_t * msg,uint16_t * src_id)443 static inline int llmnr_unpack_query_header(struct dns_msg_t *msg,
444 					    uint16_t *src_id)
445 {
446 	return mdns_unpack_query_header(msg, src_id);
447 }
448 
449 /**
450  * @brief Unpacks the query.
451  *
452  * @param dns_msg Structure containing the message.
453  * @param buf Result buf
454  * @param qtype Query type is returned to caller
455  * @param qclass Query class is returned to caller
456  * @retval 0 on success
457  * @retval -ENOMEM if the null label is not found after traversing the buffer
458  *         or if QCLASS and QTYPE are not found.
459  * @retval -EINVAL if QTYPE is not "A" (IPv4) or "AAAA" (IPv6) or if QCLASS
460  *         is not "IN".
461  */
462 int dns_unpack_query(struct dns_msg_t *dns_msg, struct net_buf *buf,
463 		     enum dns_rr_type *qtype,
464 		     enum dns_class *qclass);
465 
466 /**
467  * @brief Map query type number to a string.
468  *
469  * @param qtype Query type
470  *
471  * @return Printable query type name.
472  */
473 const char *dns_qtype_to_str(enum dns_rr_type qtype);
474 
475 #endif
476