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