keys.c revision 246827
1/*
2 * keys.c handle private keys for use in DNSSEC
3 *
4 * This module should hide some of the openSSL complexities
5 * and give a general interface for private keys and hmac
6 * handling
7 *
8 * (c) NLnet Labs, 2004-2006
9 *
10 * See the file LICENSE for the license
11 */
12
13#include <ldns/config.h>
14
15#include <ldns/ldns.h>
16
17#ifdef HAVE_SSL
18#include <openssl/ssl.h>
19#include <openssl/engine.h>
20#include <openssl/rand.h>
21#endif /* HAVE_SSL */
22
23ldns_lookup_table ldns_signing_algorithms[] = {
24        { LDNS_SIGN_RSAMD5, "RSAMD5" },
25        { LDNS_SIGN_RSASHA1, "RSASHA1" },
26        { LDNS_SIGN_RSASHA1_NSEC3, "RSASHA1-NSEC3-SHA1" },
27#ifdef USE_SHA2
28        { LDNS_SIGN_RSASHA256, "RSASHA256" },
29        { LDNS_SIGN_RSASHA512, "RSASHA512" },
30#endif
31#ifdef USE_GOST
32        { LDNS_SIGN_ECC_GOST, "ECC-GOST" },
33#endif
34#ifdef USE_ECDSA
35        { LDNS_SIGN_ECDSAP256SHA256, "ECDSAP256SHA256" },
36        { LDNS_SIGN_ECDSAP384SHA384, "ECDSAP384SHA384" },
37#endif
38        { LDNS_SIGN_DSA, "DSA" },
39        { LDNS_SIGN_DSA_NSEC3, "DSA-NSEC3-SHA1" },
40        { LDNS_SIGN_HMACMD5, "hmac-md5.sig-alg.reg.int" },
41        { LDNS_SIGN_HMACSHA1, "hmac-sha1" },
42        { LDNS_SIGN_HMACSHA256, "hmac-sha256" },
43        { 0, NULL }
44};
45
46ldns_key_list *
47ldns_key_list_new(void)
48{
49	ldns_key_list *key_list = LDNS_MALLOC(ldns_key_list);
50	if (!key_list) {
51		return NULL;
52	} else {
53		key_list->_key_count = 0;
54		key_list->_keys = NULL;
55		return key_list;
56	}
57}
58
59ldns_key *
60ldns_key_new(void)
61{
62	ldns_key *newkey;
63
64	newkey = LDNS_MALLOC(ldns_key);
65	if (!newkey) {
66		return NULL;
67	} else {
68		/* some defaults - not sure wether to do this */
69		ldns_key_set_use(newkey, true);
70		ldns_key_set_flags(newkey, LDNS_KEY_ZONE_KEY);
71		ldns_key_set_origttl(newkey, 0);
72		ldns_key_set_keytag(newkey, 0);
73		ldns_key_set_inception(newkey, 0);
74		ldns_key_set_expiration(newkey, 0);
75		ldns_key_set_pubkey_owner(newkey, NULL);
76#ifdef HAVE_SSL
77		ldns_key_set_evp_key(newkey, NULL);
78#endif /* HAVE_SSL */
79		ldns_key_set_hmac_key(newkey, NULL);
80		ldns_key_set_external_key(newkey, NULL);
81		return newkey;
82	}
83}
84
85ldns_status
86ldns_key_new_frm_fp(ldns_key **k, FILE *fp)
87{
88	return ldns_key_new_frm_fp_l(k, fp, NULL);
89}
90
91#ifdef HAVE_SSL
92ldns_status
93ldns_key_new_frm_engine(ldns_key **key, ENGINE *e, char *key_id, ldns_algorithm alg)
94{
95	ldns_key *k;
96
97	k = ldns_key_new();
98        if(!k) return LDNS_STATUS_MEM_ERR;
99#ifndef S_SPLINT_S
100	k->_key.key = ENGINE_load_private_key(e, key_id, UI_OpenSSL(), NULL);
101        if(!k->_key.key) {
102                ldns_key_free(k);
103                return LDNS_STATUS_ERR;
104        }
105	ldns_key_set_algorithm(k, (ldns_signing_algorithm) alg);
106	if (!k->_key.key) {
107                ldns_key_free(k);
108		return LDNS_STATUS_ENGINE_KEY_NOT_LOADED;
109	}
110#endif /* splint */
111	*key = k;
112	return LDNS_STATUS_OK;
113}
114#endif
115
116#ifdef USE_GOST
117/** store GOST engine reference loaded into OpenSSL library */
118ENGINE* ldns_gost_engine = NULL;
119
120int
121ldns_key_EVP_load_gost_id(void)
122{
123	static int gost_id = 0;
124	const EVP_PKEY_ASN1_METHOD* meth;
125	ENGINE* e;
126
127	if(gost_id) return gost_id;
128
129	/* see if configuration loaded gost implementation from other engine*/
130	meth = EVP_PKEY_asn1_find_str(NULL, "gost2001", -1);
131	if(meth) {
132		EVP_PKEY_asn1_get0_info(&gost_id, NULL, NULL, NULL, NULL, meth);
133		return gost_id;
134	}
135
136	/* see if engine can be loaded already */
137	e = ENGINE_by_id("gost");
138	if(!e) {
139		/* load it ourself, in case statically linked */
140		ENGINE_load_builtin_engines();
141		ENGINE_load_dynamic();
142		e = ENGINE_by_id("gost");
143	}
144	if(!e) {
145		/* no gost engine in openssl */
146		return 0;
147	}
148	if(!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
149		ENGINE_finish(e);
150		ENGINE_free(e);
151		return 0;
152	}
153
154	meth = EVP_PKEY_asn1_find_str(&e, "gost2001", -1);
155	if(!meth) {
156		/* algo not found */
157		ENGINE_finish(e);
158		ENGINE_free(e);
159		return 0;
160	}
161        /* Note: do not ENGINE_finish and ENGINE_free the acquired engine
162         * on some platforms this frees up the meth and unloads gost stuff */
163        ldns_gost_engine = e;
164
165	EVP_PKEY_asn1_get0_info(&gost_id, NULL, NULL, NULL, NULL, meth);
166	return gost_id;
167}
168
169void ldns_key_EVP_unload_gost(void)
170{
171        if(ldns_gost_engine) {
172                ENGINE_finish(ldns_gost_engine);
173                ENGINE_free(ldns_gost_engine);
174                ldns_gost_engine = NULL;
175        }
176}
177
178/** read GOST private key */
179static EVP_PKEY*
180ldns_key_new_frm_fp_gost_l(FILE* fp, int* line_nr)
181{
182	char token[16384];
183	const unsigned char* pp;
184	int gost_id;
185	EVP_PKEY* pkey;
186	ldns_rdf* b64rdf = NULL;
187
188	gost_id = ldns_key_EVP_load_gost_id();
189	if(!gost_id)
190		return NULL;
191
192	if (ldns_fget_keyword_data_l(fp, "GostAsn1", ": ", token, "\n",
193		sizeof(token), line_nr) == -1)
194		return NULL;
195	while(strlen(token) < 96) {
196		/* read more b64 from the file, b64 split on multiple lines */
197		if(ldns_fget_token_l(fp, token+strlen(token), "\n",
198			sizeof(token)-strlen(token), line_nr) == -1)
199			return NULL;
200	}
201	if(ldns_str2rdf_b64(&b64rdf, token) != LDNS_STATUS_OK)
202		return NULL;
203	pp = (unsigned char*)ldns_rdf_data(b64rdf);
204	pkey = d2i_PrivateKey(gost_id, NULL, &pp, (int)ldns_rdf_size(b64rdf));
205	ldns_rdf_deep_free(b64rdf);
206	return pkey;
207}
208#endif
209
210#ifdef USE_ECDSA
211/** calculate public key from private key */
212static int
213ldns_EC_KEY_calc_public(EC_KEY* ec)
214{
215        EC_POINT* pub_key;
216        const EC_GROUP* group;
217        group = EC_KEY_get0_group(ec);
218        pub_key = EC_POINT_new(group);
219        if(!pub_key) return 0;
220        if(!EC_POINT_copy(pub_key, EC_GROUP_get0_generator(group))) {
221                EC_POINT_free(pub_key);
222                return 0;
223        }
224        if(!EC_POINT_mul(group, pub_key, EC_KEY_get0_private_key(ec),
225                NULL, NULL, NULL)) {
226                EC_POINT_free(pub_key);
227                return 0;
228        }
229        if(EC_KEY_set_public_key(ec, pub_key) == 0) {
230                EC_POINT_free(pub_key);
231                return 0;
232        }
233        EC_POINT_free(pub_key);
234        return 1;
235}
236
237/** read ECDSA private key */
238static EVP_PKEY*
239ldns_key_new_frm_fp_ecdsa_l(FILE* fp, ldns_algorithm alg, int* line_nr)
240{
241	char token[16384];
242        ldns_rdf* b64rdf = NULL;
243        unsigned char* pp;
244        BIGNUM* bn;
245        EVP_PKEY* evp_key;
246        EC_KEY* ec;
247	if (ldns_fget_keyword_data_l(fp, "PrivateKey", ": ", token, "\n",
248		sizeof(token), line_nr) == -1)
249		return NULL;
250	if(ldns_str2rdf_b64(&b64rdf, token) != LDNS_STATUS_OK)
251		return NULL;
252        pp = (unsigned char*)ldns_rdf_data(b64rdf);
253
254        if(alg == LDNS_ECDSAP256SHA256)
255                ec = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
256        else if(alg == LDNS_ECDSAP384SHA384)
257                ec = EC_KEY_new_by_curve_name(NID_secp384r1);
258        else    ec = NULL;
259        if(!ec) {
260	        ldns_rdf_deep_free(b64rdf);
261                return NULL;
262        }
263	bn = BN_bin2bn(pp, (int)ldns_rdf_size(b64rdf), NULL);
264	ldns_rdf_deep_free(b64rdf);
265        if(!bn) {
266                EC_KEY_free(ec);
267                return NULL;
268        }
269        EC_KEY_set_private_key(ec, bn);
270        BN_free(bn);
271        if(!ldns_EC_KEY_calc_public(ec)) {
272                EC_KEY_free(ec);
273                return NULL;
274        }
275
276        evp_key = EVP_PKEY_new();
277        if(!evp_key) {
278                EC_KEY_free(ec);
279                return NULL;
280        }
281        if (!EVP_PKEY_assign_EC_KEY(evp_key, ec)) {
282		EVP_PKEY_free(evp_key);
283                EC_KEY_free(ec);
284                return NULL;
285	}
286        return evp_key;
287}
288#endif
289
290ldns_status
291ldns_key_new_frm_fp_l(ldns_key **key, FILE *fp, int *line_nr)
292{
293	ldns_key *k;
294	char *d;
295	ldns_signing_algorithm alg;
296	ldns_rr *key_rr;
297#ifdef HAVE_SSL
298	RSA *rsa;
299	DSA *dsa;
300	unsigned char *hmac;
301	size_t hmac_size;
302#endif /* HAVE_SSL */
303
304	k = ldns_key_new();
305
306	d = LDNS_XMALLOC(char, LDNS_MAX_LINELEN);
307	if (!k || !d) {
308                ldns_key_free(k);
309                LDNS_FREE(d);
310		return LDNS_STATUS_MEM_ERR;
311	}
312
313	alg = 0;
314
315	/* the file is highly structured. Do this in sequence */
316	/* RSA:
317	 * Private-key-format: v1.x.
318 	 * Algorithm: 1 (RSA)
319
320	 */
321	/* get the key format version number */
322	if (ldns_fget_keyword_data_l(fp, "Private-key-format", ": ", d, "\n",
323				LDNS_MAX_LINELEN, line_nr) == -1) {
324		/* no version information */
325                ldns_key_free(k);
326                LDNS_FREE(d);
327		return LDNS_STATUS_SYNTAX_ERR;
328	}
329	if (strncmp(d, "v1.", 3) != 0) {
330                ldns_key_free(k);
331                LDNS_FREE(d);
332		return LDNS_STATUS_SYNTAX_VERSION_ERR;
333	}
334
335	/* get the algorithm type, our file function strip ( ) so there are
336	 * not in the return string! */
337	if (ldns_fget_keyword_data_l(fp, "Algorithm", ": ", d, "\n",
338				LDNS_MAX_LINELEN, line_nr) == -1) {
339		/* no alg information */
340                ldns_key_free(k);
341                LDNS_FREE(d);
342		return LDNS_STATUS_SYNTAX_ALG_ERR;
343	}
344
345	if (strncmp(d, "1 RSA", 2) == 0) {
346		alg = LDNS_SIGN_RSAMD5;
347	}
348	if (strncmp(d, "2 DH", 2) == 0) {
349		alg = (ldns_signing_algorithm)LDNS_DH;
350	}
351	if (strncmp(d, "3 DSA", 2) == 0) {
352		alg = LDNS_SIGN_DSA;
353	}
354	if (strncmp(d, "4 ECC", 2) == 0) {
355		alg = (ldns_signing_algorithm)LDNS_ECC;
356	}
357	if (strncmp(d, "5 RSASHA1", 2) == 0) {
358		alg = LDNS_SIGN_RSASHA1;
359	}
360	if (strncmp(d, "6 DSA", 2) == 0) {
361		alg = LDNS_SIGN_DSA_NSEC3;
362	}
363	if (strncmp(d, "7 RSASHA1", 2) == 0) {
364		alg = LDNS_SIGN_RSASHA1_NSEC3;
365	}
366
367	if (strncmp(d, "8 RSASHA256", 2) == 0) {
368#ifdef USE_SHA2
369		alg = LDNS_SIGN_RSASHA256;
370#else
371		fprintf(stderr, "Warning: SHA256 not compiled into this ");
372		fprintf(stderr, "version of ldns\n");
373#endif
374	}
375	if (strncmp(d, "10 RSASHA512", 3) == 0) {
376#ifdef USE_SHA2
377		alg = LDNS_SIGN_RSASHA512;
378#else
379		fprintf(stderr, "Warning: SHA512 not compiled into this ");
380		fprintf(stderr, "version of ldns\n");
381#endif
382	}
383	if (strncmp(d, "12 ECC-GOST", 3) == 0) {
384#ifdef USE_GOST
385		alg = LDNS_SIGN_ECC_GOST;
386#else
387		fprintf(stderr, "Warning: ECC-GOST not compiled into this ");
388		fprintf(stderr, "version of ldns, use --enable-gost\n");
389#endif
390	}
391	if (strncmp(d, "13 ECDSAP256SHA256", 3) == 0) {
392#ifdef USE_ECDSA
393                alg = LDNS_SIGN_ECDSAP256SHA256;
394#else
395		fprintf(stderr, "Warning: ECDSA not compiled into this ");
396		fprintf(stderr, "version of ldns, use --enable-ecdsa\n");
397#endif
398        }
399	if (strncmp(d, "14 ECDSAP384SHA384", 3) == 0) {
400#ifdef USE_ECDSA
401                alg = LDNS_SIGN_ECDSAP384SHA384;
402#else
403		fprintf(stderr, "Warning: ECDSA not compiled into this ");
404		fprintf(stderr, "version of ldns, use --enable-ecdsa\n");
405#endif
406        }
407	if (strncmp(d, "157 HMAC-MD5", 4) == 0) {
408		alg = LDNS_SIGN_HMACMD5;
409	}
410	if (strncmp(d, "158 HMAC-SHA1", 4) == 0) {
411		alg = LDNS_SIGN_HMACSHA1;
412	}
413	if (strncmp(d, "159 HMAC-SHA256", 4) == 0) {
414		alg = LDNS_SIGN_HMACSHA256;
415	}
416
417	LDNS_FREE(d);
418
419	switch(alg) {
420		case LDNS_SIGN_RSAMD5:
421		case LDNS_SIGN_RSASHA1:
422		case LDNS_SIGN_RSASHA1_NSEC3:
423#ifdef USE_SHA2
424		case LDNS_SIGN_RSASHA256:
425		case LDNS_SIGN_RSASHA512:
426#endif
427			ldns_key_set_algorithm(k, alg);
428#ifdef HAVE_SSL
429			rsa = ldns_key_new_frm_fp_rsa_l(fp, line_nr);
430			if (!rsa) {
431				ldns_key_free(k);
432				return LDNS_STATUS_ERR;
433			}
434			ldns_key_set_rsa_key(k, rsa);
435			RSA_free(rsa);
436#endif /* HAVE_SSL */
437			break;
438		case LDNS_SIGN_DSA:
439		case LDNS_SIGN_DSA_NSEC3:
440			ldns_key_set_algorithm(k, alg);
441#ifdef HAVE_SSL
442			dsa = ldns_key_new_frm_fp_dsa_l(fp, line_nr);
443			if (!dsa) {
444				ldns_key_free(k);
445				return LDNS_STATUS_ERR;
446			}
447			ldns_key_set_dsa_key(k, dsa);
448			DSA_free(dsa);
449#endif /* HAVE_SSL */
450			break;
451		case LDNS_SIGN_HMACMD5:
452		case LDNS_SIGN_HMACSHA1:
453		case LDNS_SIGN_HMACSHA256:
454			ldns_key_set_algorithm(k, alg);
455#ifdef HAVE_SSL
456			hmac = ldns_key_new_frm_fp_hmac_l(fp, line_nr, &hmac_size);
457			if (!hmac) {
458				ldns_key_free(k);
459				return LDNS_STATUS_ERR;
460			}
461			ldns_key_set_hmac_size(k, hmac_size);
462			ldns_key_set_hmac_key(k, hmac);
463#endif /* HAVE_SSL */
464			break;
465		case LDNS_SIGN_ECC_GOST:
466			ldns_key_set_algorithm(k, alg);
467#if defined(HAVE_SSL) && defined(USE_GOST)
468                        if(!ldns_key_EVP_load_gost_id()) {
469				ldns_key_free(k);
470                                return LDNS_STATUS_CRYPTO_ALGO_NOT_IMPL;
471                        }
472			ldns_key_set_evp_key(k,
473				ldns_key_new_frm_fp_gost_l(fp, line_nr));
474#ifndef S_SPLINT_S
475			if(!k->_key.key) {
476				ldns_key_free(k);
477				return LDNS_STATUS_ERR;
478			}
479#endif /* splint */
480#endif
481			break;
482#ifdef USE_ECDSA
483               case LDNS_SIGN_ECDSAP256SHA256:
484               case LDNS_SIGN_ECDSAP384SHA384:
485                        ldns_key_set_algorithm(k, alg);
486                        ldns_key_set_evp_key(k,
487                                ldns_key_new_frm_fp_ecdsa_l(fp, (ldns_algorithm)alg, line_nr));
488#ifndef S_SPLINT_S
489			if(!k->_key.key) {
490				ldns_key_free(k);
491				return LDNS_STATUS_ERR;
492			}
493#endif /* splint */
494			break;
495#endif
496		default:
497			ldns_key_free(k);
498			return LDNS_STATUS_SYNTAX_ALG_ERR;
499	}
500	key_rr = ldns_key2rr(k);
501	ldns_key_set_keytag(k, ldns_calc_keytag(key_rr));
502	ldns_rr_free(key_rr);
503
504	if (key) {
505		*key = k;
506		return LDNS_STATUS_OK;
507	}
508	return LDNS_STATUS_ERR;
509}
510
511#ifdef HAVE_SSL
512RSA *
513ldns_key_new_frm_fp_rsa(FILE *f)
514{
515	return ldns_key_new_frm_fp_rsa_l(f, NULL);
516}
517
518RSA *
519ldns_key_new_frm_fp_rsa_l(FILE *f, int *line_nr)
520{
521	/* we parse
522 	 * Modulus:
523 	 * PublicExponent:
524 	 * PrivateExponent:
525 	 * Prime1:
526 	 * Prime2:
527 	 * Exponent1:
528 	 * Exponent2:
529 	 * Coefficient:
530	 *
531	 * man 3 RSA:
532	 *
533	 * struct
534         *     {
535         *     BIGNUM *n;              // public modulus
536         *     BIGNUM *e;              // public exponent
537         *     BIGNUM *d;              // private exponent
538         *     BIGNUM *p;              // secret prime factor
539         *     BIGNUM *q;              // secret prime factor
540         *     BIGNUM *dmp1;           // d mod (p-1)
541         *     BIGNUM *dmq1;           // d mod (q-1)
542         *     BIGNUM *iqmp;           // q^-1 mod p
543         *     // ...
544	 *
545	 */
546	char *d;
547	RSA *rsa;
548	uint8_t *buf;
549	int i;
550
551	d = LDNS_XMALLOC(char, LDNS_MAX_LINELEN);
552	buf = LDNS_XMALLOC(uint8_t, LDNS_MAX_LINELEN);
553	rsa = RSA_new();
554	if (!d || !rsa || !buf) {
555                goto error;
556	}
557
558	/* I could use functions again, but that seems an overkill,
559	 * allthough this also looks tedious
560	 */
561
562	/* Modules, rsa->n */
563	if (ldns_fget_keyword_data_l(f, "Modulus", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
564		goto error;
565	}
566	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
567#ifndef S_SPLINT_S
568	rsa->n = BN_bin2bn((const char unsigned*)buf, i, NULL);
569	if (!rsa->n) {
570		goto error;
571	}
572
573	/* PublicExponent, rsa->e */
574	if (ldns_fget_keyword_data_l(f, "PublicExponent", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
575		goto error;
576	}
577	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
578	rsa->e = BN_bin2bn((const char unsigned*)buf, i, NULL);
579	if (!rsa->e) {
580		goto error;
581	}
582
583	/* PrivateExponent, rsa->d */
584	if (ldns_fget_keyword_data_l(f, "PrivateExponent", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
585		goto error;
586	}
587	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
588	rsa->d = BN_bin2bn((const char unsigned*)buf, i, NULL);
589	if (!rsa->d) {
590		goto error;
591	}
592
593	/* Prime1, rsa->p */
594	if (ldns_fget_keyword_data_l(f, "Prime1", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
595		goto error;
596	}
597	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
598	rsa->p = BN_bin2bn((const char unsigned*)buf, i, NULL);
599	if (!rsa->p) {
600		goto error;
601	}
602
603	/* Prime2, rsa->q */
604	if (ldns_fget_keyword_data_l(f, "Prime2", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
605		goto error;
606	}
607	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
608	rsa->q = BN_bin2bn((const char unsigned*)buf, i, NULL);
609	if (!rsa->q) {
610		goto error;
611	}
612
613	/* Exponent1, rsa->dmp1 */
614	if (ldns_fget_keyword_data_l(f, "Exponent1", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
615		goto error;
616	}
617	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
618	rsa->dmp1 = BN_bin2bn((const char unsigned*)buf, i, NULL);
619	if (!rsa->dmp1) {
620		goto error;
621	}
622
623	/* Exponent2, rsa->dmq1 */
624	if (ldns_fget_keyword_data_l(f, "Exponent2", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
625		goto error;
626	}
627	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
628	rsa->dmq1 = BN_bin2bn((const char unsigned*)buf, i, NULL);
629	if (!rsa->dmq1) {
630		goto error;
631	}
632
633	/* Coefficient, rsa->iqmp */
634	if (ldns_fget_keyword_data_l(f, "Coefficient", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
635		goto error;
636	}
637	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
638	rsa->iqmp = BN_bin2bn((const char unsigned*)buf, i, NULL);
639	if (!rsa->iqmp) {
640		goto error;
641	}
642#endif /* splint */
643
644	LDNS_FREE(buf);
645	LDNS_FREE(d);
646	return rsa;
647
648error:
649	RSA_free(rsa);
650	LDNS_FREE(d);
651	LDNS_FREE(buf);
652	return NULL;
653}
654
655DSA *
656ldns_key_new_frm_fp_dsa(FILE *f)
657{
658	return ldns_key_new_frm_fp_dsa_l(f, NULL);
659}
660
661DSA *
662ldns_key_new_frm_fp_dsa_l(FILE *f, ATTR_UNUSED(int *line_nr))
663{
664	int i;
665	char *d;
666	DSA *dsa;
667	uint8_t *buf;
668
669	d = LDNS_XMALLOC(char, LDNS_MAX_LINELEN);
670	buf = LDNS_XMALLOC(uint8_t, LDNS_MAX_LINELEN);
671	dsa = DSA_new();
672	if (!d || !dsa || !buf) {
673                goto error;
674	}
675
676	/* the line parser removes the () from the input... */
677
678	/* Prime, dsa->p */
679	if (ldns_fget_keyword_data_l(f, "Primep", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
680		goto error;
681	}
682	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
683#ifndef S_SPLINT_S
684	dsa->p = BN_bin2bn((const char unsigned*)buf, i, NULL);
685	if (!dsa->p) {
686		goto error;
687	}
688
689	/* Subprime, dsa->q */
690	if (ldns_fget_keyword_data_l(f, "Subprimeq", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
691		goto error;
692	}
693	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
694	dsa->q = BN_bin2bn((const char unsigned*)buf, i, NULL);
695	if (!dsa->q) {
696		goto error;
697	}
698
699	/* Base, dsa->g */
700	if (ldns_fget_keyword_data_l(f, "Baseg", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
701		goto error;
702	}
703	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
704	dsa->g = BN_bin2bn((const char unsigned*)buf, i, NULL);
705	if (!dsa->g) {
706		goto error;
707	}
708
709	/* Private key, dsa->priv_key */
710	if (ldns_fget_keyword_data_l(f, "Private_valuex", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
711		goto error;
712	}
713	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
714	dsa->priv_key = BN_bin2bn((const char unsigned*)buf, i, NULL);
715	if (!dsa->priv_key) {
716		goto error;
717	}
718
719	/* Public key, dsa->priv_key */
720	if (ldns_fget_keyword_data_l(f, "Public_valuey", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
721		goto error;
722	}
723	i = ldns_b64_pton((const char*)d, buf, ldns_b64_ntop_calculate_size(strlen(d)));
724	dsa->pub_key = BN_bin2bn((const char unsigned*)buf, i, NULL);
725	if (!dsa->pub_key) {
726		goto error;
727	}
728#endif /* splint */
729
730	LDNS_FREE(buf);
731	LDNS_FREE(d);
732
733	return dsa;
734
735error:
736	LDNS_FREE(d);
737	LDNS_FREE(buf);
738        DSA_free(dsa);
739	return NULL;
740}
741
742unsigned char *
743ldns_key_new_frm_fp_hmac(FILE *f, size_t *hmac_size)
744{
745	return ldns_key_new_frm_fp_hmac_l(f, NULL, hmac_size);
746}
747
748unsigned char *
749ldns_key_new_frm_fp_hmac_l( FILE *f
750			  , ATTR_UNUSED(int *line_nr)
751			  , size_t *hmac_size
752			  )
753{
754	size_t i;
755	char *d;
756	unsigned char *buf;
757
758	d = LDNS_XMALLOC(char, LDNS_MAX_LINELEN);
759	buf = LDNS_XMALLOC(unsigned char, LDNS_MAX_LINELEN);
760        if(!d || !buf) {
761                goto error;
762        }
763
764	if (ldns_fget_keyword_data_l(f, "Key", ": ", d, "\n", LDNS_MAX_LINELEN, line_nr) == -1) {
765		goto error;
766	}
767	i = (size_t) ldns_b64_pton((const char*)d,
768	                           buf,
769	                           ldns_b64_ntop_calculate_size(strlen(d)));
770
771	*hmac_size = i;
772	return buf;
773
774	error:
775	LDNS_FREE(d);
776	LDNS_FREE(buf);
777	*hmac_size = 0;
778	return NULL;
779}
780#endif /* HAVE_SSL */
781
782#ifdef USE_GOST
783static EVP_PKEY*
784ldns_gen_gost_key(void)
785{
786	EVP_PKEY_CTX* ctx;
787	EVP_PKEY* p = NULL;
788	int gost_id = ldns_key_EVP_load_gost_id();
789	if(!gost_id)
790		return NULL;
791	ctx = EVP_PKEY_CTX_new_id(gost_id, NULL);
792	if(!ctx) {
793		/* the id should be available now */
794		return NULL;
795	}
796	if(EVP_PKEY_CTX_ctrl_str(ctx, "paramset", "A") <= 0) {
797		/* cannot set paramset */
798		EVP_PKEY_CTX_free(ctx);
799		return NULL;
800	}
801
802	if(EVP_PKEY_keygen_init(ctx) <= 0) {
803		EVP_PKEY_CTX_free(ctx);
804		return NULL;
805	}
806	if(EVP_PKEY_keygen(ctx, &p) <= 0) {
807		EVP_PKEY_free(p);
808		EVP_PKEY_CTX_free(ctx);
809		return NULL;
810	}
811	EVP_PKEY_CTX_free(ctx);
812	return p;
813}
814#endif
815
816ldns_key *
817ldns_key_new_frm_algorithm(ldns_signing_algorithm alg, uint16_t size)
818{
819	ldns_key *k;
820#ifdef HAVE_SSL
821	DSA *d;
822	RSA *r;
823#  ifdef USE_ECDSA
824        EC_KEY *ec = NULL;
825#  endif
826#else
827	int i;
828	uint16_t offset = 0;
829#endif
830	unsigned char *hmac;
831
832	k = ldns_key_new();
833	if (!k) {
834		return NULL;
835	}
836	switch(alg) {
837		case LDNS_SIGN_RSAMD5:
838		case LDNS_SIGN_RSASHA1:
839		case LDNS_SIGN_RSASHA1_NSEC3:
840		case LDNS_SIGN_RSASHA256:
841		case LDNS_SIGN_RSASHA512:
842#ifdef HAVE_SSL
843			r = RSA_generate_key((int)size, RSA_F4, NULL, NULL);
844                        if(!r) {
845				ldns_key_free(k);
846				return NULL;
847			}
848			if (RSA_check_key(r) != 1) {
849				ldns_key_free(k);
850				return NULL;
851			}
852			ldns_key_set_rsa_key(k, r);
853#endif /* HAVE_SSL */
854			break;
855		case LDNS_SIGN_DSA:
856		case LDNS_SIGN_DSA_NSEC3:
857#ifdef HAVE_SSL
858			d = DSA_generate_parameters((int)size, NULL, 0, NULL, NULL, NULL, NULL);
859			if (!d) {
860				ldns_key_free(k);
861				return NULL;
862			}
863			if (DSA_generate_key(d) != 1) {
864				ldns_key_free(k);
865				return NULL;
866			}
867			ldns_key_set_dsa_key(k, d);
868#endif /* HAVE_SSL */
869			break;
870		case LDNS_SIGN_HMACMD5:
871		case LDNS_SIGN_HMACSHA1:
872		case LDNS_SIGN_HMACSHA256:
873#ifdef HAVE_SSL
874#ifndef S_SPLINT_S
875			k->_key.key = NULL;
876#endif /* splint */
877#endif /* HAVE_SSL */
878			size = size / 8;
879			ldns_key_set_hmac_size(k, size);
880
881			hmac = LDNS_XMALLOC(unsigned char, size);
882                        if(!hmac) {
883				ldns_key_free(k);
884				return NULL;
885                        }
886#ifdef HAVE_SSL
887			if (RAND_bytes(hmac, (int) size) != 1) {
888				LDNS_FREE(hmac);
889				ldns_key_free(k);
890				return NULL;
891			}
892#else
893			while (offset + sizeof(i) < size) {
894			  i = random();
895			  memcpy(&hmac[offset], &i, sizeof(i));
896			  offset += sizeof(i);
897			}
898			if (offset < size) {
899			  i = random();
900			  memcpy(&hmac[offset], &i, size - offset);
901			}
902#endif /* HAVE_SSL */
903			ldns_key_set_hmac_key(k, hmac);
904
905			ldns_key_set_flags(k, 0);
906			break;
907		case LDNS_SIGN_ECC_GOST:
908#if defined(HAVE_SSL) && defined(USE_GOST)
909			ldns_key_set_evp_key(k, ldns_gen_gost_key());
910#ifndef S_SPLINT_S
911                        if(!k->_key.key) {
912                                ldns_key_free(k);
913                                return NULL;
914                        }
915#endif /* splint */
916#else
917			ldns_key_free(k);
918			return NULL;
919#endif /* HAVE_SSL and USE_GOST */
920                        break;
921                case LDNS_SIGN_ECDSAP256SHA256:
922                case LDNS_SIGN_ECDSAP384SHA384:
923#ifdef USE_ECDSA
924                        if(alg == LDNS_SIGN_ECDSAP256SHA256)
925                                ec = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
926                        else if(alg == LDNS_SIGN_ECDSAP384SHA384)
927                                ec = EC_KEY_new_by_curve_name(NID_secp384r1);
928                        if(!ec) {
929                                ldns_key_free(k);
930                                return NULL;
931                        }
932                        if(!EC_KEY_generate_key(ec)) {
933                                ldns_key_free(k);
934                                EC_KEY_free(ec);
935                                return NULL;
936                        }
937#ifndef S_SPLINT_S
938                        k->_key.key = EVP_PKEY_new();
939                        if(!k->_key.key) {
940                                ldns_key_free(k);
941                                EC_KEY_free(ec);
942                                return NULL;
943                        }
944                        if (!EVP_PKEY_assign_EC_KEY(k->_key.key, ec)) {
945                                ldns_key_free(k);
946                                EC_KEY_free(ec);
947                                return NULL;
948			}
949#endif /* splint */
950#else
951			ldns_key_free(k);
952			return NULL;
953#endif /* ECDSA */
954			break;
955	}
956	ldns_key_set_algorithm(k, alg);
957	return k;
958}
959
960void
961ldns_key_print(FILE *output, const ldns_key *k)
962{
963	char *str = ldns_key2str(k);
964	if (str) {
965                fprintf(output, "%s", str);
966        } else {
967                fprintf(output, "Unable to convert private key to string\n");
968        }
969        LDNS_FREE(str);
970}
971
972
973void
974ldns_key_set_algorithm(ldns_key *k, ldns_signing_algorithm l)
975{
976	k->_alg = l;
977}
978
979void
980ldns_key_set_flags(ldns_key *k, uint16_t f)
981{
982	k->_extra.dnssec.flags = f;
983}
984
985#ifdef HAVE_SSL
986#ifndef S_SPLINT_S
987void
988ldns_key_set_evp_key(ldns_key *k, EVP_PKEY *e)
989{
990	k->_key.key = e;
991}
992
993void
994ldns_key_set_rsa_key(ldns_key *k, RSA *r)
995{
996	EVP_PKEY *key = EVP_PKEY_new();
997	EVP_PKEY_set1_RSA(key, r);
998	k->_key.key = key;
999}
1000
1001void
1002ldns_key_set_dsa_key(ldns_key *k, DSA *d)
1003{
1004	EVP_PKEY *key = EVP_PKEY_new();
1005	EVP_PKEY_set1_DSA(key, d);
1006	k->_key.key  = key;
1007}
1008#endif /* splint */
1009#endif /* HAVE_SSL */
1010
1011void
1012ldns_key_set_hmac_key(ldns_key *k, unsigned char *hmac)
1013{
1014	k->_key.hmac.key = hmac;
1015}
1016
1017void
1018ldns_key_set_hmac_size(ldns_key *k, size_t hmac_size)
1019{
1020	k->_key.hmac.size = hmac_size;
1021}
1022
1023void
1024ldns_key_set_external_key(ldns_key *k, void *external_key)
1025{
1026	k->_key.external_key = external_key;
1027}
1028
1029void
1030ldns_key_set_origttl(ldns_key *k, uint32_t t)
1031{
1032	k->_extra.dnssec.orig_ttl = t;
1033}
1034
1035void
1036ldns_key_set_inception(ldns_key *k, uint32_t i)
1037{
1038	k->_extra.dnssec.inception = i;
1039}
1040
1041void
1042ldns_key_set_expiration(ldns_key *k, uint32_t e)
1043{
1044	k->_extra.dnssec.expiration = e;
1045}
1046
1047void
1048ldns_key_set_pubkey_owner(ldns_key *k, ldns_rdf *r)
1049{
1050	k->_pubkey_owner = r;
1051}
1052
1053void
1054ldns_key_set_keytag(ldns_key *k, uint16_t tag)
1055{
1056	k->_extra.dnssec.keytag = tag;
1057}
1058
1059/* read */
1060size_t
1061ldns_key_list_key_count(const ldns_key_list *key_list)
1062{
1063	        return key_list->_key_count;
1064}
1065
1066ldns_key *
1067ldns_key_list_key(const ldns_key_list *key, size_t nr)
1068{
1069	if (nr < ldns_key_list_key_count(key)) {
1070		return key->_keys[nr];
1071	} else {
1072		return NULL;
1073	}
1074}
1075
1076ldns_signing_algorithm
1077ldns_key_algorithm(const ldns_key *k)
1078{
1079	return k->_alg;
1080}
1081
1082void
1083ldns_key_set_use(ldns_key *k, bool v)
1084{
1085	if (k) {
1086		k->_use = v;
1087	}
1088}
1089
1090bool
1091ldns_key_use(const ldns_key *k)
1092{
1093	if (k) {
1094		return k->_use;
1095	}
1096	return false;
1097}
1098
1099#ifdef HAVE_SSL
1100#ifndef S_SPLINT_S
1101EVP_PKEY *
1102ldns_key_evp_key(const ldns_key *k)
1103{
1104	return k->_key.key;
1105}
1106
1107RSA *
1108ldns_key_rsa_key(const ldns_key *k)
1109{
1110	if (k->_key.key) {
1111		return EVP_PKEY_get1_RSA(k->_key.key);
1112	} else {
1113		return NULL;
1114	}
1115}
1116
1117DSA *
1118ldns_key_dsa_key(const ldns_key *k)
1119{
1120	if (k->_key.key) {
1121		return EVP_PKEY_get1_DSA(k->_key.key);
1122	} else {
1123		return NULL;
1124	}
1125}
1126#endif /* splint */
1127#endif /* HAVE_SSL */
1128
1129unsigned char *
1130ldns_key_hmac_key(const ldns_key *k)
1131{
1132	if (k->_key.hmac.key) {
1133		return k->_key.hmac.key;
1134	} else {
1135		return NULL;
1136	}
1137}
1138
1139size_t
1140ldns_key_hmac_size(const ldns_key *k)
1141{
1142	if (k->_key.hmac.size) {
1143		return k->_key.hmac.size;
1144	} else {
1145		return 0;
1146	}
1147}
1148
1149void *
1150ldns_key_external_key(const ldns_key *k)
1151{
1152	return k->_key.external_key;
1153}
1154
1155uint32_t
1156ldns_key_origttl(const ldns_key *k)
1157{
1158	return k->_extra.dnssec.orig_ttl;
1159}
1160
1161uint16_t
1162ldns_key_flags(const ldns_key *k)
1163{
1164	return k->_extra.dnssec.flags;
1165}
1166
1167uint32_t
1168ldns_key_inception(const ldns_key *k)
1169{
1170	return k->_extra.dnssec.inception;
1171}
1172
1173uint32_t
1174ldns_key_expiration(const ldns_key *k)
1175{
1176	return k->_extra.dnssec.expiration;
1177}
1178
1179uint16_t
1180ldns_key_keytag(const ldns_key *k)
1181{
1182	return k->_extra.dnssec.keytag;
1183}
1184
1185ldns_rdf *
1186ldns_key_pubkey_owner(const ldns_key *k)
1187{
1188	return k->_pubkey_owner;
1189}
1190
1191/* write */
1192void
1193ldns_key_list_set_use(ldns_key_list *keys, bool v)
1194{
1195	size_t i;
1196
1197	for (i = 0; i < ldns_key_list_key_count(keys); i++) {
1198		ldns_key_set_use(ldns_key_list_key(keys, i), v);
1199	}
1200}
1201
1202void
1203ldns_key_list_set_key_count(ldns_key_list *key, size_t count)
1204{
1205	        key->_key_count = count;
1206}
1207
1208bool
1209ldns_key_list_push_key(ldns_key_list *key_list, ldns_key *key)
1210{
1211        size_t key_count;
1212        ldns_key **keys;
1213
1214        key_count = ldns_key_list_key_count(key_list);
1215
1216        /* grow the array */
1217        keys = LDNS_XREALLOC(
1218                key_list->_keys, ldns_key *, key_count + 1);
1219        if (!keys) {
1220                return false;
1221        }
1222
1223        /* add the new member */
1224        key_list->_keys = keys;
1225        key_list->_keys[key_count] = key;
1226
1227        ldns_key_list_set_key_count(key_list, key_count + 1);
1228        return true;
1229}
1230
1231ldns_key *
1232ldns_key_list_pop_key(ldns_key_list *key_list)
1233{
1234        size_t key_count;
1235        ldns_key** a;
1236        ldns_key *pop;
1237
1238	if (!key_list) {
1239		return NULL;
1240	}
1241
1242        key_count = ldns_key_list_key_count(key_list);
1243        if (key_count == 0) {
1244                return NULL;
1245        }
1246
1247        pop = ldns_key_list_key(key_list, key_count);
1248
1249        /* shrink the array */
1250        a = LDNS_XREALLOC(key_list->_keys, ldns_key *, key_count - 1);
1251        if(a) {
1252                key_list->_keys = a;
1253        }
1254
1255        ldns_key_list_set_key_count(key_list, key_count - 1);
1256
1257        return pop;
1258}
1259
1260#ifdef HAVE_SSL
1261#ifndef S_SPLINT_S
1262/* data pointer must be large enough (LDNS_MAX_KEYLEN) */
1263static bool
1264ldns_key_rsa2bin(unsigned char *data, RSA *k, uint16_t *size)
1265{
1266	int i,j;
1267
1268	if (!k) {
1269		return false;
1270	}
1271
1272	if (BN_num_bytes(k->e) <= 256) {
1273		/* normally only this path is executed (small factors are
1274		 * more common
1275		 */
1276		data[0] = (unsigned char) BN_num_bytes(k->e);
1277		i = BN_bn2bin(k->e, data + 1);
1278		j = BN_bn2bin(k->n, data + i + 1);
1279		*size = (uint16_t) i + j;
1280	} else if (BN_num_bytes(k->e) <= 65536) {
1281		data[0] = 0;
1282		/* BN_bn2bin does bigendian, _uint16 also */
1283		ldns_write_uint16(data + 1, (uint16_t) BN_num_bytes(k->e));
1284
1285		BN_bn2bin(k->e, data + 3);
1286		BN_bn2bin(k->n, data + 4 + BN_num_bytes(k->e));
1287		*size = (uint16_t) BN_num_bytes(k->n) + 6;
1288	} else {
1289		return false;
1290	}
1291	return true;
1292}
1293
1294/* data pointer must be large enough (LDNS_MAX_KEYLEN) */
1295static bool
1296ldns_key_dsa2bin(unsigned char *data, DSA *k, uint16_t *size)
1297{
1298	uint8_t T;
1299
1300	if (!k) {
1301		return false;
1302	}
1303
1304	/* See RFC2536 */
1305	*size = (uint16_t)BN_num_bytes(k->g);
1306	T = (*size - 64) / 8;
1307	memcpy(data, &T, 1);
1308
1309	if (T > 8) {
1310		fprintf(stderr, "DSA key with T > 8 (ie. > 1024 bits)");
1311		fprintf(stderr, " not implemented\n");
1312		return false;
1313	}
1314
1315	/* size = 64 + (T * 8); */
1316	data[0] = (unsigned char)T;
1317	BN_bn2bin(k->q, data + 1 ); 		/* 20 octects */
1318	BN_bn2bin(k->p, data + 21 ); 		/* offset octects */
1319	BN_bn2bin(k->g, data + 21 + *size); 	/* offset octets */
1320	BN_bn2bin(k->pub_key, data + 21 + *size + *size); /* offset octets */
1321	*size = 21 + (*size * 3);
1322	return true;
1323}
1324
1325#ifdef USE_GOST
1326static bool
1327ldns_key_gost2bin(unsigned char* data, EVP_PKEY* k, uint16_t* size)
1328{
1329	int i;
1330	unsigned char* pp = NULL;
1331	if(i2d_PUBKEY(k, &pp) != 37 + 64) {
1332		/* expect 37 byte(ASN header) and 64 byte(X and Y) */
1333		CRYPTO_free(pp);
1334		return false;
1335	}
1336	/* omit ASN header */
1337	for(i=0; i<64; i++)
1338		data[i] = pp[i+37];
1339	CRYPTO_free(pp);
1340	*size = 64;
1341	return true;
1342}
1343#endif /* USE_GOST */
1344#endif /* splint */
1345#endif /* HAVE_SSL */
1346
1347ldns_rr *
1348ldns_key2rr(const ldns_key *k)
1349{
1350	/* this function will convert a the keydata contained in
1351	 * rsa/dsa pointers to a DNSKEY rr. It will fill in as
1352	 * much as it can, but it does not know about key-flags
1353	 * for instance
1354	 */
1355	ldns_rr *pubkey;
1356	ldns_rdf *keybin;
1357	unsigned char *bin = NULL;
1358	uint16_t size = 0;
1359#ifdef HAVE_SSL
1360	RSA *rsa = NULL;
1361	DSA *dsa = NULL;
1362#endif /* HAVE_SSL */
1363#ifdef USE_ECDSA
1364        EC_KEY* ec;
1365#endif
1366	int internal_data = 0;
1367
1368	pubkey = ldns_rr_new();
1369	if (!k) {
1370		return NULL;
1371	}
1372
1373	switch (ldns_key_algorithm(k)) {
1374	case LDNS_SIGN_HMACMD5:
1375	case LDNS_SIGN_HMACSHA1:
1376	case LDNS_SIGN_HMACSHA256:
1377		ldns_rr_set_type(pubkey, LDNS_RR_TYPE_KEY);
1378        	break;
1379	default:
1380		ldns_rr_set_type(pubkey, LDNS_RR_TYPE_DNSKEY);
1381		break;
1382        }
1383	/* zero-th rdf - flags */
1384	ldns_rr_push_rdf(pubkey,
1385			ldns_native2rdf_int16(LDNS_RDF_TYPE_INT16,
1386				ldns_key_flags(k)));
1387	/* first - proto */
1388	ldns_rr_push_rdf(pubkey,
1389			ldns_native2rdf_int8(LDNS_RDF_TYPE_INT8, LDNS_DNSSEC_KEYPROTO));
1390
1391	if (ldns_key_pubkey_owner(k)) {
1392		ldns_rr_set_owner(pubkey, ldns_rdf_clone(ldns_key_pubkey_owner(k)));
1393	}
1394
1395	/* third - da algorithm */
1396	switch(ldns_key_algorithm(k)) {
1397		case LDNS_SIGN_RSAMD5:
1398		case LDNS_SIGN_RSASHA1:
1399		case LDNS_SIGN_RSASHA1_NSEC3:
1400		case LDNS_SIGN_RSASHA256:
1401		case LDNS_SIGN_RSASHA512:
1402			ldns_rr_push_rdf(pubkey,
1403						  ldns_native2rdf_int8(LDNS_RDF_TYPE_ALG, ldns_key_algorithm(k)));
1404#ifdef HAVE_SSL
1405			rsa =  ldns_key_rsa_key(k);
1406			if (rsa) {
1407				bin = LDNS_XMALLOC(unsigned char, LDNS_MAX_KEYLEN);
1408				if (!bin) {
1409                                        ldns_rr_free(pubkey);
1410					return NULL;
1411				}
1412				if (!ldns_key_rsa2bin(bin, rsa, &size)) {
1413		                        LDNS_FREE(bin);
1414                                        ldns_rr_free(pubkey);
1415					return NULL;
1416				}
1417				RSA_free(rsa);
1418				internal_data = 1;
1419			}
1420#endif
1421			size++;
1422			break;
1423		case LDNS_SIGN_DSA:
1424			ldns_rr_push_rdf(pubkey,
1425					ldns_native2rdf_int8(LDNS_RDF_TYPE_ALG, LDNS_DSA));
1426#ifdef HAVE_SSL
1427			dsa = ldns_key_dsa_key(k);
1428			if (dsa) {
1429				bin = LDNS_XMALLOC(unsigned char, LDNS_MAX_KEYLEN);
1430				if (!bin) {
1431                                        ldns_rr_free(pubkey);
1432					return NULL;
1433				}
1434				if (!ldns_key_dsa2bin(bin, dsa, &size)) {
1435		                        LDNS_FREE(bin);
1436                                        ldns_rr_free(pubkey);
1437					return NULL;
1438				}
1439				DSA_free(dsa);
1440				internal_data = 1;
1441			}
1442#endif /* HAVE_SSL */
1443			break;
1444		case LDNS_SIGN_DSA_NSEC3:
1445			ldns_rr_push_rdf(pubkey,
1446					ldns_native2rdf_int8(LDNS_RDF_TYPE_ALG, LDNS_DSA_NSEC3));
1447#ifdef HAVE_SSL
1448			dsa = ldns_key_dsa_key(k);
1449			if (dsa) {
1450				bin = LDNS_XMALLOC(unsigned char, LDNS_MAX_KEYLEN);
1451				if (!bin) {
1452                                        ldns_rr_free(pubkey);
1453					return NULL;
1454				}
1455				if (!ldns_key_dsa2bin(bin, dsa, &size)) {
1456		                        LDNS_FREE(bin);
1457                                        ldns_rr_free(pubkey);
1458					return NULL;
1459				}
1460				DSA_free(dsa);
1461				internal_data = 1;
1462			}
1463#endif /* HAVE_SSL */
1464			break;
1465		case LDNS_SIGN_ECC_GOST:
1466			ldns_rr_push_rdf(pubkey, ldns_native2rdf_int8(
1467				LDNS_RDF_TYPE_ALG, ldns_key_algorithm(k)));
1468#if defined(HAVE_SSL) && defined(USE_GOST)
1469			bin = LDNS_XMALLOC(unsigned char, LDNS_MAX_KEYLEN);
1470			if (!bin) {
1471                                ldns_rr_free(pubkey);
1472				return NULL;
1473                        }
1474#ifndef S_SPLINT_S
1475			if (!ldns_key_gost2bin(bin, k->_key.key, &size)) {
1476		                LDNS_FREE(bin);
1477                                ldns_rr_free(pubkey);
1478				return NULL;
1479			}
1480#endif /* splint */
1481			internal_data = 1;
1482#else
1483                        ldns_rr_free(pubkey);
1484			return NULL;
1485#endif /* HAVE_SSL and USE_GOST */
1486			break;
1487                case LDNS_SIGN_ECDSAP256SHA256:
1488                case LDNS_SIGN_ECDSAP384SHA384:
1489#ifdef USE_ECDSA
1490			ldns_rr_push_rdf(pubkey, ldns_native2rdf_int8(
1491				LDNS_RDF_TYPE_ALG, ldns_key_algorithm(k)));
1492                        bin = NULL;
1493#ifndef S_SPLINT_S
1494                        ec = EVP_PKEY_get1_EC_KEY(k->_key.key);
1495#endif
1496                        EC_KEY_set_conv_form(ec, POINT_CONVERSION_UNCOMPRESSED);
1497                        size = (uint16_t)i2o_ECPublicKey(ec, NULL);
1498                        if(!i2o_ECPublicKey(ec, &bin)) {
1499                                EC_KEY_free(ec);
1500                                ldns_rr_free(pubkey);
1501                                return NULL;
1502                        }
1503			if(size > 1) {
1504				/* move back one byte to shave off the 0x02
1505				 * 'uncompressed' indicator that openssl made
1506				 * Actually its 0x04 (from implementation).
1507				 */
1508				assert(bin[0] == POINT_CONVERSION_UNCOMPRESSED);
1509				size -= 1;
1510				memmove(bin, bin+1, size);
1511			}
1512                        /* down the reference count for ec, its still assigned
1513                         * to the pkey */
1514                        EC_KEY_free(ec);
1515			internal_data = 1;
1516#else
1517                        ldns_rr_free(pubkey);
1518			return NULL;
1519#endif /* ECDSA */
1520                        break;
1521		case LDNS_SIGN_HMACMD5:
1522		case LDNS_SIGN_HMACSHA1:
1523		case LDNS_SIGN_HMACSHA256:
1524			bin = LDNS_XMALLOC(unsigned char, ldns_key_hmac_size(k));
1525			if (!bin) {
1526                                ldns_rr_free(pubkey);
1527				return NULL;
1528			}
1529			ldns_rr_push_rdf(pubkey,
1530			                 ldns_native2rdf_int8(LDNS_RDF_TYPE_ALG,
1531			                 ldns_key_algorithm(k)));
1532			size = ldns_key_hmac_size(k);
1533			memcpy(bin, ldns_key_hmac_key(k), size);
1534			internal_data = 1;
1535			break;
1536	}
1537	/* fourth the key bin material */
1538	if (internal_data) {
1539		keybin = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_B64, size, bin);
1540		LDNS_FREE(bin);
1541		ldns_rr_push_rdf(pubkey, keybin);
1542	}
1543	return pubkey;
1544}
1545
1546void
1547ldns_key_free(ldns_key *key)
1548{
1549	LDNS_FREE(key);
1550}
1551
1552void
1553ldns_key_deep_free(ldns_key *key)
1554{
1555	unsigned char* hmac;
1556	if (ldns_key_pubkey_owner(key)) {
1557		ldns_rdf_deep_free(ldns_key_pubkey_owner(key));
1558	}
1559#ifdef HAVE_SSL
1560	if (ldns_key_evp_key(key)) {
1561		EVP_PKEY_free(ldns_key_evp_key(key));
1562	}
1563#endif /* HAVE_SSL */
1564	if (ldns_key_hmac_key(key)) {
1565		hmac = ldns_key_hmac_key(key);
1566		LDNS_FREE(hmac);
1567	}
1568	LDNS_FREE(key);
1569}
1570
1571void
1572ldns_key_list_free(ldns_key_list *key_list)
1573{
1574	size_t i;
1575	for (i = 0; i < ldns_key_list_key_count(key_list); i++) {
1576		ldns_key_deep_free(ldns_key_list_key(key_list, i));
1577	}
1578	LDNS_FREE(key_list->_keys);
1579	LDNS_FREE(key_list);
1580}
1581
1582ldns_rr *
1583ldns_read_anchor_file(const char *filename)
1584{
1585	FILE *fp;
1586	/*char line[LDNS_MAX_PACKETLEN];*/
1587	char *line = LDNS_XMALLOC(char, LDNS_MAX_PACKETLEN);
1588	int c;
1589	size_t i = 0;
1590	ldns_rr *r;
1591	ldns_status status;
1592        if(!line) {
1593                return NULL;
1594        }
1595
1596	fp = fopen(filename, "r");
1597	if (!fp) {
1598		fprintf(stderr, "Unable to open %s: %s\n", filename, strerror(errno));
1599		LDNS_FREE(line);
1600		return NULL;
1601	}
1602
1603	while ((c = fgetc(fp)) && i+1 < LDNS_MAX_PACKETLEN && c != EOF) {
1604		line[i] = c;
1605		i++;
1606	}
1607	line[i] = '\0';
1608
1609	fclose(fp);
1610
1611	if (i <= 0) {
1612		fprintf(stderr, "nothing read from %s", filename);
1613		LDNS_FREE(line);
1614		return NULL;
1615	} else {
1616		status = ldns_rr_new_frm_str(&r, line, 0, NULL, NULL);
1617		if (status == LDNS_STATUS_OK && (ldns_rr_get_type(r) == LDNS_RR_TYPE_DNSKEY || ldns_rr_get_type(r) == LDNS_RR_TYPE_DS)) {
1618			LDNS_FREE(line);
1619			return r;
1620		} else {
1621			fprintf(stderr, "Error creating DNSKEY or DS rr from %s: %s\n", filename, ldns_get_errorstr_by_id(status));
1622			LDNS_FREE(line);
1623			return NULL;
1624		}
1625	}
1626}
1627
1628char *
1629ldns_key_get_file_base_name(ldns_key *key)
1630{
1631	ldns_buffer *buffer;
1632	char *file_base_name;
1633
1634	buffer = ldns_buffer_new(255);
1635	ldns_buffer_printf(buffer, "K");
1636	(void)ldns_rdf2buffer_str_dname(buffer, ldns_key_pubkey_owner(key));
1637	ldns_buffer_printf(buffer,
1638	                   "+%03u+%05u",
1639			   ldns_key_algorithm(key),
1640			   ldns_key_keytag(key));
1641	file_base_name = strdup(ldns_buffer_export(buffer));
1642	ldns_buffer_free(buffer);
1643	return file_base_name;
1644}
1645
1646int ldns_key_algo_supported(int algo)
1647{
1648	ldns_lookup_table *lt = ldns_signing_algorithms;
1649	while(lt->name) {
1650		if(lt->id == algo)
1651			return 1;
1652		lt++;
1653	}
1654	return 0;
1655}
1656
1657ldns_signing_algorithm ldns_get_signing_algorithm_by_name(const char* name)
1658{
1659        /* list of (signing algorithm id, alias_name) */
1660        ldns_lookup_table aliases[] = {
1661                /* from bind dnssec-keygen */
1662                {LDNS_SIGN_HMACMD5, "HMAC-MD5"},
1663                {LDNS_SIGN_DSA_NSEC3, "NSEC3DSA"},
1664                {LDNS_SIGN_RSASHA1_NSEC3, "NSEC3RSASHA1"},
1665                /* old ldns usage, now RFC names */
1666                {LDNS_SIGN_DSA_NSEC3, "DSA_NSEC3" },
1667                {LDNS_SIGN_RSASHA1_NSEC3, "RSASHA1_NSEC3" },
1668#ifdef USE_GOST
1669                {LDNS_SIGN_ECC_GOST, "GOST"},
1670#endif
1671                /* compat with possible output */
1672                {LDNS_DH, "DH"},
1673                {LDNS_ECC, "ECC"},
1674                {LDNS_INDIRECT, "INDIRECT"},
1675                {LDNS_PRIVATEDNS, "PRIVATEDNS"},
1676                {LDNS_PRIVATEOID, "PRIVATEOID"},
1677                {0, NULL}};
1678        ldns_lookup_table* lt = ldns_signing_algorithms;
1679        while(lt->name) {
1680                if(strcasecmp(lt->name, name) == 0)
1681                        return lt->id;
1682                lt++;
1683        }
1684        lt = aliases;
1685        while(lt->name) {
1686                if(strcasecmp(lt->name, name) == 0)
1687                        return lt->id;
1688                lt++;
1689        }
1690        if(atoi(name) != 0)
1691                return atoi(name);
1692        return 0;
1693}
1694