xref: /freebsd/contrib/ldns/dnssec.c (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
1 /*
2  * dnssec.c
3  *
4  * contains the cryptographic function needed for DNSSEC in ldns
5  * The crypto library used is openssl
6  *
7  * (c) NLnet Labs, 2004-2008
8  *
9  * See the file LICENSE for the license
10  */
11 
12 #include <ldns/config.h>
13 
14 #include <ldns/ldns.h>
15 #include <ldns/dnssec.h>
16 
17 #include <strings.h>
18 #include <time.h>
19 
20 #ifdef HAVE_SSL
21 #include <openssl/ssl.h>
22 #include <openssl/evp.h>
23 #include <openssl/rand.h>
24 #include <openssl/err.h>
25 #include <openssl/md5.h>
26 #endif
27 
28 ldns_rr *
29 ldns_dnssec_get_rrsig_for_name_and_type(const ldns_rdf *name,
30                                         const ldns_rr_type type,
31                                         const ldns_rr_list *rrs)
32 {
33 	size_t i;
34 	ldns_rr *candidate;
35 
36 	if (!name || !rrs) {
37 		return NULL;
38 	}
39 
40 	for (i = 0; i < ldns_rr_list_rr_count(rrs); i++) {
41 		candidate = ldns_rr_list_rr(rrs, i);
42 		if (ldns_rr_get_type(candidate) == LDNS_RR_TYPE_RRSIG) {
43 			if (ldns_dname_compare(ldns_rr_owner(candidate),
44 			                       name) == 0 &&
45 			    ldns_rdf2rr_type(ldns_rr_rrsig_typecovered(candidate))
46 			    == type
47 			    ) {
48 				return candidate;
49 			}
50 		}
51 	}
52 
53 	return NULL;
54 }
55 
56 ldns_rr *
57 ldns_dnssec_get_dnskey_for_rrsig(const ldns_rr *rrsig,
58 						   const ldns_rr_list *rrs)
59 {
60 	size_t i;
61 	ldns_rr *candidate;
62 
63 	if (!rrsig || !rrs) {
64 		return NULL;
65 	}
66 
67 	for (i = 0; i < ldns_rr_list_rr_count(rrs); i++) {
68 		candidate = ldns_rr_list_rr(rrs, i);
69 		if (ldns_rr_get_type(candidate) == LDNS_RR_TYPE_DNSKEY) {
70 			if (ldns_dname_compare(ldns_rr_owner(candidate),
71 			                       ldns_rr_rrsig_signame(rrsig)) == 0 &&
72 			    ldns_rdf2native_int16(ldns_rr_rrsig_keytag(rrsig)) ==
73 			    ldns_calc_keytag(candidate)
74 			    ) {
75 				return candidate;
76 			}
77 		}
78 	}
79 
80 	return NULL;
81 }
82 
83 ldns_rdf *
84 ldns_nsec_get_bitmap(const ldns_rr *nsec) {
85 	if (ldns_rr_get_type(nsec) == LDNS_RR_TYPE_NSEC) {
86 		return ldns_rr_rdf(nsec, 1);
87 	} else if (ldns_rr_get_type(nsec) == LDNS_RR_TYPE_NSEC3) {
88 		return ldns_rr_rdf(nsec, 5);
89 	} else {
90 		return NULL;
91 	}
92 }
93 
94 /*return the owner name of the closest encloser for name from the list of rrs */
95 /* this is NOT the hash, but the original name! */
96 ldns_rdf *
97 ldns_dnssec_nsec3_closest_encloser(const ldns_rdf *qname,
98                                    ATTR_UNUSED(ldns_rr_type qtype),
99                                    const ldns_rr_list *nsec3s)
100 {
101 	/* remember parameters, they must match */
102 	uint8_t algorithm;
103 	uint32_t iterations;
104 	uint8_t salt_length;
105 	uint8_t *salt;
106 
107 	ldns_rdf *sname, *hashed_sname, *tmp;
108 	bool flag;
109 
110 	bool exact_match_found;
111 	bool in_range_found;
112 
113 	ldns_status status;
114 	ldns_rdf *zone_name;
115 
116 	size_t nsec_i;
117 	ldns_rr *nsec;
118 	ldns_rdf *result = NULL;
119 
120 	if (!qname || !nsec3s || ldns_rr_list_rr_count(nsec3s) < 1) {
121 		return NULL;
122 	}
123 
124 	nsec = ldns_rr_list_rr(nsec3s, 0);
125 	algorithm = ldns_nsec3_algorithm(nsec);
126 	salt_length = ldns_nsec3_salt_length(nsec);
127 	salt = ldns_nsec3_salt_data(nsec);
128 	iterations = ldns_nsec3_iterations(nsec);
129 
130 	sname = ldns_rdf_clone(qname);
131 
132 	flag = false;
133 
134 	zone_name = ldns_dname_left_chop(ldns_rr_owner(nsec));
135 
136 	/* algorithm from nsec3-07 8.3 */
137 	while (ldns_dname_label_count(sname) > 0) {
138 		exact_match_found = false;
139 		in_range_found = false;
140 
141 		hashed_sname = ldns_nsec3_hash_name(sname,
142 									 algorithm,
143 									 iterations,
144 									 salt_length,
145 									 salt);
146 
147 		status = ldns_dname_cat(hashed_sname, zone_name);
148                 if(status != LDNS_STATUS_OK) {
149 	                LDNS_FREE(salt);
150 	                ldns_rdf_deep_free(zone_name);
151 	                ldns_rdf_deep_free(sname);
152                         return NULL;
153                 }
154 
155 		for (nsec_i = 0; nsec_i < ldns_rr_list_rr_count(nsec3s); nsec_i++) {
156 			nsec = ldns_rr_list_rr(nsec3s, nsec_i);
157 
158 			/* check values of iterations etc! */
159 
160 			/* exact match? */
161 			if (ldns_dname_compare(ldns_rr_owner(nsec), hashed_sname) == 0) {
162 			 	exact_match_found = true;
163 			} else if (ldns_nsec_covers_name(nsec, hashed_sname)) {
164 				in_range_found = true;
165 			}
166 
167 		}
168 		if (!exact_match_found && in_range_found) {
169 			flag = true;
170 		} else if (exact_match_found && flag) {
171 			result = ldns_rdf_clone(sname);
172 			/* RFC 5155: 8.3. 2.** "The proof is complete" */
173 			ldns_rdf_deep_free(hashed_sname);
174 			goto done;
175 		} else if (exact_match_found && !flag) {
176 			/* error! */
177 			ldns_rdf_deep_free(hashed_sname);
178 			goto done;
179 		} else {
180 			flag = false;
181 		}
182 
183 		ldns_rdf_deep_free(hashed_sname);
184 		tmp = sname;
185 		sname = ldns_dname_left_chop(sname);
186 		ldns_rdf_deep_free(tmp);
187 	}
188 
189 	done:
190 	LDNS_FREE(salt);
191 	ldns_rdf_deep_free(zone_name);
192 	ldns_rdf_deep_free(sname);
193 
194 	return result;
195 }
196 
197 bool
198 ldns_dnssec_pkt_has_rrsigs(const ldns_pkt *pkt)
199 {
200 	size_t i;
201 	for (i = 0; i < ldns_pkt_ancount(pkt); i++) {
202 		if (ldns_rr_get_type(ldns_rr_list_rr(ldns_pkt_answer(pkt), i)) ==
203 		    LDNS_RR_TYPE_RRSIG) {
204 			return true;
205 		}
206 	}
207 	for (i = 0; i < ldns_pkt_nscount(pkt); i++) {
208 		if (ldns_rr_get_type(ldns_rr_list_rr(ldns_pkt_authority(pkt), i)) ==
209 		    LDNS_RR_TYPE_RRSIG) {
210 			return true;
211 		}
212 	}
213 	return false;
214 }
215 
216 ldns_rr_list *
217 ldns_dnssec_pkt_get_rrsigs_for_name_and_type(const ldns_pkt *pkt,
218 									const ldns_rdf *name,
219 									ldns_rr_type type)
220 {
221 	uint16_t t_netorder;
222 	ldns_rr_list *sigs;
223 	ldns_rr_list *sigs_covered;
224 	ldns_rdf *rdf_t;
225 
226 	sigs = ldns_pkt_rr_list_by_name_and_type(pkt,
227 									 name,
228 									 LDNS_RR_TYPE_RRSIG,
229 									 LDNS_SECTION_ANY_NOQUESTION
230 									 );
231 
232 	t_netorder = htons(type); /* rdf are in network order! */
233 	rdf_t = ldns_rdf_new(LDNS_RDF_TYPE_TYPE, LDNS_RDF_SIZE_WORD, &t_netorder);
234 	sigs_covered = ldns_rr_list_subtype_by_rdf(sigs, rdf_t, 0);
235 
236 	ldns_rdf_free(rdf_t);
237 	ldns_rr_list_deep_free(sigs);
238 
239 	return sigs_covered;
240 
241 }
242 
243 ldns_rr_list *
244 ldns_dnssec_pkt_get_rrsigs_for_type(const ldns_pkt *pkt, ldns_rr_type type)
245 {
246 	uint16_t t_netorder;
247 	ldns_rr_list *sigs;
248 	ldns_rr_list *sigs_covered;
249 	ldns_rdf *rdf_t;
250 
251 	sigs = ldns_pkt_rr_list_by_type(pkt,
252 	                                LDNS_RR_TYPE_RRSIG,
253 	                                LDNS_SECTION_ANY_NOQUESTION
254 							  );
255 
256 	t_netorder = htons(type); /* rdf are in network order! */
257 	rdf_t = ldns_rdf_new(LDNS_RDF_TYPE_TYPE,
258 					 2,
259 					 &t_netorder);
260 	sigs_covered = ldns_rr_list_subtype_by_rdf(sigs, rdf_t, 0);
261 
262 	ldns_rdf_free(rdf_t);
263 	ldns_rr_list_deep_free(sigs);
264 
265 	return sigs_covered;
266 
267 }
268 
269 /* used only on the public key RR */
270 uint16_t
271 ldns_calc_keytag(const ldns_rr *key)
272 {
273 	uint16_t ac16;
274 	ldns_buffer *keybuf;
275 	size_t keysize;
276 
277 	if (!key) {
278 		return 0;
279 	}
280 
281 	if (ldns_rr_get_type(key) != LDNS_RR_TYPE_DNSKEY &&
282 	    ldns_rr_get_type(key) != LDNS_RR_TYPE_KEY
283 	    ) {
284 		return 0;
285 	}
286 
287 	/* rdata to buf - only put the rdata in a buffer */
288 	keybuf = ldns_buffer_new(LDNS_MIN_BUFLEN); /* grows */
289 	if (!keybuf) {
290 		return 0;
291 	}
292 	(void)ldns_rr_rdata2buffer_wire(keybuf, key);
293 	/* the current pos in the buffer is the keysize */
294 	keysize= ldns_buffer_position(keybuf);
295 
296 	ac16 = ldns_calc_keytag_raw(ldns_buffer_begin(keybuf), keysize);
297 	ldns_buffer_free(keybuf);
298 	return ac16;
299 }
300 
301 uint16_t ldns_calc_keytag_raw(const uint8_t* key, size_t keysize)
302 {
303 	unsigned int i;
304 	uint32_t ac32;
305 	uint16_t ac16;
306 
307 	if(keysize < 4) {
308 		return 0;
309 	}
310 	/* look at the algorithm field, copied from 2535bis */
311 	if (key[3] == LDNS_RSAMD5) {
312 		ac16 = 0;
313 		if (keysize > 4) {
314 			memmove(&ac16, key + keysize - 3, 2);
315 		}
316 		ac16 = ntohs(ac16);
317 		return (uint16_t) ac16;
318 	} else {
319 		ac32 = 0;
320 		for (i = 0; (size_t)i < keysize; ++i) {
321 			ac32 += (i & 1) ? key[i] : key[i] << 8;
322 		}
323 		ac32 += (ac32 >> 16) & 0xFFFF;
324 		return (uint16_t) (ac32 & 0xFFFF);
325 	}
326 }
327 
328 #ifdef HAVE_SSL
329 DSA *
330 ldns_key_buf2dsa(const ldns_buffer *key)
331 {
332 	return ldns_key_buf2dsa_raw((const unsigned char*)ldns_buffer_begin(key),
333 						   ldns_buffer_position(key));
334 }
335 
336 DSA *
337 ldns_key_buf2dsa_raw(const unsigned char* key, size_t len)
338 {
339 	uint8_t T;
340 	uint16_t length;
341 	uint16_t offset;
342 	DSA *dsa;
343 	BIGNUM *Q; BIGNUM *P;
344 	BIGNUM *G; BIGNUM *Y;
345 
346 	if(len == 0)
347 		return NULL;
348 	T = (uint8_t)key[0];
349 	length = (64 + T * 8);
350 	offset = 1;
351 
352 	if (T > 8) {
353 		return NULL;
354 	}
355 	if(len < (size_t)1 + SHA_DIGEST_LENGTH + 3*length)
356 		return NULL;
357 
358 	Q = BN_bin2bn(key+offset, SHA_DIGEST_LENGTH, NULL);
359 	offset += SHA_DIGEST_LENGTH;
360 
361 	P = BN_bin2bn(key+offset, (int)length, NULL);
362 	offset += length;
363 
364 	G = BN_bin2bn(key+offset, (int)length, NULL);
365 	offset += length;
366 
367 	Y = BN_bin2bn(key+offset, (int)length, NULL);
368 	offset += length;
369 
370 	/* create the key and set its properties */
371 	if(!Q || !P || !G || !Y || !(dsa = DSA_new())) {
372 		BN_free(Q);
373 		BN_free(P);
374 		BN_free(G);
375 		BN_free(Y);
376 		return NULL;
377 	}
378 #if OPENSSL_VERSION_NUMBER < 0x10100000 || defined(HAVE_LIBRESSL)
379 #ifndef S_SPLINT_S
380 	dsa->p = P;
381 	dsa->q = Q;
382 	dsa->g = G;
383 	dsa->pub_key = Y;
384 #endif /* splint */
385 #else /* OPENSSL_VERSION_NUMBER */
386 	if (!DSA_set0_pqg(dsa, P, Q, G)) {
387 		/* QPG not yet attached, need to free */
388 		BN_free(Q);
389 		BN_free(P);
390 		BN_free(G);
391 
392 		DSA_free(dsa);
393 		BN_free(Y);
394 		return NULL;
395 	}
396 	if (!DSA_set0_key(dsa, Y, NULL)) {
397 		/* QPG attached, cleaned up by DSA_fre() */
398 		DSA_free(dsa);
399 		BN_free(Y);
400 		return NULL;
401 	}
402 #endif /* OPENSSL_VERSION_NUMBER */
403 	return dsa;
404 }
405 
406 RSA *
407 ldns_key_buf2rsa(const ldns_buffer *key)
408 {
409 	return ldns_key_buf2rsa_raw((const unsigned char*)ldns_buffer_begin(key),
410 						   ldns_buffer_position(key));
411 }
412 
413 RSA *
414 ldns_key_buf2rsa_raw(const unsigned char* key, size_t len)
415 {
416 	uint16_t offset;
417 	uint16_t exp;
418 	uint16_t int16;
419 	RSA *rsa;
420 	BIGNUM *modulus;
421 	BIGNUM *exponent;
422 
423 	if (len == 0)
424 		return NULL;
425 	if (key[0] == 0) {
426 		if(len < 3)
427 			return NULL;
428 		/* need some smart comment here XXX*/
429 		/* the exponent is too large so it's places
430 		 * futher...???? */
431 		memmove(&int16, key+1, 2);
432 		exp = ntohs(int16);
433 		offset = 3;
434 	} else {
435 		exp = key[0];
436 		offset = 1;
437 	}
438 
439 	/* key length at least one */
440 	if(len < (size_t)offset + exp + 1)
441 		return NULL;
442 
443 	/* Exponent */
444 	exponent = BN_new();
445 	if(!exponent) return NULL;
446 	(void) BN_bin2bn(key+offset, (int)exp, exponent);
447 	offset += exp;
448 
449 	/* Modulus */
450 	modulus = BN_new();
451 	if(!modulus) {
452 		BN_free(exponent);
453 		return NULL;
454 	}
455 	/* length of the buffer must match the key length! */
456 	(void) BN_bin2bn(key+offset, (int)(len - offset), modulus);
457 
458 	rsa = RSA_new();
459 	if(!rsa) {
460 		BN_free(exponent);
461 		BN_free(modulus);
462 		return NULL;
463 	}
464 #if OPENSSL_VERSION_NUMBER < 0x10100000 || defined(HAVE_LIBRESSL)
465 #ifndef S_SPLINT_S
466 	rsa->n = modulus;
467 	rsa->e = exponent;
468 #endif /* splint */
469 #else /* OPENSSL_VERSION_NUMBER */
470 	if (!RSA_set0_key(rsa, modulus, exponent, NULL)) {
471 		BN_free(exponent);
472 		BN_free(modulus);
473 		RSA_free(rsa);
474 		return NULL;
475 	}
476 #endif /* OPENSSL_VERSION_NUMBER */
477 
478 	return rsa;
479 }
480 
481 int
482 ldns_digest_evp(const unsigned char* data, unsigned int len, unsigned char* dest,
483 	const EVP_MD* md)
484 {
485 	EVP_MD_CTX* ctx;
486 	ctx = EVP_MD_CTX_create();
487 	if(!ctx)
488 		return false;
489 	if(!EVP_DigestInit_ex(ctx, md, NULL) ||
490 		!EVP_DigestUpdate(ctx, data, len) ||
491 		!EVP_DigestFinal_ex(ctx, dest, NULL)) {
492 		EVP_MD_CTX_destroy(ctx);
493 		return false;
494 	}
495 	EVP_MD_CTX_destroy(ctx);
496 	return true;
497 }
498 #endif /* HAVE_SSL */
499 
500 ldns_rr *
501 ldns_key_rr2ds(const ldns_rr *key, ldns_hash h)
502 {
503 	ldns_rdf *tmp;
504 	ldns_rr *ds;
505 	uint16_t keytag;
506 	uint8_t  sha1hash;
507 	uint8_t *digest;
508 	ldns_buffer *data_buf;
509 #ifdef USE_GOST
510 	const EVP_MD* md = NULL;
511 #endif
512 
513 	if (ldns_rr_get_type(key) != LDNS_RR_TYPE_DNSKEY) {
514 		return NULL;
515 	}
516 
517 	ds = ldns_rr_new();
518 	if (!ds) {
519 		return NULL;
520 	}
521 	ldns_rr_set_type(ds, LDNS_RR_TYPE_DS);
522 	ldns_rr_set_owner(ds, ldns_rdf_clone(
523 								  ldns_rr_owner(key)));
524 	ldns_rr_set_ttl(ds, ldns_rr_ttl(key));
525 	ldns_rr_set_class(ds, ldns_rr_get_class(key));
526 
527 	switch(h) {
528 	default:
529 	case LDNS_SHA1:
530 		digest = LDNS_XMALLOC(uint8_t, LDNS_SHA1_DIGEST_LENGTH);
531 		if (!digest) {
532 			ldns_rr_free(ds);
533 			return NULL;
534 		}
535 		break;
536 	case LDNS_SHA256:
537 		digest = LDNS_XMALLOC(uint8_t, LDNS_SHA256_DIGEST_LENGTH);
538 		if (!digest) {
539 			ldns_rr_free(ds);
540 			return NULL;
541 		}
542 		break;
543 	case LDNS_HASH_GOST:
544 #ifdef USE_GOST
545 		(void)ldns_key_EVP_load_gost_id();
546 		md = EVP_get_digestbyname("md_gost94");
547 		if(!md) {
548 			ldns_rr_free(ds);
549 			return NULL;
550 		}
551 		digest = LDNS_XMALLOC(uint8_t, EVP_MD_size(md));
552 		if (!digest) {
553 			ldns_rr_free(ds);
554 			return NULL;
555 		}
556                 break;
557 #else
558 		/* not implemented */
559 		ldns_rr_free(ds);
560 		return NULL;
561 #endif
562 	case LDNS_SHA384:
563 #ifdef USE_ECDSA
564 		digest = LDNS_XMALLOC(uint8_t, SHA384_DIGEST_LENGTH);
565 		if (!digest) {
566 			ldns_rr_free(ds);
567 			return NULL;
568 		}
569                 break;
570 #else
571 		/* not implemented */
572 		ldns_rr_free(ds);
573 		return NULL;
574 #endif
575 	}
576 
577 	data_buf = ldns_buffer_new(LDNS_MAX_PACKETLEN);
578 	if (!data_buf) {
579 		LDNS_FREE(digest);
580 		ldns_rr_free(ds);
581 		return NULL;
582 	}
583 
584 	/* keytag */
585 	keytag = htons(ldns_calc_keytag((ldns_rr*)key));
586 	tmp = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_INT16,
587 						   sizeof(uint16_t),
588 						   &keytag);
589 	ldns_rr_push_rdf(ds, tmp);
590 
591 	/* copy the algorithm field */
592 	if ((tmp = ldns_rr_rdf(key, 2)) == NULL) {
593 		LDNS_FREE(digest);
594 		ldns_buffer_free(data_buf);
595 		ldns_rr_free(ds);
596 		return NULL;
597 	} else {
598 		ldns_rr_push_rdf(ds, ldns_rdf_clone( tmp ));
599 	}
600 
601 	/* digest hash type */
602 	sha1hash = (uint8_t)h;
603 	tmp = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_INT8,
604 						   sizeof(uint8_t),
605 						   &sha1hash);
606 	ldns_rr_push_rdf(ds, tmp);
607 
608 	/* digest */
609 	/* owner name */
610 	tmp = ldns_rdf_clone(ldns_rr_owner(key));
611 	ldns_dname2canonical(tmp);
612 	if (ldns_rdf2buffer_wire(data_buf, tmp) != LDNS_STATUS_OK) {
613 		LDNS_FREE(digest);
614 		ldns_buffer_free(data_buf);
615 		ldns_rr_free(ds);
616 		ldns_rdf_deep_free(tmp);
617 		return NULL;
618 	}
619 	ldns_rdf_deep_free(tmp);
620 
621 	/* all the rdata's */
622 	if (ldns_rr_rdata2buffer_wire(data_buf,
623 							(ldns_rr*)key) != LDNS_STATUS_OK) {
624 		LDNS_FREE(digest);
625 		ldns_buffer_free(data_buf);
626 		ldns_rr_free(ds);
627 		return NULL;
628 	}
629 	switch(h) {
630 	case LDNS_SHA1:
631 		(void) ldns_sha1((unsigned char *) ldns_buffer_begin(data_buf),
632 		                 (unsigned int) ldns_buffer_position(data_buf),
633 		                 (unsigned char *) digest);
634 
635 		tmp = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_HEX,
636 		                            LDNS_SHA1_DIGEST_LENGTH,
637 		                            digest);
638 		ldns_rr_push_rdf(ds, tmp);
639 
640 		break;
641 	case LDNS_SHA256:
642 		(void) ldns_sha256((unsigned char *) ldns_buffer_begin(data_buf),
643 		                   (unsigned int) ldns_buffer_position(data_buf),
644 		                   (unsigned char *) digest);
645 		tmp = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_HEX,
646 		                            LDNS_SHA256_DIGEST_LENGTH,
647 		                            digest);
648 		ldns_rr_push_rdf(ds, tmp);
649 		break;
650 	case LDNS_HASH_GOST:
651 #ifdef USE_GOST
652 		if(!ldns_digest_evp((unsigned char *) ldns_buffer_begin(data_buf),
653 				(unsigned int) ldns_buffer_position(data_buf),
654 				(unsigned char *) digest, md)) {
655 			LDNS_FREE(digest);
656 			ldns_buffer_free(data_buf);
657 			ldns_rr_free(ds);
658 			return NULL;
659 		}
660 		tmp = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_HEX,
661 		                            (size_t)EVP_MD_size(md),
662 		                            digest);
663 		ldns_rr_push_rdf(ds, tmp);
664 #endif
665 		break;
666 	case LDNS_SHA384:
667 #ifdef USE_ECDSA
668 		(void) SHA384((unsigned char *) ldns_buffer_begin(data_buf),
669 		                 (unsigned int) ldns_buffer_position(data_buf),
670 		                 (unsigned char *) digest);
671 		tmp = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_HEX,
672 		                            SHA384_DIGEST_LENGTH,
673 		                            digest);
674 		ldns_rr_push_rdf(ds, tmp);
675 #endif
676 		break;
677 	}
678 
679 	LDNS_FREE(digest);
680 	ldns_buffer_free(data_buf);
681 	return ds;
682 }
683 
684 /* From RFC3845:
685  *
686  * 2.1.2.  The List of Type Bit Map(s) Field
687  *
688  *    The RR type space is split into 256 window blocks, each representing
689  *    the low-order 8 bits of the 16-bit RR type space.  Each block that
690  *    has at least one active RR type is encoded using a single octet
691  *    window number (from 0 to 255), a single octet bitmap length (from 1
692  *    to 32) indicating the number of octets used for the window block's
693  *    bitmap, and up to 32 octets (256 bits) of bitmap.
694  *
695  *    Window blocks are present in the NSEC RR RDATA in increasing
696  *    numerical order.
697  *
698  *    "|" denotes concatenation
699  *
700  *    Type Bit Map(s) Field = ( Window Block # | Bitmap Length | Bitmap ) +
701  *
702  *    <cut>
703  *
704  *    Blocks with no types present MUST NOT be included.  Trailing zero
705  *    octets in the bitmap MUST be omitted.  The length of each block's
706  *    bitmap is determined by the type code with the largest numerical
707  *    value within that block, among the set of RR types present at the
708  *    NSEC RR's owner name.  Trailing zero octets not specified MUST be
709  *    interpreted as zero octets.
710  */
711 ldns_rdf *
712 ldns_dnssec_create_nsec_bitmap(ldns_rr_type rr_type_list[],
713                                size_t size,
714                                ldns_rr_type nsec_type)
715 {
716 	uint8_t  window;		/*  most significant octet of type */
717 	uint8_t  subtype;		/* least significant octet of type */
718 	int      windows[256];		/* Max subtype per window */
719 	uint8_t  windowpresent[256];	/* bool if window appears in bitmap */
720 	ldns_rr_type* d;	/* used to traverse rr_type_list*/
721 	size_t i;		/* used to traverse windows array */
722 
723 	size_t sz;			/* size needed for type bitmap rdf */
724 	uint8_t* data = NULL;		/* rdf data */
725 	uint8_t* dptr;			/* used to itraverse rdf data */
726 	ldns_rdf* rdf;			/* bitmap rdf to return */
727 
728 	if (nsec_type != LDNS_RR_TYPE_NSEC &&
729 	    nsec_type != LDNS_RR_TYPE_NSEC3) {
730 		return NULL;
731 	}
732 	memset(windows, 0, sizeof(int)*256);
733 	memset(windowpresent, 0, 256);
734 
735 	/* Which other windows need to be in the bitmap rdf?
736 	 */
737 	for (d = rr_type_list; d < rr_type_list + size; d++) {
738 		window  = *d >> 8;
739 		subtype = *d & 0xff;
740 		windowpresent[window] = 1;
741 		if (windows[window] < (int)subtype) {
742 			windows[window] = (int)subtype;
743 		}
744 	}
745 
746 	/* How much space do we need in the rdf for those windows?
747 	 */
748 	sz = 0;
749 	for (i = 0; i < 256; i++) {
750 		if (windowpresent[i]) {
751 			sz += windows[i] / 8 + 3;
752 		}
753 	}
754 	if (sz > 0) {
755 		/* Format rdf data according RFC3845 Section 2.1.2 (see above)
756 		 */
757 		dptr = data = LDNS_CALLOC(uint8_t, sz);
758 		if (!data) {
759 			return NULL;
760 		}
761 		for (i = 0; i < 256; i++) {
762 			if (windowpresent[i]) {
763 				*dptr++ = (uint8_t)i;
764 				*dptr++ = (uint8_t)(windows[i] / 8 + 1);
765 
766 				/* Now let windows[i] index the bitmap
767 				 * within data
768 				 */
769 				windows[i] = (int)(dptr - data);
770 
771 				dptr += dptr[-1];
772 			}
773 		}
774 	}
775 
776 	/* Set the bits?
777 	 */
778 	for (d = rr_type_list; d < rr_type_list + size; d++) {
779 		subtype = *d & 0xff;
780 		data[windows[*d >> 8] + subtype/8] |= (0x80 >> (subtype % 8));
781 	}
782 
783 	/* Allocate and return rdf structure for the data
784 	 */
785 	rdf = ldns_rdf_new(LDNS_RDF_TYPE_BITMAP, sz, data);
786 	if (!rdf) {
787 		LDNS_FREE(data);
788 		return NULL;
789 	}
790 	return rdf;
791 }
792 
793 int
794 ldns_dnssec_rrsets_contains_type(const ldns_dnssec_rrsets *rrsets,
795                                  ldns_rr_type type)
796 {
797 	const ldns_dnssec_rrsets *cur_rrset = rrsets;
798 	while (cur_rrset) {
799 		if (cur_rrset->type == type) {
800 			return 1;
801 		}
802 		cur_rrset = cur_rrset->next;
803 	}
804 	return 0;
805 }
806 
807 ldns_rr *
808 ldns_dnssec_create_nsec(const ldns_dnssec_name *from,
809                         const ldns_dnssec_name *to,
810                         ldns_rr_type nsec_type)
811 {
812 	ldns_rr *nsec_rr;
813 	ldns_rr_type types[65536];
814 	size_t type_count = 0;
815 	ldns_dnssec_rrsets *cur_rrsets;
816 	int on_delegation_point;
817 
818 	if (!from || !to || (nsec_type != LDNS_RR_TYPE_NSEC)) {
819 		return NULL;
820 	}
821 
822 	nsec_rr = ldns_rr_new();
823 	ldns_rr_set_type(nsec_rr, nsec_type);
824 	ldns_rr_set_owner(nsec_rr, ldns_rdf_clone(ldns_dnssec_name_name(from)));
825 	ldns_rr_push_rdf(nsec_rr, ldns_rdf_clone(ldns_dnssec_name_name(to)));
826 
827 	on_delegation_point = ldns_dnssec_rrsets_contains_type(
828 			from->rrsets, LDNS_RR_TYPE_NS)
829 		&& !ldns_dnssec_rrsets_contains_type(
830 			from->rrsets, LDNS_RR_TYPE_SOA);
831 
832 	cur_rrsets = from->rrsets;
833 	while (cur_rrsets) {
834 		/* Do not include non-authoritative rrsets on the delegation point
835 		 * in the type bitmap */
836 		if ((on_delegation_point && (
837 				cur_rrsets->type == LDNS_RR_TYPE_NS
838 			     || cur_rrsets->type == LDNS_RR_TYPE_DS))
839 			|| (!on_delegation_point &&
840 				cur_rrsets->type != LDNS_RR_TYPE_RRSIG
841 			     && cur_rrsets->type != LDNS_RR_TYPE_NSEC)) {
842 
843 			types[type_count] = cur_rrsets->type;
844 			type_count++;
845 		}
846 		cur_rrsets = cur_rrsets->next;
847 
848 	}
849 	types[type_count] = LDNS_RR_TYPE_RRSIG;
850 	type_count++;
851 	types[type_count] = LDNS_RR_TYPE_NSEC;
852 	type_count++;
853 
854 	ldns_rr_push_rdf(nsec_rr, ldns_dnssec_create_nsec_bitmap(types,
855 	                               type_count,
856 	                               nsec_type));
857 
858 	return nsec_rr;
859 }
860 
861 ldns_rr *
862 ldns_dnssec_create_nsec3(const ldns_dnssec_name *from,
863 					const ldns_dnssec_name *to,
864 					const ldns_rdf *zone_name,
865 					uint8_t algorithm,
866 					uint8_t flags,
867 					uint16_t iterations,
868 					uint8_t salt_length,
869 					const uint8_t *salt)
870 {
871 	ldns_rr *nsec_rr;
872 	ldns_rr_type types[65536];
873 	size_t type_count = 0;
874 	ldns_dnssec_rrsets *cur_rrsets;
875 	ldns_status status;
876 	int on_delegation_point;
877 
878 	if (!from) {
879 		return NULL;
880 	}
881 
882 	nsec_rr = ldns_rr_new_frm_type(LDNS_RR_TYPE_NSEC3);
883 	ldns_rr_set_owner(nsec_rr,
884 	                  ldns_nsec3_hash_name(ldns_dnssec_name_name(from),
885 	                  algorithm,
886 	                  iterations,
887 	                  salt_length,
888 	                  salt));
889 	status = ldns_dname_cat(ldns_rr_owner(nsec_rr), zone_name);
890         if(status != LDNS_STATUS_OK) {
891                 ldns_rr_free(nsec_rr);
892                 return NULL;
893         }
894 	ldns_nsec3_add_param_rdfs(nsec_rr,
895 	                          algorithm,
896 	                          flags,
897 	                          iterations,
898 	                          salt_length,
899 	                          salt);
900 
901 	on_delegation_point = ldns_dnssec_rrsets_contains_type(
902 			from->rrsets, LDNS_RR_TYPE_NS)
903 		&& !ldns_dnssec_rrsets_contains_type(
904 			from->rrsets, LDNS_RR_TYPE_SOA);
905 	cur_rrsets = from->rrsets;
906 	while (cur_rrsets) {
907 		/* Do not include non-authoritative rrsets on the delegation point
908 		 * in the type bitmap. Potentionally not skipping insecure
909 		 * delegation should have been done earlier, in function
910 		 * ldns_dnssec_zone_create_nsec3s, or even earlier in:
911 		 * ldns_dnssec_zone_sign_nsec3_flg .
912 		 */
913 		if ((on_delegation_point && (
914 				cur_rrsets->type == LDNS_RR_TYPE_NS
915 			     || cur_rrsets->type == LDNS_RR_TYPE_DS))
916 			|| (!on_delegation_point &&
917 				cur_rrsets->type != LDNS_RR_TYPE_RRSIG)) {
918 
919 			types[type_count] = cur_rrsets->type;
920 			type_count++;
921 		}
922 		cur_rrsets = cur_rrsets->next;
923 	}
924 	/* always add rrsig type if this is not an unsigned
925 	 * delegation
926 	 */
927 	if (type_count > 0 &&
928 	    !(type_count == 1 && types[0] == LDNS_RR_TYPE_NS)) {
929 		types[type_count] = LDNS_RR_TYPE_RRSIG;
930 		type_count++;
931 	}
932 
933 	/* leave next rdata empty if they weren't precomputed yet */
934 	if (to && to->hashed_name) {
935 		(void) ldns_rr_set_rdf(nsec_rr,
936 		                       ldns_rdf_clone(to->hashed_name),
937 		                       4);
938 	} else {
939 		(void) ldns_rr_set_rdf(nsec_rr, NULL, 4);
940 	}
941 
942 	ldns_rr_push_rdf(nsec_rr,
943 	                 ldns_dnssec_create_nsec_bitmap(types,
944 	                 type_count,
945 	                 LDNS_RR_TYPE_NSEC3));
946 
947 	return nsec_rr;
948 }
949 
950 ldns_rr *
951 ldns_create_nsec(ldns_rdf *cur_owner, ldns_rdf *next_owner, ldns_rr_list *rrs)
952 {
953 	/* we do not do any check here - garbage in, garbage out */
954 
955 	/* the the start and end names - get the type from the
956 	 * before rrlist */
957 
958 	/* inefficient, just give it a name, a next name, and a list of rrs */
959 	/* we make 1 big uberbitmap first, then windows */
960 	/* todo: make something more efficient :) */
961 	uint16_t i;
962 	ldns_rr *i_rr;
963 	uint16_t i_type;
964 
965 	ldns_rr *nsec = NULL;
966 	ldns_rr_type i_type_list[65536];
967 	size_t type_count = 0;
968 
969 	nsec = ldns_rr_new();
970 	ldns_rr_set_type(nsec, LDNS_RR_TYPE_NSEC);
971 	ldns_rr_set_owner(nsec, ldns_rdf_clone(cur_owner));
972 	ldns_rr_push_rdf(nsec, ldns_rdf_clone(next_owner));
973 
974 	for (i = 0; i < ldns_rr_list_rr_count(rrs); i++) {
975 		i_rr = ldns_rr_list_rr(rrs, i);
976 		if (ldns_rdf_compare(cur_owner,
977 						 ldns_rr_owner(i_rr)) == 0) {
978 			i_type = ldns_rr_get_type(i_rr);
979 			if (i_type != LDNS_RR_TYPE_RRSIG && i_type != LDNS_RR_TYPE_NSEC) {
980 				if (type_count == 0 || i_type_list[type_count-1] != i_type) {
981 					i_type_list[type_count] = i_type;
982 					type_count++;
983 				}
984 			}
985 		}
986 	}
987 
988 	i_type_list[type_count] = LDNS_RR_TYPE_RRSIG;
989 	type_count++;
990 	i_type_list[type_count] = LDNS_RR_TYPE_NSEC;
991 	type_count++;
992 
993 	ldns_rr_push_rdf(nsec,
994 				  ldns_dnssec_create_nsec_bitmap(i_type_list,
995 						type_count, LDNS_RR_TYPE_NSEC));
996 
997 	return nsec;
998 }
999 
1000 ldns_rdf *
1001 ldns_nsec3_hash_name(const ldns_rdf *name,
1002 				 uint8_t algorithm,
1003 				 uint16_t iterations,
1004 				 uint8_t salt_length,
1005 				 const uint8_t *salt)
1006 {
1007 	size_t hashed_owner_str_len;
1008 	ldns_rdf *cann;
1009 	ldns_rdf *hashed_owner;
1010 	unsigned char *hashed_owner_str;
1011 	char *hashed_owner_b32;
1012 	size_t hashed_owner_b32_len;
1013 	uint32_t cur_it;
1014 	/* define to contain the largest possible hash, which is
1015 	 * sha1 at the moment */
1016 	unsigned char hash[LDNS_SHA1_DIGEST_LENGTH];
1017 	ldns_status status;
1018 
1019 	/* TODO: mnemonic list for hash algs SHA-1, default to 1 now (sha1) */
1020 	if (algorithm != LDNS_SHA1) {
1021 		return NULL;
1022 	}
1023 
1024 	/* prepare the owner name according to the draft section bla */
1025 	cann = ldns_rdf_clone(name);
1026 	if(!cann) {
1027 #ifdef STDERR_MSGS
1028 		fprintf(stderr, "Memory error\n");
1029 #endif
1030 		return NULL;
1031 	}
1032 	ldns_dname2canonical(cann);
1033 
1034 	hashed_owner_str_len = salt_length + ldns_rdf_size(cann);
1035 	hashed_owner_str = LDNS_XMALLOC(unsigned char, hashed_owner_str_len);
1036         if(!hashed_owner_str) {
1037 	        ldns_rdf_deep_free(cann);
1038                 return NULL;
1039         }
1040 	memcpy(hashed_owner_str, ldns_rdf_data(cann), ldns_rdf_size(cann));
1041 	memcpy(hashed_owner_str + ldns_rdf_size(cann), salt, salt_length);
1042 	ldns_rdf_deep_free(cann);
1043 
1044 	for (cur_it = iterations + 1; cur_it > 0; cur_it--) {
1045 		(void) ldns_sha1((unsigned char *) hashed_owner_str,
1046 		                 (unsigned int) hashed_owner_str_len, hash);
1047 
1048 		LDNS_FREE(hashed_owner_str);
1049 		hashed_owner_str_len = salt_length + LDNS_SHA1_DIGEST_LENGTH;
1050 		hashed_owner_str = LDNS_XMALLOC(unsigned char, hashed_owner_str_len);
1051 		if (!hashed_owner_str) {
1052 			return NULL;
1053 		}
1054 		memcpy(hashed_owner_str, hash, LDNS_SHA1_DIGEST_LENGTH);
1055 		memcpy(hashed_owner_str + LDNS_SHA1_DIGEST_LENGTH, salt, salt_length);
1056 		hashed_owner_str_len = LDNS_SHA1_DIGEST_LENGTH + salt_length;
1057 	}
1058 
1059 	LDNS_FREE(hashed_owner_str);
1060 	hashed_owner_str = hash;
1061 	hashed_owner_str_len = LDNS_SHA1_DIGEST_LENGTH;
1062 
1063 	hashed_owner_b32 = LDNS_XMALLOC(char,
1064                   ldns_b32_ntop_calculate_size(hashed_owner_str_len) + 1);
1065         if(!hashed_owner_b32) {
1066                 return NULL;
1067         }
1068         hashed_owner_b32_len = (size_t) ldns_b32_ntop_extended_hex(
1069                 (uint8_t *) hashed_owner_str,
1070                 hashed_owner_str_len,
1071                 hashed_owner_b32,
1072                 ldns_b32_ntop_calculate_size(hashed_owner_str_len)+1);
1073 	if (hashed_owner_b32_len < 1) {
1074 #ifdef STDERR_MSGS
1075 		fprintf(stderr, "Error in base32 extended hex encoding ");
1076 		fprintf(stderr, "of hashed owner name (name: ");
1077 		ldns_rdf_print(stderr, name);
1078 		fprintf(stderr, ", return code: %u)\n",
1079 		        (unsigned int) hashed_owner_b32_len);
1080 #endif
1081 		LDNS_FREE(hashed_owner_b32);
1082 		return NULL;
1083 	}
1084 	hashed_owner_b32[hashed_owner_b32_len] = '\0';
1085 
1086 	status = ldns_str2rdf_dname(&hashed_owner, hashed_owner_b32);
1087 	if (status != LDNS_STATUS_OK) {
1088 #ifdef STDERR_MSGS
1089 		fprintf(stderr, "Error creating rdf from %s\n", hashed_owner_b32);
1090 #endif
1091 		LDNS_FREE(hashed_owner_b32);
1092 		return NULL;
1093 	}
1094 
1095 	LDNS_FREE(hashed_owner_b32);
1096 	return hashed_owner;
1097 }
1098 
1099 void
1100 ldns_nsec3_add_param_rdfs(ldns_rr *rr,
1101 					 uint8_t algorithm,
1102 					 uint8_t flags,
1103 					 uint16_t iterations,
1104 					 uint8_t salt_length,
1105 					 const uint8_t *salt)
1106 {
1107 	ldns_rdf *salt_rdf = NULL;
1108 	uint8_t *salt_data = NULL;
1109 	ldns_rdf *old;
1110 
1111 	old = ldns_rr_set_rdf(rr,
1112 	                      ldns_rdf_new_frm_data(LDNS_RDF_TYPE_INT8,
1113 	                                            1, (void*)&algorithm),
1114 	                      0);
1115 	if (old) ldns_rdf_deep_free(old);
1116 
1117 	old = ldns_rr_set_rdf(rr,
1118 	                      ldns_rdf_new_frm_data(LDNS_RDF_TYPE_INT8,
1119 	                                            1, (void*)&flags),
1120 	                      1);
1121 	if (old) ldns_rdf_deep_free(old);
1122 
1123 	old = ldns_rr_set_rdf(rr,
1124                           ldns_native2rdf_int16(LDNS_RDF_TYPE_INT16,
1125                                                 iterations),
1126 	                      2);
1127 	if (old) ldns_rdf_deep_free(old);
1128 
1129 	salt_data = LDNS_XMALLOC(uint8_t, salt_length + 1);
1130         if(!salt_data) {
1131                 /* no way to return error */
1132                 return;
1133         }
1134 	salt_data[0] = salt_length;
1135 	memcpy(salt_data + 1, salt, salt_length);
1136 	salt_rdf = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_NSEC3_SALT,
1137 							   salt_length + 1,
1138 							   salt_data);
1139         if(!salt_rdf) {
1140                 LDNS_FREE(salt_data);
1141                 /* no way to return error */
1142                 return;
1143         }
1144 
1145 	old = ldns_rr_set_rdf(rr, salt_rdf, 3);
1146 	if (old) ldns_rdf_deep_free(old);
1147 	LDNS_FREE(salt_data);
1148 }
1149 
1150 static int
1151 rr_list_delegation_only(const ldns_rdf *origin, const ldns_rr_list *rr_list)
1152 {
1153 	size_t i;
1154 	ldns_rr *cur_rr;
1155 	if (!origin || !rr_list) return 0;
1156 	for (i = 0; i < ldns_rr_list_rr_count(rr_list); i++) {
1157 		cur_rr = ldns_rr_list_rr(rr_list, i);
1158 		if (ldns_dname_compare(ldns_rr_owner(cur_rr), origin) == 0) {
1159 			return 0;
1160 		}
1161 		if (ldns_rr_get_type(cur_rr) != LDNS_RR_TYPE_NS) {
1162 			return 0;
1163 		}
1164 	}
1165 	return 1;
1166 }
1167 
1168 /* this will NOT return the NSEC3  completed, you will have to run the
1169    finalize function on the rrlist later! */
1170 ldns_rr *
1171 ldns_create_nsec3(const ldns_rdf *cur_owner,
1172                   const ldns_rdf *cur_zone,
1173                   const ldns_rr_list *rrs,
1174                   uint8_t algorithm,
1175                   uint8_t flags,
1176                   uint16_t iterations,
1177                   uint8_t salt_length,
1178                   const uint8_t *salt,
1179                   bool emptynonterminal)
1180 {
1181 	size_t i;
1182 	ldns_rr *i_rr;
1183 	uint16_t i_type;
1184 
1185 	ldns_rr *nsec = NULL;
1186 	ldns_rdf *hashed_owner = NULL;
1187 
1188 	ldns_status status;
1189 
1190     ldns_rr_type i_type_list[1024];
1191 	size_t type_count = 0;
1192 
1193 	hashed_owner = ldns_nsec3_hash_name(cur_owner,
1194 								 algorithm,
1195 								 iterations,
1196 								 salt_length,
1197 								 salt);
1198 	status = ldns_dname_cat(hashed_owner, cur_zone);
1199         if(status != LDNS_STATUS_OK) {
1200 		ldns_rdf_deep_free(hashed_owner);
1201                 return NULL;
1202 	}
1203 	nsec = ldns_rr_new_frm_type(LDNS_RR_TYPE_NSEC3);
1204         if(!nsec) {
1205 		ldns_rdf_deep_free(hashed_owner);
1206                 return NULL;
1207 	}
1208 	ldns_rr_set_type(nsec, LDNS_RR_TYPE_NSEC3);
1209 	ldns_rr_set_owner(nsec, hashed_owner);
1210 
1211 	ldns_nsec3_add_param_rdfs(nsec,
1212 						 algorithm,
1213 						 flags,
1214 						 iterations,
1215 						 salt_length,
1216 						 salt);
1217 	(void) ldns_rr_set_rdf(nsec, NULL, 4);
1218 
1219 
1220 	for (i = 0; i < ldns_rr_list_rr_count(rrs); i++) {
1221 		i_rr = ldns_rr_list_rr(rrs, i);
1222 		if (ldns_rdf_compare(cur_owner,
1223 						 ldns_rr_owner(i_rr)) == 0) {
1224 			i_type = ldns_rr_get_type(i_rr);
1225 			if (type_count == 0 || i_type_list[type_count-1] != i_type) {
1226 				i_type_list[type_count] = i_type;
1227 				type_count++;
1228 			}
1229 		}
1230 	}
1231 
1232 	/* add RRSIG anyway, but only if this is not an ENT or
1233 	 * an unsigned delegation */
1234 	if (!emptynonterminal && !rr_list_delegation_only(cur_zone, rrs)) {
1235 		i_type_list[type_count] = LDNS_RR_TYPE_RRSIG;
1236 		type_count++;
1237 	}
1238 
1239 	/* and SOA if owner == zone */
1240 	if (ldns_dname_compare(cur_zone, cur_owner) == 0) {
1241 		i_type_list[type_count] = LDNS_RR_TYPE_SOA;
1242 		type_count++;
1243 	}
1244 
1245 	ldns_rr_push_rdf(nsec,
1246 				  ldns_dnssec_create_nsec_bitmap(i_type_list,
1247 						type_count, LDNS_RR_TYPE_NSEC3));
1248 
1249 	return nsec;
1250 }
1251 
1252 uint8_t
1253 ldns_nsec3_algorithm(const ldns_rr *nsec3_rr)
1254 {
1255 	if (nsec3_rr &&
1256 	      (ldns_rr_get_type(nsec3_rr) == LDNS_RR_TYPE_NSEC3 ||
1257 	       ldns_rr_get_type(nsec3_rr) == LDNS_RR_TYPE_NSEC3PARAM)
1258 	    && (ldns_rr_rdf(nsec3_rr, 0) != NULL)
1259 	    && ldns_rdf_size(ldns_rr_rdf(nsec3_rr, 0)) > 0) {
1260 		return ldns_rdf2native_int8(ldns_rr_rdf(nsec3_rr, 0));
1261 	}
1262 	return 0;
1263 }
1264 
1265 uint8_t
1266 ldns_nsec3_flags(const ldns_rr *nsec3_rr)
1267 {
1268 	if (nsec3_rr &&
1269 	      (ldns_rr_get_type(nsec3_rr) == LDNS_RR_TYPE_NSEC3 ||
1270 	       ldns_rr_get_type(nsec3_rr) == LDNS_RR_TYPE_NSEC3PARAM)
1271 	    && (ldns_rr_rdf(nsec3_rr, 1) != NULL)
1272 	    && ldns_rdf_size(ldns_rr_rdf(nsec3_rr, 1)) > 0) {
1273 		return ldns_rdf2native_int8(ldns_rr_rdf(nsec3_rr, 1));
1274 	}
1275 	return 0;
1276 }
1277 
1278 bool
1279 ldns_nsec3_optout(const ldns_rr *nsec3_rr)
1280 {
1281 	return (ldns_nsec3_flags(nsec3_rr) & LDNS_NSEC3_VARS_OPTOUT_MASK);
1282 }
1283 
1284 uint16_t
1285 ldns_nsec3_iterations(const ldns_rr *nsec3_rr)
1286 {
1287 	if (nsec3_rr &&
1288 	      (ldns_rr_get_type(nsec3_rr) == LDNS_RR_TYPE_NSEC3 ||
1289 	       ldns_rr_get_type(nsec3_rr) == LDNS_RR_TYPE_NSEC3PARAM)
1290 	    && (ldns_rr_rdf(nsec3_rr, 2) != NULL)
1291 	    && ldns_rdf_size(ldns_rr_rdf(nsec3_rr, 2)) > 0) {
1292 		return ldns_rdf2native_int16(ldns_rr_rdf(nsec3_rr, 2));
1293 	}
1294 	return 0;
1295 
1296 }
1297 
1298 ldns_rdf *
1299 ldns_nsec3_salt(const ldns_rr *nsec3_rr)
1300 {
1301 	if (nsec3_rr &&
1302 	      (ldns_rr_get_type(nsec3_rr) == LDNS_RR_TYPE_NSEC3 ||
1303 	       ldns_rr_get_type(nsec3_rr) == LDNS_RR_TYPE_NSEC3PARAM)
1304 	    ) {
1305 		return ldns_rr_rdf(nsec3_rr, 3);
1306 	}
1307 	return NULL;
1308 }
1309 
1310 uint8_t
1311 ldns_nsec3_salt_length(const ldns_rr *nsec3_rr)
1312 {
1313 	ldns_rdf *salt_rdf = ldns_nsec3_salt(nsec3_rr);
1314 	if (salt_rdf && ldns_rdf_size(salt_rdf) > 0) {
1315 		return (uint8_t) ldns_rdf_data(salt_rdf)[0];
1316 	}
1317 	return 0;
1318 }
1319 
1320 /* allocs data, free with LDNS_FREE() */
1321 uint8_t *
1322 ldns_nsec3_salt_data(const ldns_rr *nsec3_rr)
1323 {
1324 	uint8_t salt_length;
1325 	uint8_t *salt;
1326 
1327 	ldns_rdf *salt_rdf = ldns_nsec3_salt(nsec3_rr);
1328 	if (salt_rdf && ldns_rdf_size(salt_rdf) > 0) {
1329 	    	salt_length = ldns_rdf_data(salt_rdf)[0];
1330 		salt = LDNS_XMALLOC(uint8_t, salt_length);
1331                 if(!salt) return NULL;
1332 		memcpy(salt, &ldns_rdf_data(salt_rdf)[1], salt_length);
1333 		return salt;
1334 	}
1335 	return NULL;
1336 }
1337 
1338 ldns_rdf *
1339 ldns_nsec3_next_owner(const ldns_rr *nsec3_rr)
1340 {
1341 	if (!nsec3_rr || ldns_rr_get_type(nsec3_rr) != LDNS_RR_TYPE_NSEC3) {
1342 		return NULL;
1343 	} else {
1344 		return ldns_rr_rdf(nsec3_rr, 4);
1345 	}
1346 }
1347 
1348 ldns_rdf *
1349 ldns_nsec3_bitmap(const ldns_rr *nsec3_rr)
1350 {
1351 	if (!nsec3_rr || ldns_rr_get_type(nsec3_rr) != LDNS_RR_TYPE_NSEC3) {
1352 		return NULL;
1353 	} else {
1354 		return ldns_rr_rdf(nsec3_rr, 5);
1355 	}
1356 }
1357 
1358 ldns_rdf *
1359 ldns_nsec3_hash_name_frm_nsec3(const ldns_rr *nsec, const ldns_rdf *name)
1360 {
1361 	uint8_t algorithm;
1362 	uint16_t iterations;
1363 	uint8_t salt_length;
1364 	uint8_t *salt = 0;
1365 
1366 	ldns_rdf *hashed_owner;
1367 
1368 	algorithm = ldns_nsec3_algorithm(nsec);
1369 	salt_length = ldns_nsec3_salt_length(nsec);
1370 	salt = ldns_nsec3_salt_data(nsec);
1371 	iterations = ldns_nsec3_iterations(nsec);
1372 
1373 	hashed_owner = ldns_nsec3_hash_name(name,
1374 								 algorithm,
1375 								 iterations,
1376 								 salt_length,
1377 								 salt);
1378 
1379 	LDNS_FREE(salt);
1380 	return hashed_owner;
1381 }
1382 
1383 bool
1384 ldns_nsec_bitmap_covers_type(const ldns_rdf* bitmap, ldns_rr_type type)
1385 {
1386 	uint8_t* dptr;
1387 	uint8_t* dend;
1388 
1389 	/* From RFC3845 Section 2.1.2:
1390 	 *
1391 	 *	"The RR type space is split into 256 window blocks, each re-
1392 	 *	 presenting the low-order 8 bits of the 16-bit RR type space."
1393 	 */
1394 	uint8_t  window = type >> 8;
1395 	uint8_t subtype = type & 0xff;
1396 
1397 	if (! bitmap) {
1398 		return false;
1399 	}
1400 	assert(ldns_rdf_get_type(bitmap) == LDNS_RDF_TYPE_BITMAP);
1401 
1402 	dptr = ldns_rdf_data(bitmap);
1403 	dend = ldns_rdf_data(bitmap) + ldns_rdf_size(bitmap);
1404 
1405 	/* Type Bitmap = ( Window Block # | Bitmap Length | Bitmap ) +
1406 	 *                 dptr[0]          dptr[1]         dptr[2:]
1407 	 */
1408 	while (dptr < dend && dptr[0] <= window) {
1409 
1410 		if (dptr[0] == window && subtype / 8 < dptr[1] &&
1411 				dptr + dptr[1] + 2 <= dend) {
1412 
1413 			return dptr[2 + subtype / 8] & (0x80 >> (subtype % 8));
1414 		}
1415 		dptr += dptr[1] + 2; /* next window */
1416 	}
1417 	return false;
1418 }
1419 
1420 ldns_status
1421 ldns_nsec_bitmap_set_type(ldns_rdf* bitmap, ldns_rr_type type)
1422 {
1423 	uint8_t* dptr;
1424 	uint8_t* dend;
1425 
1426 	/* From RFC3845 Section 2.1.2:
1427 	 *
1428 	 *	"The RR type space is split into 256 window blocks, each re-
1429 	 *	 presenting the low-order 8 bits of the 16-bit RR type space."
1430 	 */
1431 	uint8_t  window = type >> 8;
1432 	uint8_t subtype = type & 0xff;
1433 
1434 	if (! bitmap) {
1435 		return false;
1436 	}
1437 	assert(ldns_rdf_get_type(bitmap) == LDNS_RDF_TYPE_BITMAP);
1438 
1439 	dptr = ldns_rdf_data(bitmap);
1440 	dend = ldns_rdf_data(bitmap) + ldns_rdf_size(bitmap);
1441 
1442 	/* Type Bitmap = ( Window Block # | Bitmap Length | Bitmap ) +
1443 	 *                 dptr[0]          dptr[1]         dptr[2:]
1444 	 */
1445 	while (dptr < dend && dptr[0] <= window) {
1446 
1447 		if (dptr[0] == window && subtype / 8 < dptr[1] &&
1448 				dptr + dptr[1] + 2 <= dend) {
1449 
1450 			dptr[2 + subtype / 8] |= (0x80 >> (subtype % 8));
1451 			return LDNS_STATUS_OK;
1452 		}
1453 		dptr += dptr[1] + 2; /* next window */
1454 	}
1455 	return LDNS_STATUS_TYPE_NOT_IN_BITMAP;
1456 }
1457 
1458 ldns_status
1459 ldns_nsec_bitmap_clear_type(ldns_rdf* bitmap, ldns_rr_type type)
1460 {
1461 	uint8_t* dptr;
1462 	uint8_t* dend;
1463 
1464 	/* From RFC3845 Section 2.1.2:
1465 	 *
1466 	 *	"The RR type space is split into 256 window blocks, each re-
1467 	 *	 presenting the low-order 8 bits of the 16-bit RR type space."
1468 	 */
1469 	uint8_t  window = type >> 8;
1470 	uint8_t subtype = type & 0xff;
1471 
1472 	if (! bitmap) {
1473 		return false;
1474 	}
1475 
1476 	assert(ldns_rdf_get_type(bitmap) == LDNS_RDF_TYPE_BITMAP);
1477 
1478 	dptr = ldns_rdf_data(bitmap);
1479 	dend = ldns_rdf_data(bitmap) + ldns_rdf_size(bitmap);
1480 
1481 	/* Type Bitmap = ( Window Block # | Bitmap Length | Bitmap ) +
1482 	 *                 dptr[0]          dptr[1]         dptr[2:]
1483 	 */
1484 	while (dptr < dend && dptr[0] <= window) {
1485 
1486 		if (dptr[0] == window && subtype / 8 < dptr[1] &&
1487 				dptr + dptr[1] + 2 <= dend) {
1488 
1489 			dptr[2 + subtype / 8] &= ~(0x80 >> (subtype % 8));
1490 			return LDNS_STATUS_OK;
1491 		}
1492 		dptr += dptr[1] + 2; /* next window */
1493 	}
1494 	return LDNS_STATUS_TYPE_NOT_IN_BITMAP;
1495 }
1496 
1497 
1498 bool
1499 ldns_nsec_covers_name(const ldns_rr *nsec, const ldns_rdf *name)
1500 {
1501 	ldns_rdf *nsec_owner = ldns_rr_owner(nsec);
1502 	ldns_rdf *hash_next;
1503 	char *next_hash_str;
1504 	ldns_rdf *nsec_next = NULL;
1505 	ldns_status status;
1506 	ldns_rdf *chopped_dname;
1507 	bool result;
1508 
1509 	if (ldns_rr_get_type(nsec) == LDNS_RR_TYPE_NSEC) {
1510 		if (ldns_rr_rdf(nsec, 0) != NULL) {
1511 			nsec_next = ldns_rdf_clone(ldns_rr_rdf(nsec, 0));
1512 		} else {
1513 			return false;
1514 		}
1515 	} else if (ldns_rr_get_type(nsec) == LDNS_RR_TYPE_NSEC3) {
1516 		hash_next = ldns_nsec3_next_owner(nsec);
1517 		next_hash_str = ldns_rdf2str(hash_next);
1518 		nsec_next = ldns_dname_new_frm_str(next_hash_str);
1519 		LDNS_FREE(next_hash_str);
1520 		chopped_dname = ldns_dname_left_chop(nsec_owner);
1521 		status = ldns_dname_cat(nsec_next, chopped_dname);
1522 		ldns_rdf_deep_free(chopped_dname);
1523 		if (status != LDNS_STATUS_OK) {
1524 			printf("error catting: %s\n", ldns_get_errorstr_by_id(status));
1525 		}
1526 	} else {
1527 		ldns_rdf_deep_free(nsec_next);
1528 		return false;
1529 	}
1530 
1531 	/* in the case of the last nsec */
1532 	if(ldns_dname_compare(nsec_owner, nsec_next) > 0) {
1533 		result = (ldns_dname_compare(nsec_owner, name) <= 0 ||
1534 				ldns_dname_compare(name, nsec_next) < 0);
1535 	} else if(ldns_dname_compare(nsec_owner, nsec_next) < 0) {
1536 		result = (ldns_dname_compare(nsec_owner, name) <= 0 &&
1537 		          ldns_dname_compare(name, nsec_next) < 0);
1538 	} else {
1539 		result = true;
1540 	}
1541 
1542 	ldns_rdf_deep_free(nsec_next);
1543 	return result;
1544 }
1545 
1546 #ifdef HAVE_SSL
1547 /* sig may be null - if so look in the packet */
1548 
1549 ldns_status
1550 ldns_pkt_verify_time(const ldns_pkt *p, ldns_rr_type t, const ldns_rdf *o,
1551 		const ldns_rr_list *k, const ldns_rr_list *s,
1552 		time_t check_time, ldns_rr_list *good_keys)
1553 {
1554 	ldns_rr_list *rrset;
1555 	ldns_rr_list *sigs;
1556 	ldns_rr_list *sigs_covered;
1557 	ldns_rdf *rdf_t;
1558 	ldns_rr_type t_netorder;
1559 
1560 	if (!k) {
1561 		return LDNS_STATUS_ERR;
1562 		/* return LDNS_STATUS_CRYPTO_NO_DNSKEY; */
1563 	}
1564 
1565 	if (t == LDNS_RR_TYPE_RRSIG) {
1566 		/* we don't have RRSIG(RRSIG) (yet? ;-) ) */
1567 		return LDNS_STATUS_ERR;
1568 	}
1569 
1570 	if (s) {
1571 		/* if s is not NULL, the sigs are given to use */
1572 		sigs = (ldns_rr_list *)s;
1573 	} else {
1574 		/* otherwise get them from the packet */
1575 		sigs = ldns_pkt_rr_list_by_name_and_type(p, o,
1576 				LDNS_RR_TYPE_RRSIG,
1577 				LDNS_SECTION_ANY_NOQUESTION);
1578 		if (!sigs) {
1579 			/* no sigs */
1580 			return LDNS_STATUS_ERR;
1581 			/* return LDNS_STATUS_CRYPTO_NO_RRSIG; */
1582 		}
1583 	}
1584 
1585 	/* rrsig are subtyped, so now we need to find the correct
1586 	 * sigs for the type t
1587 	 */
1588 	t_netorder = htons(t); /* rdf are in network order! */
1589 	/* a type identifier is a 16-bit number, so the size is 2 bytes */
1590 	rdf_t = ldns_rdf_new(LDNS_RDF_TYPE_TYPE, 2, &t_netorder);
1591 
1592 	sigs_covered = ldns_rr_list_subtype_by_rdf(sigs, rdf_t, 0);
1593 	ldns_rdf_free(rdf_t);
1594 	if (! sigs_covered) {
1595 		if (! s) {
1596 			ldns_rr_list_deep_free(sigs);
1597 		}
1598 		return LDNS_STATUS_ERR;
1599 	}
1600 	ldns_rr_list_deep_free(sigs_covered);
1601 
1602 	rrset = ldns_pkt_rr_list_by_name_and_type(p, o, t,
1603 			LDNS_SECTION_ANY_NOQUESTION);
1604 	if (!rrset) {
1605 		if (! s) {
1606 			ldns_rr_list_deep_free(sigs);
1607 		}
1608 		return LDNS_STATUS_ERR;
1609 	}
1610 	return ldns_verify_time(rrset, sigs, k, check_time, good_keys);
1611 }
1612 
1613 ldns_status
1614 ldns_pkt_verify(const ldns_pkt *p, ldns_rr_type t, const ldns_rdf *o,
1615 		const ldns_rr_list *k, const ldns_rr_list *s, ldns_rr_list *good_keys)
1616 {
1617 	return ldns_pkt_verify_time(p, t, o, k, s, ldns_time(NULL), good_keys);
1618 }
1619 #endif /* HAVE_SSL */
1620 
1621 ldns_status
1622 ldns_dnssec_chain_nsec3_list(ldns_rr_list *nsec3_rrs)
1623 {
1624 	size_t i;
1625 	char *next_nsec_owner_str;
1626 	ldns_rdf *next_nsec_owner_label;
1627 	ldns_rdf *next_nsec_rdf;
1628 	ldns_status status = LDNS_STATUS_OK;
1629 
1630 	for (i = 0; i < ldns_rr_list_rr_count(nsec3_rrs); i++) {
1631 		if (i == ldns_rr_list_rr_count(nsec3_rrs) - 1) {
1632 			next_nsec_owner_label =
1633 				ldns_dname_label(ldns_rr_owner(ldns_rr_list_rr(nsec3_rrs,
1634 													  0)), 0);
1635 			next_nsec_owner_str = ldns_rdf2str(next_nsec_owner_label);
1636 			if (next_nsec_owner_str[strlen(next_nsec_owner_str) - 1]
1637 			    == '.') {
1638 				next_nsec_owner_str[strlen(next_nsec_owner_str) - 1]
1639 					= '\0';
1640 			}
1641 			status = ldns_str2rdf_b32_ext(&next_nsec_rdf,
1642 									next_nsec_owner_str);
1643 			if (!ldns_rr_set_rdf(ldns_rr_list_rr(nsec3_rrs, i),
1644 							 next_nsec_rdf, 4)) {
1645 				/* todo: error */
1646 			}
1647 
1648 			ldns_rdf_deep_free(next_nsec_owner_label);
1649 			LDNS_FREE(next_nsec_owner_str);
1650 		} else {
1651 			next_nsec_owner_label =
1652 				ldns_dname_label(ldns_rr_owner(ldns_rr_list_rr(nsec3_rrs,
1653 													  i + 1)),
1654 							  0);
1655 			next_nsec_owner_str = ldns_rdf2str(next_nsec_owner_label);
1656 			if (next_nsec_owner_str[strlen(next_nsec_owner_str) - 1]
1657 			    == '.') {
1658 				next_nsec_owner_str[strlen(next_nsec_owner_str) - 1]
1659 					= '\0';
1660 			}
1661 			status = ldns_str2rdf_b32_ext(&next_nsec_rdf,
1662 									next_nsec_owner_str);
1663 			ldns_rdf_deep_free(next_nsec_owner_label);
1664 			LDNS_FREE(next_nsec_owner_str);
1665 			if (!ldns_rr_set_rdf(ldns_rr_list_rr(nsec3_rrs, i),
1666 							 next_nsec_rdf, 4)) {
1667 				/* todo: error */
1668 			}
1669 		}
1670 	}
1671 	return status;
1672 }
1673 
1674 int
1675 qsort_rr_compare_nsec3(const void *a, const void *b)
1676 {
1677 	const ldns_rr *rr1 = * (const ldns_rr **) a;
1678 	const ldns_rr *rr2 = * (const ldns_rr **) b;
1679 	if (rr1 == NULL && rr2 == NULL) {
1680 		return 0;
1681 	}
1682 	if (rr1 == NULL) {
1683 		return -1;
1684 	}
1685 	if (rr2 == NULL) {
1686 		return 1;
1687 	}
1688 	return ldns_rdf_compare(ldns_rr_owner(rr1), ldns_rr_owner(rr2));
1689 }
1690 
1691 void
1692 ldns_rr_list_sort_nsec3(ldns_rr_list *unsorted)
1693 {
1694 	qsort(unsorted->_rrs,
1695 	      ldns_rr_list_rr_count(unsorted),
1696 	      sizeof(ldns_rr *),
1697 	      qsort_rr_compare_nsec3);
1698 }
1699 
1700 int
1701 ldns_dnssec_default_add_to_signatures( ATTR_UNUSED(ldns_rr *sig)
1702 				     , ATTR_UNUSED(void *n)
1703 				     )
1704 {
1705 	return LDNS_SIGNATURE_LEAVE_ADD_NEW;
1706 }
1707 
1708 int
1709 ldns_dnssec_default_leave_signatures( ATTR_UNUSED(ldns_rr *sig)
1710 				    , ATTR_UNUSED(void *n)
1711 				    )
1712 {
1713 	return LDNS_SIGNATURE_LEAVE_NO_ADD;
1714 }
1715 
1716 int
1717 ldns_dnssec_default_delete_signatures( ATTR_UNUSED(ldns_rr *sig)
1718 				     , ATTR_UNUSED(void *n)
1719 				     )
1720 {
1721 	return LDNS_SIGNATURE_REMOVE_NO_ADD;
1722 }
1723 
1724 int
1725 ldns_dnssec_default_replace_signatures( ATTR_UNUSED(ldns_rr *sig)
1726 				      , ATTR_UNUSED(void *n)
1727 				      )
1728 {
1729 	return LDNS_SIGNATURE_REMOVE_ADD_NEW;
1730 }
1731 
1732 #ifdef HAVE_SSL
1733 ldns_rdf *
1734 ldns_convert_dsa_rrsig_asn12rdf(const ldns_buffer *sig,
1735 						  const long sig_len)
1736 {
1737 #ifdef USE_DSA
1738 	ldns_rdf *sigdata_rdf;
1739 	DSA_SIG *dsasig;
1740 	const BIGNUM *R, *S;
1741 	unsigned char *dsasig_data = (unsigned char*)ldns_buffer_begin(sig);
1742 	size_t byte_offset;
1743 
1744 	dsasig = d2i_DSA_SIG(NULL,
1745 					 (const unsigned char **)&dsasig_data,
1746 					 sig_len);
1747 	if (!dsasig) {
1748                 DSA_SIG_free(dsasig);
1749 		return NULL;
1750 	}
1751 
1752 	dsasig_data = LDNS_XMALLOC(unsigned char, 41);
1753         if(!dsasig_data) {
1754                 DSA_SIG_free(dsasig);
1755                 return NULL;
1756         }
1757 	dsasig_data[0] = 0;
1758 # ifdef HAVE_DSA_SIG_GET0
1759 	DSA_SIG_get0(dsasig, &R, &S);
1760 # else
1761 	R = dsasig->r;
1762 	S = dsasig->s;
1763 # endif
1764 	byte_offset = (size_t) (20 - BN_num_bytes(R));
1765 	if (byte_offset > 20) {
1766                 DSA_SIG_free(dsasig);
1767                 LDNS_FREE(dsasig_data);
1768 		return NULL;
1769 	}
1770 	memset(&dsasig_data[1], 0, byte_offset);
1771 	BN_bn2bin(R, &dsasig_data[1 + byte_offset]);
1772 	byte_offset = (size_t) (20 - BN_num_bytes(S));
1773 	if (byte_offset > 20) {
1774                 DSA_SIG_free(dsasig);
1775                 LDNS_FREE(dsasig_data);
1776 		return NULL;
1777 	}
1778 	memset(&dsasig_data[21], 0, byte_offset);
1779 	BN_bn2bin(S, &dsasig_data[21 + byte_offset]);
1780 
1781 	sigdata_rdf = ldns_rdf_new(LDNS_RDF_TYPE_B64, 41, dsasig_data);
1782         if(!sigdata_rdf) {
1783                 LDNS_FREE(dsasig_data);
1784         }
1785 	DSA_SIG_free(dsasig);
1786 
1787 	return sigdata_rdf;
1788 #else
1789 	(void)sig; (void)sig_len;
1790 	return NULL;
1791 #endif
1792 }
1793 
1794 ldns_status
1795 ldns_convert_dsa_rrsig_rdf2asn1(ldns_buffer *target_buffer,
1796 						  const ldns_rdf *sig_rdf)
1797 {
1798 #ifdef USE_DSA
1799 	/* the EVP api wants the DER encoding of the signature... */
1800 	BIGNUM *R, *S;
1801 	DSA_SIG *dsasig;
1802 	unsigned char *raw_sig = NULL;
1803 	int raw_sig_len;
1804 
1805         if(ldns_rdf_size(sig_rdf) < 1 + 2*SHA_DIGEST_LENGTH)
1806                 return LDNS_STATUS_SYNTAX_RDATA_ERR;
1807 	/* extract the R and S field from the sig buffer */
1808 	R = BN_new();
1809 	if(!R) return LDNS_STATUS_MEM_ERR;
1810 	(void) BN_bin2bn((unsigned char *) ldns_rdf_data(sig_rdf) + 1,
1811 	                 SHA_DIGEST_LENGTH, R);
1812 	S = BN_new();
1813 	if(!S) {
1814 		BN_free(R);
1815 		return LDNS_STATUS_MEM_ERR;
1816 	}
1817 	(void) BN_bin2bn((unsigned char *) ldns_rdf_data(sig_rdf) + 21,
1818 	                 SHA_DIGEST_LENGTH, S);
1819 
1820 	dsasig = DSA_SIG_new();
1821 	if (!dsasig) {
1822 		BN_free(R);
1823 		BN_free(S);
1824 		return LDNS_STATUS_MEM_ERR;
1825 	}
1826 # ifdef HAVE_DSA_SIG_SET0
1827        if (! DSA_SIG_set0(dsasig, R, S))
1828 	       return LDNS_STATUS_SSL_ERR;
1829 # else
1830 	dsasig->r = R;
1831 	dsasig->s = S;
1832 # endif
1833 
1834 	raw_sig_len = i2d_DSA_SIG(dsasig, &raw_sig);
1835 	if (raw_sig_len < 0) {
1836 		DSA_SIG_free(dsasig);
1837 		free(raw_sig);
1838 		return LDNS_STATUS_SSL_ERR;
1839 	}
1840 	if (ldns_buffer_reserve(target_buffer, (size_t) raw_sig_len)) {
1841 		ldns_buffer_write(target_buffer, raw_sig, (size_t)raw_sig_len);
1842 	}
1843 
1844 	DSA_SIG_free(dsasig);
1845 	free(raw_sig);
1846 
1847 	return ldns_buffer_status(target_buffer);
1848 #else
1849 	(void)target_buffer; (void)sig_rdf;
1850 	return LDNS_STATUS_CRYPTO_ALGO_NOT_IMPL;
1851 #endif
1852 }
1853 
1854 #ifdef USE_ECDSA
1855 #ifndef S_SPLINT_S
1856 ldns_rdf *
1857 ldns_convert_ecdsa_rrsig_asn1len2rdf(const ldns_buffer *sig,
1858 	const long sig_len, int num_bytes)
1859 {
1860         ECDSA_SIG* ecdsa_sig;
1861 	const BIGNUM *r, *s;
1862 	unsigned char *data = (unsigned char*)ldns_buffer_begin(sig);
1863         ldns_rdf* rdf;
1864 	ecdsa_sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&data, sig_len);
1865         if(!ecdsa_sig) return NULL;
1866 
1867 #ifdef HAVE_ECDSA_SIG_GET0
1868 	ECDSA_SIG_get0(ecdsa_sig, &r, &s);
1869 #else
1870 	r = ecdsa_sig->r;
1871 	s = ecdsa_sig->s;
1872 #endif
1873         /* "r | s". */
1874         if(BN_num_bytes(r) > num_bytes ||
1875 		BN_num_bytes(s) > num_bytes) {
1876                 ECDSA_SIG_free(ecdsa_sig);
1877 		return NULL; /* numbers too big for passed curve size */
1878 	}
1879         data = LDNS_XMALLOC(unsigned char, num_bytes*2);
1880         if(!data) {
1881                 ECDSA_SIG_free(ecdsa_sig);
1882                 return NULL;
1883         }
1884 	/* write the bignums (in big-endian) a little offset if the BN code
1885 	 * wants to write a shorter number of bytes, with zeroes prefixed */
1886 	memset(data, 0, num_bytes*2);
1887         BN_bn2bin(r, data+num_bytes-BN_num_bytes(r));
1888         BN_bn2bin(s, data+num_bytes*2-BN_num_bytes(s));
1889 	rdf = ldns_rdf_new(LDNS_RDF_TYPE_B64, (size_t)(num_bytes*2), data);
1890         ECDSA_SIG_free(ecdsa_sig);
1891         return rdf;
1892 }
1893 
1894 ldns_status
1895 ldns_convert_ecdsa_rrsig_rdf2asn1(ldns_buffer *target_buffer,
1896         const ldns_rdf *sig_rdf)
1897 {
1898         /* convert from two BIGNUMs in the rdata buffer, to ASN notation.
1899 	 * ASN preable:  30440220 <R 32bytefor256> 0220 <S 32bytefor256>
1900 	 * the '20' is the length of that field (=bnsize).
1901 	 * the '44' is the total remaining length.
1902 	 * if negative, start with leading zero.
1903 	 * if starts with 00s, remove them from the number.
1904 	 */
1905         uint8_t pre[] = {0x30, 0x44, 0x02, 0x20};
1906         int pre_len = 4;
1907         uint8_t mid[] = {0x02, 0x20};
1908         int mid_len = 2;
1909         int raw_sig_len, r_high, s_high, r_rem=0, s_rem=0;
1910         long bnsize = (long)ldns_rdf_size(sig_rdf) / 2;
1911         uint8_t* d = ldns_rdf_data(sig_rdf);
1912         /* if too short, or not even length, do not bother */
1913         if(bnsize < 16 || (size_t)bnsize*2 != ldns_rdf_size(sig_rdf))
1914                 return LDNS_STATUS_ERR;
1915         /* strip leading zeroes from r (but not last one) */
1916         while(r_rem < bnsize-1 && d[r_rem] == 0)
1917                 r_rem++;
1918         /* strip leading zeroes from s (but not last one) */
1919         while(s_rem < bnsize-1 && d[bnsize+s_rem] == 0)
1920                 s_rem++;
1921 
1922         r_high = ((d[0+r_rem]&0x80)?1:0);
1923         s_high = ((d[bnsize+s_rem]&0x80)?1:0);
1924         raw_sig_len = pre_len + r_high + bnsize - r_rem + mid_len +
1925 		s_high + bnsize - s_rem;
1926         if(ldns_buffer_reserve(target_buffer, (size_t) raw_sig_len)) {
1927                 ldns_buffer_write_u8(target_buffer, pre[0]);
1928                 ldns_buffer_write_u8(target_buffer, raw_sig_len-2);
1929                 ldns_buffer_write_u8(target_buffer, pre[2]);
1930                 ldns_buffer_write_u8(target_buffer, bnsize + r_high - r_rem);
1931                 if(r_high)
1932                         ldns_buffer_write_u8(target_buffer, 0);
1933                 ldns_buffer_write(target_buffer, d+r_rem, bnsize-r_rem);
1934                 ldns_buffer_write(target_buffer, mid, mid_len-1);
1935                 ldns_buffer_write_u8(target_buffer, bnsize + s_high - s_rem);
1936                 if(s_high)
1937                         ldns_buffer_write_u8(target_buffer, 0);
1938                 ldns_buffer_write(target_buffer, d+bnsize+s_rem, bnsize-s_rem);
1939         }
1940         return ldns_buffer_status(target_buffer);
1941 }
1942 
1943 #endif /* S_SPLINT_S */
1944 #endif /* USE_ECDSA */
1945 
1946 #if defined(USE_ED25519) || defined(USE_ED448)
1947 /* debug printout routine */
1948 static void print_hex(const char* str, uint8_t* d, int len)
1949 {
1950 	const char hex[] = "0123456789abcdef";
1951 	int i;
1952 	printf("%s [len=%d]: ", str, len);
1953 	for(i=0; i<len; i++) {
1954 		int x = (d[i]&0xf0)>>4;
1955 		int y = (d[i]&0x0f);
1956 		printf("%c%c", hex[x], hex[y]);
1957 	}
1958 	printf("\n");
1959 }
1960 #endif
1961 
1962 #ifdef USE_ED25519
1963 ldns_rdf *
1964 ldns_convert_ed25519_rrsig_asn12rdf(const ldns_buffer *sig, long sig_len)
1965 {
1966 	unsigned char *data = (unsigned char*)ldns_buffer_begin(sig);
1967         ldns_rdf* rdf = NULL;
1968 
1969 	/* TODO when Openssl supports signing and you can test this */
1970 	print_hex("sig in ASN", data, sig_len);
1971 
1972         return rdf;
1973 }
1974 
1975 ldns_status
1976 ldns_convert_ed25519_rrsig_rdf2asn1(ldns_buffer *target_buffer,
1977         const ldns_rdf *sig_rdf)
1978 {
1979 	/* TODO when Openssl supports signing and you can test this. */
1980 	/* convert sig_buf into ASN1 into the target_buffer */
1981 	print_hex("sig raw", ldns_rdf_data(sig_rdf), ldns_rdf_size(sig_rdf));
1982         return ldns_buffer_status(target_buffer);
1983 }
1984 #endif /* USE_ED25519 */
1985 
1986 #ifdef USE_ED448
1987 ldns_rdf *
1988 ldns_convert_ed448_rrsig_asn12rdf(const ldns_buffer *sig, long sig_len)
1989 {
1990 	unsigned char *data = (unsigned char*)ldns_buffer_begin(sig);
1991         ldns_rdf* rdf = NULL;
1992 
1993 	/* TODO when Openssl supports signing and you can test this */
1994 	print_hex("sig in ASN", data, sig_len);
1995 
1996 	return rdf;
1997 }
1998 
1999 ldns_status
2000 ldns_convert_ed448_rrsig_rdf2asn1(ldns_buffer *target_buffer,
2001         const ldns_rdf *sig_rdf)
2002 {
2003 	/* TODO when Openssl supports signing and you can test this. */
2004 	/* convert sig_buf into ASN1 into the target_buffer */
2005 	print_hex("sig raw", ldns_rdf_data(sig_rdf), ldns_rdf_size(sig_rdf));
2006         return ldns_buffer_status(target_buffer);
2007 }
2008 #endif /* USE_ED448 */
2009 
2010 #endif /* HAVE_SSL */
2011