xref: /freebsd/contrib/unbound/util/data/msgparse.h (revision 87b759f0fa1f7554d50ce640c40138512bbded44)
1 /*
2  * util/data/msgparse.h - parse wireformat DNS messages.
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 /**
36  * \file
37  * Contains message parsing data structures.
38  * These point back into the packet buffer.
39  *
40  * During parsing RRSIGS are put together with the rrsets they (claim to) sign.
41  * This process works as follows:
42  *	o if RRSIG follows the data rrset, it is added to the rrset rrsig list.
43  *	o if no matching data rrset is found, the RRSIG becomes a new rrset.
44  *	o If the data rrset later follows the RRSIG
45  *		o See if the RRSIG rrset contains multiple types, and needs to
46  *		  have the rrsig(s) for that data type split off.
47  *		o Put the data rr as data type in the rrset and rrsig in list.
48  *	o RRSIGs are allowed to move to a different section. The section of
49  *	  the data item is used for the final rrset.
50  *	o multiple signatures over an RRset are possible.
51  *
52  * For queries of qtype=RRSIG, some special handling is needed, to avoid
53  * splitting the RRSIG in the answer section.
54  *	o duplicate, not split, RRSIGs from the answer section, if qtype=RRSIG.
55  *	o check for doubles in the rrsig list when adding an RRSIG to data,
56  *	  so that a data rrset is signed by RRSIGs with different rdata.
57  *	  when qtype=RRSIG.
58  * This will move the RRSIG from the answer section to sign the data further
59  * in the packet (if possible). If then after that, more RRSIGs are found
60  * that sign the data as well, doubles are removed.
61  */
62 
63 #ifndef UTIL_DATA_MSGPARSE_H
64 #define UTIL_DATA_MSGPARSE_H
65 #include "util/storage/lruhash.h"
66 #include "sldns/pkthdr.h"
67 #include "sldns/rrdef.h"
68 struct sldns_buffer;
69 struct rrset_parse;
70 struct rr_parse;
71 struct regional;
72 struct edns_option;
73 struct config_file;
74 struct comm_point;
75 struct comm_reply;
76 struct cookie_secrets;
77 
78 /** number of buckets in parse rrset hash table. Must be power of 2. */
79 #define PARSE_TABLE_SIZE 32
80 /** Maximum TTL that is allowed. */
81 extern time_t MAX_TTL;
82 /** Minimum TTL that is allowed. */
83 extern time_t MIN_TTL;
84 /** Maximum Negative TTL that is allowed */
85 extern time_t MAX_NEG_TTL;
86 /** Minimum Negative TTL that is allowed */
87 extern time_t MIN_NEG_TTL;
88 /** If we serve expired entries and prefetch them */
89 extern int SERVE_EXPIRED;
90 /** Time to serve records after expiration */
91 extern time_t SERVE_EXPIRED_TTL;
92 /** TTL to use for expired records */
93 extern time_t SERVE_EXPIRED_REPLY_TTL;
94 /** Negative cache time (for entries without any RRs.) */
95 #define NORR_TTL 5 /* seconds */
96 /** If we serve the original TTL or decrementing TTLs */
97 extern int SERVE_ORIGINAL_TTL;
98 
99 /**
100  * Data stored in scratch pad memory during parsing.
101  * Stores the data that will enter into the msgreply and packet result.
102  */
103 struct msg_parse {
104 	/** id from message, network format. */
105 	uint16_t id;
106 	/** flags from message, host format. */
107 	uint16_t flags;
108 	/** count of RRs, host format */
109 	uint16_t qdcount;
110 	/** count of RRs, host format */
111 	uint16_t ancount;
112 	/** count of RRs, host format */
113 	uint16_t nscount;
114 	/** count of RRs, host format */
115 	uint16_t arcount;
116 	/** count of RRsets per section. */
117 	size_t an_rrsets;
118 	/** count of RRsets per section. */
119 	size_t ns_rrsets;
120 	/** count of RRsets per section. */
121 	size_t ar_rrsets;
122 	/** total number of rrsets found. */
123 	size_t rrset_count;
124 
125 	/** query dname (pointer to start location in packet, NULL if none */
126 	uint8_t* qname;
127 	/** length of query dname in octets, 0 if none */
128 	size_t qname_len;
129 	/** query type, host order. 0 if qdcount=0 */
130 	uint16_t qtype;
131 	/** query class, host order. 0 if qdcount=0 */
132 	uint16_t qclass;
133 
134 	/**
135 	 * Hash table array used during parsing to lookup rrset types.
136 	 * Based on name, type, class.  Same hash value as in rrset cache.
137 	 */
138 	struct rrset_parse* hashtable[PARSE_TABLE_SIZE];
139 
140 	/** linked list of rrsets that have been found (in order). */
141 	struct rrset_parse* rrset_first;
142 	/** last element of rrset list. */
143 	struct rrset_parse* rrset_last;
144 };
145 
146 /**
147  * Data stored for an rrset during parsing.
148  */
149 struct rrset_parse {
150 	/** next in hash bucket */
151 	struct rrset_parse* rrset_bucket_next;
152 	/** next in list of all rrsets */
153 	struct rrset_parse* rrset_all_next;
154 	/** hash value of rrset */
155 	hashvalue_type hash;
156 	/** which section was it found in: one of
157 	 * LDNS_SECTION_ANSWER, LDNS_SECTION_AUTHORITY, LDNS_SECTION_ADDITIONAL
158 	 */
159 	sldns_pkt_section section;
160 	/** start of (possibly compressed) dname in packet */
161 	uint8_t* dname;
162 	/** length of the dname uncompressed wireformat */
163 	size_t dname_len;
164 	/** type, host order. */
165 	uint16_t type;
166 	/** class, network order. var name so that it is not a c++ keyword. */
167 	uint16_t rrset_class;
168 	/** the flags for the rrset, like for packedrrset */
169 	uint32_t flags;
170 	/** number of RRs in the rr list */
171 	size_t rr_count;
172 	/** sum of RR rdata sizes */
173 	size_t size;
174 	/** linked list of RRs in this rrset. */
175 	struct rr_parse* rr_first;
176 	/** last in list of RRs in this rrset. */
177 	struct rr_parse* rr_last;
178 	/** number of RRSIGs over this rrset. */
179 	size_t rrsig_count;
180 	/** linked list of RRsig RRs over this rrset. */
181 	struct rr_parse* rrsig_first;
182 	/** last in list of RRSIG RRs over this rrset. */
183 	struct rr_parse* rrsig_last;
184 };
185 
186 /**
187  * Data stored for an RR during parsing.
188  */
189 struct rr_parse {
190 	/**
191 	 * Pointer to the RR. Points to start of TTL value in the packet.
192 	 * Rdata length and rdata follow it.
193 	 * its dname, type and class are the same and stored for the rrset.
194 	 */
195 	uint8_t* ttl_data;
196 	/** true if ttl_data is not part of the packet, but elsewhere in mem.
197 	 * Set for generated CNAMEs for DNAMEs. */
198 	int outside_packet;
199 	/** the length of the rdata if allocated (with no dname compression)*/
200 	size_t size;
201 	/** next in list of RRs. */
202 	struct rr_parse* next;
203 };
204 
205 /** Check if label length is first octet of a compression pointer, pass u8. */
206 #define LABEL_IS_PTR(x) ( ((x)&0xc0) == 0xc0 )
207 /** Calculate destination offset of a compression pointer. pass first and
208  * second octets of the compression pointer. */
209 #define PTR_OFFSET(x, y) ( ((x)&0x3f)<<8 | (y) )
210 /** create a compression pointer to the given offset. */
211 #define PTR_CREATE(offset) ((uint16_t)(0xc000 | (offset)))
212 
213 /** error codes, extended with EDNS, so > 15. */
214 #define EDNS_RCODE_BADVERS	16	/** bad EDNS version */
215 /** largest valid compression offset */
216 #define PTR_MAX_OFFSET 	0x3fff
217 
218 /**
219  * EDNS data storage
220  * rdata is parsed in a list (has accessor functions). allocated in a
221  * region.
222  */
223 struct edns_data {
224 	/** Extended RCODE */
225 	uint8_t ext_rcode;
226 	/** The EDNS version number */
227 	uint8_t edns_version;
228 	/** the EDNS bits field from ttl (host order): Z */
229 	uint16_t bits;
230 	/** UDP reassembly size. */
231 	uint16_t udp_size;
232 	/** rdata element list of options of an incoming packet created at
233 	 * parse time, or NULL if none */
234 	struct edns_option* opt_list_in;
235 	/** rdata element list of options to encode for outgoing packets,
236 	 * or NULL if none */
237 	struct edns_option* opt_list_out;
238 	/** rdata element list of outgoing edns options from modules
239 	 * or NULL if none */
240 	struct edns_option* opt_list_inplace_cb_out;
241 	/** block size to pad */
242 	uint16_t padding_block_size;
243 	/** if EDNS OPT record was present */
244 	unsigned int edns_present   : 1;
245 	/** if a cookie was present */
246 	unsigned int cookie_present : 1;
247 	/** if the cookie validated */
248 	unsigned int cookie_valid   : 1;
249 	/** if the cookie holds only the client part */
250 	unsigned int cookie_client  : 1;
251 };
252 
253 /**
254  * EDNS option
255  */
256 struct edns_option {
257 	/** next item in list */
258 	struct edns_option* next;
259 	/** type of this edns option */
260 	uint16_t opt_code;
261 	/** length of this edns option (cannot exceed uint16 in encoding) */
262 	size_t opt_len;
263 	/** data of this edns option; allocated in region, or NULL if len=0 */
264 	uint8_t* opt_data;
265 };
266 
267 /**
268  * Obtain size in the packet of an rr type, that is before dname type.
269  * Do TYPE_DNAME, and type STR, yourself. Gives size for most regular types.
270  * @param rdf: the rdf type from the descriptor.
271  * @return: size in octets. 0 on failure.
272  */
273 size_t get_rdf_size(sldns_rdf_type rdf);
274 
275 /**
276  * Parse the packet.
277  * @param pkt: packet, position at call must be at start of packet.
278  *	at end position is after packet.
279  * @param msg: where to store results.
280  * @param region: how to alloc results.
281  * @return: 0 if OK, or rcode on error.
282  */
283 int parse_packet(struct sldns_buffer* pkt, struct msg_parse* msg,
284 	struct regional* region);
285 
286 /**
287  * After parsing the packet, extract EDNS data from packet.
288  * If not present this is noted in the data structure.
289  * If a parse error happens, an error code is returned.
290  *
291  * Quirks:
292  *	o ignores OPT rdata.
293  *	o ignores OPT owner name.
294  *	o ignores extra OPT records, except the last one in the packet.
295  *
296  * @param msg: parsed message structure. Modified on exit, if EDNS was present
297  * 	it is removed from the additional section.
298  * @param edns: the edns data is stored here. Does not have to be initialised.
299  * @param region: region to alloc results in (edns option contents)
300  * @return: 0 on success. or an RCODE on an error.
301  *	RCODE formerr if OPT in wrong section, and so on.
302  */
303 int parse_extract_edns_from_response_msg(struct msg_parse* msg,
304 	struct edns_data* edns, struct regional* region);
305 
306 /**
307  * Skip RRs from packet
308  * @param pkt: the packet. position at start must be right after the query
309  *	section. At end, right after EDNS data or no movement if failed.
310  * @param num: Limit of the number of records we want to parse.
311  * @return: 0 on success, 1 on failure.
312  */
313 int skip_pkt_rrs(struct sldns_buffer* pkt, int num);
314 
315 /**
316  * If EDNS data follows a query section, extract it and initialize edns struct.
317  * @param pkt: the packet. position at start must be right after the query
318  *	section. At end, right after EDNS data or no movement if failed.
319  * @param edns: the edns data allocated by the caller. Does not have to be
320  *	initialised.
321  * @param cfg: the configuration (with nsid value etc.)
322  * @param c: commpoint to determine transport (if needed)
323  * @param repinfo: commreply to determine the client address
324  * @param now: current time
325  * @param region: region to alloc results in (edns option contents)
326  * @param cookie_secrets: the cookie secrets for EDNS COOKIE validation.
327  * @return: 0 on success, or an RCODE on error.
328  *	RCODE formerr if OPT is badly formatted and so on.
329  */
330 int parse_edns_from_query_pkt(struct sldns_buffer* pkt, struct edns_data* edns,
331 	struct config_file* cfg, struct comm_point* c,
332 	struct comm_reply* repinfo, time_t now, struct regional* region,
333 	struct cookie_secrets* cookie_secrets);
334 
335 /**
336  * Calculate hash value for rrset in packet.
337  * @param pkt: the packet.
338  * @param dname: pointer to uncompressed dname, or compressed dname in packet.
339  * @param type: rrset type in host order.
340  * @param dclass: rrset class in network order.
341  * @param rrset_flags: rrset flags (same as packed_rrset flags).
342  * @return hash value
343  */
344 hashvalue_type pkt_hash_rrset(struct sldns_buffer* pkt, uint8_t* dname,
345 	uint16_t type, uint16_t dclass, uint32_t rrset_flags);
346 
347 /**
348  * Lookup in msg hashtable to find a rrset.
349  * @param msg: with the hashtable.
350  * @param pkt: packet for compressed names.
351  * @param h: hash value
352  * @param rrset_flags: flags of rrset sought for.
353  * @param dname: name of rrset sought for.
354  * @param dnamelen: len of dname.
355  * @param type: rrset type, host order.
356  * @param dclass: rrset class, network order.
357  * @return NULL or the rrset_parse if found.
358  */
359 struct rrset_parse* msgparse_hashtable_lookup(struct msg_parse* msg,
360 	struct sldns_buffer* pkt, hashvalue_type h, uint32_t rrset_flags,
361 	uint8_t* dname, size_t dnamelen, uint16_t type, uint16_t dclass);
362 
363 /**
364  * Remove rrset from hash table.
365  * @param msg: with hashtable.
366  * @param rrset: with hash value and id info.
367  */
368 void msgparse_bucket_remove(struct msg_parse* msg, struct rrset_parse* rrset);
369 
370 /**
371  * Log the edns options in the edns option list.
372  * @param level: the verbosity level.
373  * @param info_str: the informational string to be printed before the options.
374  * @param list: the edns option list.
375  */
376 void log_edns_opt_list(enum verbosity_value level, const char* info_str,
377 	struct edns_option* list);
378 
379 /**
380  * Remove RR from msgparse RRset.
381  * @param str: this string is used for logging if verbose. If NULL, there is
382  *	no logging of the remove.
383  * @param pkt: packet in buffer that is removed from. Used to log the name
384  * 	of the item removed.
385  * @param rrset: RRset that the RR is removed from.
386  * @param prev: previous RR in list, or NULL.
387  * @param rr: RR that is removed.
388  * @param addr: address used for logging, if verbose, or NULL then it is not
389  *	used.
390  * @param addrlen: length of addr, if that is not NULL.
391  * @return true if rrset is entirely bad, it would then need to be removed.
392  */
393 int msgparse_rrset_remove_rr(const char* str, struct sldns_buffer* pkt,
394 	struct rrset_parse* rrset, struct rr_parse* prev, struct rr_parse* rr,
395 	struct sockaddr_storage* addr, socklen_t addrlen);
396 
397 #endif /* UTIL_DATA_MSGPARSE_H */
398