]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - contrib/bind9/lib/dns/dst_api.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / contrib / bind9 / lib / dns / dst_api.c
1 /*
2  * Portions Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
3  * Portions Copyright (C) 1999-2003  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC AND NETWORK ASSOCIATES DISCLAIMS
10  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
11  * WARRANTIES OF MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE
12  * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
15  * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  *
17  * Portions Copyright (C) 1995-2000 by Network Associates, Inc.
18  *
19  * Permission to use, copy, modify, and/or distribute this software for any
20  * purpose with or without fee is hereby granted, provided that the above
21  * copyright notice and this permission notice appear in all copies.
22  *
23  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC AND NETWORK ASSOCIATES DISCLAIMS
24  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
25  * WARRANTIES OF MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE
26  * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
27  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
28  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
29  * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
30  */
31
32 /*
33  * Principal Author: Brian Wellington
34  * $Id$
35  */
36
37 /*! \file */
38
39 #include <config.h>
40
41 #include <stdlib.h>
42 #include <time.h>
43
44 #include <isc/buffer.h>
45 #include <isc/dir.h>
46 #include <isc/entropy.h>
47 #include <isc/fsaccess.h>
48 #include <isc/hmacsha.h>
49 #include <isc/lex.h>
50 #include <isc/mem.h>
51 #include <isc/once.h>
52 #include <isc/platform.h>
53 #include <isc/print.h>
54 #include <isc/refcount.h>
55 #include <isc/random.h>
56 #include <isc/string.h>
57 #include <isc/time.h>
58 #include <isc/util.h>
59 #include <isc/file.h>
60
61 #include <dns/fixedname.h>
62 #include <dns/keyvalues.h>
63 #include <dns/name.h>
64 #include <dns/rdata.h>
65 #include <dns/rdataclass.h>
66 #include <dns/ttl.h>
67 #include <dns/types.h>
68
69 #include <dst/result.h>
70
71 #include "dst_internal.h"
72
73 #define DST_AS_STR(t) ((t).value.as_textregion.base)
74
75 static dst_func_t *dst_t_func[DST_MAX_ALGS];
76 #ifdef BIND9
77 static isc_entropy_t *dst_entropy_pool = NULL;
78 #endif
79 static unsigned int dst_entropy_flags = 0;
80 static isc_boolean_t dst_initialized = ISC_FALSE;
81
82 void gss_log(int level, const char *fmt, ...) ISC_FORMAT_PRINTF(2, 3);
83
84 isc_mem_t *dst__memory_pool = NULL;
85
86 /*
87  * Static functions.
88  */
89 static dst_key_t *      get_key_struct(dns_name_t *name,
90                                        unsigned int alg,
91                                        unsigned int flags,
92                                        unsigned int protocol,
93                                        unsigned int bits,
94                                        dns_rdataclass_t rdclass,
95                                        isc_mem_t *mctx);
96 static isc_result_t     write_public_key(const dst_key_t *key, int type,
97                                          const char *directory);
98 static isc_result_t     buildfilename(dns_name_t *name,
99                                       dns_keytag_t id,
100                                       unsigned int alg,
101                                       unsigned int type,
102                                       const char *directory,
103                                       isc_buffer_t *out);
104 static isc_result_t     computeid(dst_key_t *key);
105 static isc_result_t     frombuffer(dns_name_t *name,
106                                    unsigned int alg,
107                                    unsigned int flags,
108                                    unsigned int protocol,
109                                    dns_rdataclass_t rdclass,
110                                    isc_buffer_t *source,
111                                    isc_mem_t *mctx,
112                                    dst_key_t **keyp);
113
114 static isc_result_t     algorithm_status(unsigned int alg);
115
116 static isc_result_t     addsuffix(char *filename, int len,
117                                   const char *dirname, const char *ofilename,
118                                   const char *suffix);
119
120 #define RETERR(x)                               \
121         do {                                    \
122                 result = (x);                   \
123                 if (result != ISC_R_SUCCESS)    \
124                         goto out;               \
125         } while (0)
126
127 #define CHECKALG(alg)                           \
128         do {                                    \
129                 isc_result_t _r;                \
130                 _r = algorithm_status(alg);     \
131                 if (_r != ISC_R_SUCCESS)        \
132                         return (_r);            \
133         } while (0);                            \
134
135 #if defined(OPENSSL) && defined(BIND9)
136 static void *
137 default_memalloc(void *arg, size_t size) {
138         UNUSED(arg);
139         if (size == 0U)
140                 size = 1;
141         return (malloc(size));
142 }
143
144 static void
145 default_memfree(void *arg, void *ptr) {
146         UNUSED(arg);
147         free(ptr);
148 }
149 #endif
150
151 isc_result_t
152 dst_lib_init(isc_mem_t *mctx, isc_entropy_t *ectx, unsigned int eflags) {
153         return (dst_lib_init2(mctx, ectx, NULL, eflags));
154 }
155
156 isc_result_t
157 dst_lib_init2(isc_mem_t *mctx, isc_entropy_t *ectx,
158               const char *engine, unsigned int eflags) {
159         isc_result_t result;
160
161         REQUIRE(mctx != NULL);
162 #ifdef BIND9
163         REQUIRE(ectx != NULL);
164 #else
165         UNUSED(ectx);
166 #endif
167         REQUIRE(dst_initialized == ISC_FALSE);
168
169 #ifndef OPENSSL
170         UNUSED(engine);
171 #endif
172
173         dst__memory_pool = NULL;
174
175 #if defined(OPENSSL) && defined(BIND9)
176         UNUSED(mctx);
177         /*
178          * When using --with-openssl, there seems to be no good way of not
179          * leaking memory due to the openssl error handling mechanism.
180          * Avoid assertions by using a local memory context and not checking
181          * for leaks on exit.  Note: as there are leaks we cannot use
182          * ISC_MEMFLAG_INTERNAL as it will free up memory still being used
183          * by libcrypto.
184          */
185         result = isc_mem_createx2(0, 0, default_memalloc, default_memfree,
186                                   NULL, &dst__memory_pool, 0);
187         if (result != ISC_R_SUCCESS)
188                 return (result);
189         isc_mem_setname(dst__memory_pool, "dst", NULL);
190 #ifndef OPENSSL_LEAKS
191         isc_mem_setdestroycheck(dst__memory_pool, ISC_FALSE);
192 #endif
193 #else
194         isc_mem_attach(mctx, &dst__memory_pool);
195 #endif
196 #ifdef BIND9
197         isc_entropy_attach(ectx, &dst_entropy_pool);
198 #endif
199         dst_entropy_flags = eflags;
200
201         dst_result_register();
202
203         memset(dst_t_func, 0, sizeof(dst_t_func));
204         RETERR(dst__hmacmd5_init(&dst_t_func[DST_ALG_HMACMD5]));
205         RETERR(dst__hmacsha1_init(&dst_t_func[DST_ALG_HMACSHA1]));
206         RETERR(dst__hmacsha224_init(&dst_t_func[DST_ALG_HMACSHA224]));
207         RETERR(dst__hmacsha256_init(&dst_t_func[DST_ALG_HMACSHA256]));
208         RETERR(dst__hmacsha384_init(&dst_t_func[DST_ALG_HMACSHA384]));
209         RETERR(dst__hmacsha512_init(&dst_t_func[DST_ALG_HMACSHA512]));
210 #ifdef OPENSSL
211         RETERR(dst__openssl_init(engine));
212         RETERR(dst__opensslrsa_init(&dst_t_func[DST_ALG_RSAMD5],
213                                     DST_ALG_RSAMD5));
214         RETERR(dst__opensslrsa_init(&dst_t_func[DST_ALG_RSASHA1],
215                                     DST_ALG_RSASHA1));
216         RETERR(dst__opensslrsa_init(&dst_t_func[DST_ALG_NSEC3RSASHA1],
217                                     DST_ALG_NSEC3RSASHA1));
218         RETERR(dst__opensslrsa_init(&dst_t_func[DST_ALG_RSASHA256],
219                                     DST_ALG_RSASHA256));
220         RETERR(dst__opensslrsa_init(&dst_t_func[DST_ALG_RSASHA512],
221                                     DST_ALG_RSASHA512));
222 #ifdef HAVE_OPENSSL_DSA
223         RETERR(dst__openssldsa_init(&dst_t_func[DST_ALG_DSA]));
224         RETERR(dst__openssldsa_init(&dst_t_func[DST_ALG_NSEC3DSA]));
225 #endif
226         RETERR(dst__openssldh_init(&dst_t_func[DST_ALG_DH]));
227 #ifdef HAVE_OPENSSL_GOST
228         RETERR(dst__opensslgost_init(&dst_t_func[DST_ALG_ECCGOST]));
229 #endif
230 #ifdef HAVE_OPENSSL_ECDSA
231         RETERR(dst__opensslecdsa_init(&dst_t_func[DST_ALG_ECDSA256]));
232         RETERR(dst__opensslecdsa_init(&dst_t_func[DST_ALG_ECDSA384]));
233 #endif
234 #endif /* OPENSSL */
235 #ifdef GSSAPI
236         RETERR(dst__gssapi_init(&dst_t_func[DST_ALG_GSSAPI]));
237 #endif
238         dst_initialized = ISC_TRUE;
239         return (ISC_R_SUCCESS);
240
241  out:
242         /* avoid immediate crash! */
243         dst_initialized = ISC_TRUE;
244         dst_lib_destroy();
245         return (result);
246 }
247
248 void
249 dst_lib_destroy(void) {
250         int i;
251         RUNTIME_CHECK(dst_initialized == ISC_TRUE);
252         dst_initialized = ISC_FALSE;
253
254         for (i = 0; i < DST_MAX_ALGS; i++)
255                 if (dst_t_func[i] != NULL && dst_t_func[i]->cleanup != NULL)
256                         dst_t_func[i]->cleanup();
257 #ifdef OPENSSL
258         dst__openssl_destroy();
259 #endif
260         if (dst__memory_pool != NULL)
261                 isc_mem_detach(&dst__memory_pool);
262 #ifdef BIND9
263         if (dst_entropy_pool != NULL)
264                 isc_entropy_detach(&dst_entropy_pool);
265 #endif
266 }
267
268 isc_boolean_t
269 dst_algorithm_supported(unsigned int alg) {
270         REQUIRE(dst_initialized == ISC_TRUE);
271
272         if (alg >= DST_MAX_ALGS || dst_t_func[alg] == NULL)
273                 return (ISC_FALSE);
274         return (ISC_TRUE);
275 }
276
277 isc_result_t
278 dst_context_create(dst_key_t *key, isc_mem_t *mctx, dst_context_t **dctxp) {
279         dst_context_t *dctx;
280         isc_result_t result;
281
282         REQUIRE(dst_initialized == ISC_TRUE);
283         REQUIRE(VALID_KEY(key));
284         REQUIRE(mctx != NULL);
285         REQUIRE(dctxp != NULL && *dctxp == NULL);
286
287         if (key->func->createctx == NULL)
288                 return (DST_R_UNSUPPORTEDALG);
289         if (key->keydata.generic == NULL)
290                 return (DST_R_NULLKEY);
291
292         dctx = isc_mem_get(mctx, sizeof(dst_context_t));
293         if (dctx == NULL)
294                 return (ISC_R_NOMEMORY);
295         dctx->key = key;
296         dctx->mctx = mctx;
297         result = key->func->createctx(key, dctx);
298         if (result != ISC_R_SUCCESS) {
299                 isc_mem_put(mctx, dctx, sizeof(dst_context_t));
300                 return (result);
301         }
302         dctx->magic = CTX_MAGIC;
303         *dctxp = dctx;
304         return (ISC_R_SUCCESS);
305 }
306
307 void
308 dst_context_destroy(dst_context_t **dctxp) {
309         dst_context_t *dctx;
310
311         REQUIRE(dctxp != NULL && VALID_CTX(*dctxp));
312
313         dctx = *dctxp;
314         INSIST(dctx->key->func->destroyctx != NULL);
315         dctx->key->func->destroyctx(dctx);
316         dctx->magic = 0;
317         isc_mem_put(dctx->mctx, dctx, sizeof(dst_context_t));
318         *dctxp = NULL;
319 }
320
321 isc_result_t
322 dst_context_adddata(dst_context_t *dctx, const isc_region_t *data) {
323         REQUIRE(VALID_CTX(dctx));
324         REQUIRE(data != NULL);
325         INSIST(dctx->key->func->adddata != NULL);
326
327         return (dctx->key->func->adddata(dctx, data));
328 }
329
330 isc_result_t
331 dst_context_sign(dst_context_t *dctx, isc_buffer_t *sig) {
332         dst_key_t *key;
333
334         REQUIRE(VALID_CTX(dctx));
335         REQUIRE(sig != NULL);
336
337         key = dctx->key;
338         CHECKALG(key->key_alg);
339         if (key->keydata.generic == NULL)
340                 return (DST_R_NULLKEY);
341
342         if (key->func->sign == NULL)
343                 return (DST_R_NOTPRIVATEKEY);
344         if (key->func->isprivate == NULL ||
345             key->func->isprivate(key) == ISC_FALSE)
346                 return (DST_R_NOTPRIVATEKEY);
347
348         return (key->func->sign(dctx, sig));
349 }
350
351 isc_result_t
352 dst_context_verify(dst_context_t *dctx, isc_region_t *sig) {
353         REQUIRE(VALID_CTX(dctx));
354         REQUIRE(sig != NULL);
355
356         CHECKALG(dctx->key->key_alg);
357         if (dctx->key->keydata.generic == NULL)
358                 return (DST_R_NULLKEY);
359         if (dctx->key->func->verify == NULL)
360                 return (DST_R_NOTPUBLICKEY);
361
362         return (dctx->key->func->verify(dctx, sig));
363 }
364
365 isc_result_t
366 dst_key_computesecret(const dst_key_t *pub, const dst_key_t *priv,
367                       isc_buffer_t *secret)
368 {
369         REQUIRE(dst_initialized == ISC_TRUE);
370         REQUIRE(VALID_KEY(pub) && VALID_KEY(priv));
371         REQUIRE(secret != NULL);
372
373         CHECKALG(pub->key_alg);
374         CHECKALG(priv->key_alg);
375
376         if (pub->keydata.generic == NULL || priv->keydata.generic == NULL)
377                 return (DST_R_NULLKEY);
378
379         if (pub->key_alg != priv->key_alg ||
380             pub->func->computesecret == NULL ||
381             priv->func->computesecret == NULL)
382                 return (DST_R_KEYCANNOTCOMPUTESECRET);
383
384         if (dst_key_isprivate(priv) == ISC_FALSE)
385                 return (DST_R_NOTPRIVATEKEY);
386
387         return (pub->func->computesecret(pub, priv, secret));
388 }
389
390 isc_result_t
391 dst_key_tofile(const dst_key_t *key, int type, const char *directory) {
392         isc_result_t ret = ISC_R_SUCCESS;
393
394         REQUIRE(dst_initialized == ISC_TRUE);
395         REQUIRE(VALID_KEY(key));
396         REQUIRE((type & (DST_TYPE_PRIVATE | DST_TYPE_PUBLIC)) != 0);
397
398         CHECKALG(key->key_alg);
399
400         if (key->func->tofile == NULL)
401                 return (DST_R_UNSUPPORTEDALG);
402
403         if (type & DST_TYPE_PUBLIC) {
404                 ret = write_public_key(key, type, directory);
405                 if (ret != ISC_R_SUCCESS)
406                         return (ret);
407         }
408
409         if ((type & DST_TYPE_PRIVATE) &&
410             (key->key_flags & DNS_KEYFLAG_TYPEMASK) != DNS_KEYTYPE_NOKEY)
411                 return (key->func->tofile(key, directory));
412         else
413                 return (ISC_R_SUCCESS);
414 }
415
416 isc_result_t
417 dst_key_fromfile(dns_name_t *name, dns_keytag_t id,
418                  unsigned int alg, int type, const char *directory,
419                  isc_mem_t *mctx, dst_key_t **keyp)
420 {
421         char filename[ISC_DIR_NAMEMAX];
422         isc_buffer_t b;
423         dst_key_t *key;
424         isc_result_t result;
425
426         REQUIRE(dst_initialized == ISC_TRUE);
427         REQUIRE(dns_name_isabsolute(name));
428         REQUIRE((type & (DST_TYPE_PRIVATE | DST_TYPE_PUBLIC)) != 0);
429         REQUIRE(mctx != NULL);
430         REQUIRE(keyp != NULL && *keyp == NULL);
431
432         CHECKALG(alg);
433
434         isc_buffer_init(&b, filename, sizeof(filename));
435         result = buildfilename(name, id, alg, type, directory, &b);
436         if (result != ISC_R_SUCCESS)
437                 return (result);
438
439         key = NULL;
440         result = dst_key_fromnamedfile(filename, NULL, type, mctx, &key);
441         if (result != ISC_R_SUCCESS)
442                 return (result);
443
444         result = computeid(key);
445         if (result != ISC_R_SUCCESS) {
446                 dst_key_free(&key);
447                 return (result);
448         }
449
450         if (!dns_name_equal(name, key->key_name) || id != key->key_id ||
451             alg != key->key_alg) {
452                 dst_key_free(&key);
453                 return (DST_R_INVALIDPRIVATEKEY);
454         }
455
456         *keyp = key;
457         return (ISC_R_SUCCESS);
458 }
459
460 isc_result_t
461 dst_key_fromnamedfile(const char *filename, const char *dirname,
462                       int type, isc_mem_t *mctx, dst_key_t **keyp)
463 {
464         isc_result_t result;
465         dst_key_t *pubkey = NULL, *key = NULL;
466         char *newfilename = NULL;
467         int newfilenamelen = 0;
468         isc_lex_t *lex = NULL;
469
470         REQUIRE(dst_initialized == ISC_TRUE);
471         REQUIRE(filename != NULL);
472         REQUIRE((type & (DST_TYPE_PRIVATE | DST_TYPE_PUBLIC)) != 0);
473         REQUIRE(mctx != NULL);
474         REQUIRE(keyp != NULL && *keyp == NULL);
475
476         /* If an absolute path is specified, don't use the key directory */
477 #ifndef WIN32
478         if (filename[0] == '/')
479                 dirname = NULL;
480 #else /* WIN32 */
481         if (filename[0] == '/' || filename[0] == '\\')
482                 dirname = NULL;
483 #endif
484
485         newfilenamelen = strlen(filename) + 5;
486         if (dirname != NULL)
487                 newfilenamelen += strlen(dirname) + 1;
488         newfilename = isc_mem_get(mctx, newfilenamelen);
489         if (newfilename == NULL)
490                 return (ISC_R_NOMEMORY);
491         result = addsuffix(newfilename, newfilenamelen,
492                            dirname, filename, ".key");
493         INSIST(result == ISC_R_SUCCESS);
494
495         result = dst_key_read_public(newfilename, type, mctx, &pubkey);
496         isc_mem_put(mctx, newfilename, newfilenamelen);
497         newfilename = NULL;
498         if (result != ISC_R_SUCCESS)
499                 return (result);
500
501         if ((type & (DST_TYPE_PRIVATE | DST_TYPE_PUBLIC)) == DST_TYPE_PUBLIC ||
502             (pubkey->key_flags & DNS_KEYFLAG_TYPEMASK) == DNS_KEYTYPE_NOKEY) {
503                 result = computeid(pubkey);
504                 if (result != ISC_R_SUCCESS) {
505                         dst_key_free(&pubkey);
506                         return (result);
507                 }
508
509                 *keyp = pubkey;
510                 return (ISC_R_SUCCESS);
511         }
512
513         result = algorithm_status(pubkey->key_alg);
514         if (result != ISC_R_SUCCESS) {
515                 dst_key_free(&pubkey);
516                 return (result);
517         }
518
519         key = get_key_struct(pubkey->key_name, pubkey->key_alg,
520                              pubkey->key_flags, pubkey->key_proto, 0,
521                              pubkey->key_class, mctx);
522         if (key == NULL) {
523                 dst_key_free(&pubkey);
524                 return (ISC_R_NOMEMORY);
525         }
526
527         if (key->func->parse == NULL)
528                 RETERR(DST_R_UNSUPPORTEDALG);
529
530         newfilenamelen = strlen(filename) + 9;
531         if (dirname != NULL)
532                 newfilenamelen += strlen(dirname) + 1;
533         newfilename = isc_mem_get(mctx, newfilenamelen);
534         if (newfilename == NULL)
535                 RETERR(ISC_R_NOMEMORY);
536         result = addsuffix(newfilename, newfilenamelen,
537                            dirname, filename, ".private");
538         INSIST(result == ISC_R_SUCCESS);
539
540         RETERR(isc_lex_create(mctx, 1500, &lex));
541         RETERR(isc_lex_openfile(lex, newfilename));
542         isc_mem_put(mctx, newfilename, newfilenamelen);
543
544         RETERR(key->func->parse(key, lex, pubkey));
545         isc_lex_destroy(&lex);
546
547         RETERR(computeid(key));
548
549         if (pubkey->key_id != key->key_id)
550                 RETERR(DST_R_INVALIDPRIVATEKEY);
551         dst_key_free(&pubkey);
552
553         *keyp = key;
554         return (ISC_R_SUCCESS);
555
556  out:
557         if (pubkey != NULL)
558                 dst_key_free(&pubkey);
559         if (newfilename != NULL)
560                 isc_mem_put(mctx, newfilename, newfilenamelen);
561         if (lex != NULL)
562                 isc_lex_destroy(&lex);
563         dst_key_free(&key);
564         return (result);
565 }
566
567 isc_result_t
568 dst_key_todns(const dst_key_t *key, isc_buffer_t *target) {
569         REQUIRE(dst_initialized == ISC_TRUE);
570         REQUIRE(VALID_KEY(key));
571         REQUIRE(target != NULL);
572
573         CHECKALG(key->key_alg);
574
575         if (key->func->todns == NULL)
576                 return (DST_R_UNSUPPORTEDALG);
577
578         if (isc_buffer_availablelength(target) < 4)
579                 return (ISC_R_NOSPACE);
580         isc_buffer_putuint16(target, (isc_uint16_t)(key->key_flags & 0xffff));
581         isc_buffer_putuint8(target, (isc_uint8_t)key->key_proto);
582         isc_buffer_putuint8(target, (isc_uint8_t)key->key_alg);
583
584         if (key->key_flags & DNS_KEYFLAG_EXTENDED) {
585                 if (isc_buffer_availablelength(target) < 2)
586                         return (ISC_R_NOSPACE);
587                 isc_buffer_putuint16(target,
588                                      (isc_uint16_t)((key->key_flags >> 16)
589                                                     & 0xffff));
590         }
591
592         if (key->keydata.generic == NULL) /*%< NULL KEY */
593                 return (ISC_R_SUCCESS);
594
595         return (key->func->todns(key, target));
596 }
597
598 isc_result_t
599 dst_key_fromdns(dns_name_t *name, dns_rdataclass_t rdclass,
600                 isc_buffer_t *source, isc_mem_t *mctx, dst_key_t **keyp)
601 {
602         isc_uint8_t alg, proto;
603         isc_uint32_t flags, extflags;
604         dst_key_t *key = NULL;
605         dns_keytag_t id, rid;
606         isc_region_t r;
607         isc_result_t result;
608
609         REQUIRE(dst_initialized);
610
611         isc_buffer_remainingregion(source, &r);
612
613         if (isc_buffer_remaininglength(source) < 4)
614                 return (DST_R_INVALIDPUBLICKEY);
615         flags = isc_buffer_getuint16(source);
616         proto = isc_buffer_getuint8(source);
617         alg = isc_buffer_getuint8(source);
618
619         id = dst_region_computeid(&r, alg);
620         rid = dst_region_computerid(&r, alg);
621
622         if (flags & DNS_KEYFLAG_EXTENDED) {
623                 if (isc_buffer_remaininglength(source) < 2)
624                         return (DST_R_INVALIDPUBLICKEY);
625                 extflags = isc_buffer_getuint16(source);
626                 flags |= (extflags << 16);
627         }
628
629         result = frombuffer(name, alg, flags, proto, rdclass, source,
630                             mctx, &key);
631         if (result != ISC_R_SUCCESS)
632                 return (result);
633         key->key_id = id;
634         key->key_rid = rid;
635
636         *keyp = key;
637         return (ISC_R_SUCCESS);
638 }
639
640 isc_result_t
641 dst_key_frombuffer(dns_name_t *name, unsigned int alg,
642                    unsigned int flags, unsigned int protocol,
643                    dns_rdataclass_t rdclass,
644                    isc_buffer_t *source, isc_mem_t *mctx, dst_key_t **keyp)
645 {
646         dst_key_t *key = NULL;
647         isc_result_t result;
648
649         REQUIRE(dst_initialized);
650
651         result = frombuffer(name, alg, flags, protocol, rdclass, source,
652                             mctx, &key);
653         if (result != ISC_R_SUCCESS)
654                 return (result);
655
656         result = computeid(key);
657         if (result != ISC_R_SUCCESS) {
658                 dst_key_free(&key);
659                 return (result);
660         }
661
662         *keyp = key;
663         return (ISC_R_SUCCESS);
664 }
665
666 isc_result_t
667 dst_key_tobuffer(const dst_key_t *key, isc_buffer_t *target) {
668         REQUIRE(dst_initialized == ISC_TRUE);
669         REQUIRE(VALID_KEY(key));
670         REQUIRE(target != NULL);
671
672         CHECKALG(key->key_alg);
673
674         if (key->func->todns == NULL)
675                 return (DST_R_UNSUPPORTEDALG);
676
677         return (key->func->todns(key, target));
678 }
679
680 isc_result_t
681 dst_key_privatefrombuffer(dst_key_t *key, isc_buffer_t *buffer) {
682         isc_lex_t *lex = NULL;
683         isc_result_t result = ISC_R_SUCCESS;
684
685         REQUIRE(dst_initialized == ISC_TRUE);
686         REQUIRE(VALID_KEY(key));
687         REQUIRE(!dst_key_isprivate(key));
688         REQUIRE(buffer != NULL);
689
690         if (key->func->parse == NULL)
691                 RETERR(DST_R_UNSUPPORTEDALG);
692
693         RETERR(isc_lex_create(key->mctx, 1500, &lex));
694         RETERR(isc_lex_openbuffer(lex, buffer));
695         RETERR(key->func->parse(key, lex, NULL));
696  out:
697         if (lex != NULL)
698                 isc_lex_destroy(&lex);
699         return (result);
700 }
701
702 gss_ctx_id_t
703 dst_key_getgssctx(const dst_key_t *key)
704 {
705         REQUIRE(key != NULL);
706
707         return (key->keydata.gssctx);
708 }
709
710 isc_result_t
711 dst_key_fromgssapi(dns_name_t *name, gss_ctx_id_t gssctx, isc_mem_t *mctx,
712                    dst_key_t **keyp, isc_region_t *intoken)
713 {
714         dst_key_t *key;
715         isc_result_t result;
716
717         REQUIRE(gssctx != NULL);
718         REQUIRE(keyp != NULL && *keyp == NULL);
719
720         key = get_key_struct(name, DST_ALG_GSSAPI, 0, DNS_KEYPROTO_DNSSEC,
721                              0, dns_rdataclass_in, mctx);
722         if (key == NULL)
723                 return (ISC_R_NOMEMORY);
724
725         if (intoken != NULL) {
726                 /*
727                  * Keep the token for use by external ssu rules. They may need
728                  * to examine the PAC in the kerberos ticket.
729                  */
730                 RETERR(isc_buffer_allocate(key->mctx, &key->key_tkeytoken,
731                        intoken->length));
732                 RETERR(isc_buffer_copyregion(key->key_tkeytoken, intoken));
733         }
734
735         key->keydata.gssctx = gssctx;
736         *keyp = key;
737         result = ISC_R_SUCCESS;
738 out:
739         return result;
740 }
741
742 isc_result_t
743 dst_key_fromlabel(dns_name_t *name, int alg, unsigned int flags,
744                   unsigned int protocol, dns_rdataclass_t rdclass,
745                   const char *engine, const char *label, const char *pin,
746                   isc_mem_t *mctx, dst_key_t **keyp)
747 {
748         dst_key_t *key;
749         isc_result_t result;
750
751         REQUIRE(dst_initialized == ISC_TRUE);
752         REQUIRE(dns_name_isabsolute(name));
753         REQUIRE(mctx != NULL);
754         REQUIRE(keyp != NULL && *keyp == NULL);
755         REQUIRE(label != NULL);
756
757         CHECKALG(alg);
758
759         key = get_key_struct(name, alg, flags, protocol, 0, rdclass, mctx);
760         if (key == NULL)
761                 return (ISC_R_NOMEMORY);
762
763         if (key->func->fromlabel == NULL) {
764                 dst_key_free(&key);
765                 return (DST_R_UNSUPPORTEDALG);
766         }
767
768         result = key->func->fromlabel(key, engine, label, pin);
769         if (result != ISC_R_SUCCESS) {
770                 dst_key_free(&key);
771                 return (result);
772         }
773
774         result = computeid(key);
775         if (result != ISC_R_SUCCESS) {
776                 dst_key_free(&key);
777                 return (result);
778         }
779
780         *keyp = key;
781         return (ISC_R_SUCCESS);
782 }
783
784 isc_result_t
785 dst_key_generate(dns_name_t *name, unsigned int alg,
786                  unsigned int bits, unsigned int param,
787                  unsigned int flags, unsigned int protocol,
788                  dns_rdataclass_t rdclass,
789                  isc_mem_t *mctx, dst_key_t **keyp)
790 {
791         return (dst_key_generate2(name, alg, bits, param, flags, protocol,
792                                   rdclass, mctx, keyp, NULL));
793 }
794
795 isc_result_t
796 dst_key_generate2(dns_name_t *name, unsigned int alg,
797                   unsigned int bits, unsigned int param,
798                   unsigned int flags, unsigned int protocol,
799                   dns_rdataclass_t rdclass,
800                   isc_mem_t *mctx, dst_key_t **keyp,
801                   void (*callback)(int))
802 {
803         dst_key_t *key;
804         isc_result_t ret;
805
806         REQUIRE(dst_initialized == ISC_TRUE);
807         REQUIRE(dns_name_isabsolute(name));
808         REQUIRE(mctx != NULL);
809         REQUIRE(keyp != NULL && *keyp == NULL);
810
811         CHECKALG(alg);
812
813         key = get_key_struct(name, alg, flags, protocol, bits, rdclass, mctx);
814         if (key == NULL)
815                 return (ISC_R_NOMEMORY);
816
817         if (bits == 0) { /*%< NULL KEY */
818                 key->key_flags |= DNS_KEYTYPE_NOKEY;
819                 *keyp = key;
820                 return (ISC_R_SUCCESS);
821         }
822
823         if (key->func->generate == NULL) {
824                 dst_key_free(&key);
825                 return (DST_R_UNSUPPORTEDALG);
826         }
827
828         ret = key->func->generate(key, param, callback);
829         if (ret != ISC_R_SUCCESS) {
830                 dst_key_free(&key);
831                 return (ret);
832         }
833
834         ret = computeid(key);
835         if (ret != ISC_R_SUCCESS) {
836                 dst_key_free(&key);
837                 return (ret);
838         }
839
840         *keyp = key;
841         return (ISC_R_SUCCESS);
842 }
843
844 isc_result_t
845 dst_key_getnum(const dst_key_t *key, int type, isc_uint32_t *valuep)
846 {
847         REQUIRE(VALID_KEY(key));
848         REQUIRE(valuep != NULL);
849         REQUIRE(type <= DST_MAX_NUMERIC);
850         if (!key->numset[type])
851                 return (ISC_R_NOTFOUND);
852         *valuep = key->nums[type];
853         return (ISC_R_SUCCESS);
854 }
855
856 void
857 dst_key_setnum(dst_key_t *key, int type, isc_uint32_t value)
858 {
859         REQUIRE(VALID_KEY(key));
860         REQUIRE(type <= DST_MAX_NUMERIC);
861         key->nums[type] = value;
862         key->numset[type] = ISC_TRUE;
863 }
864
865 void
866 dst_key_unsetnum(dst_key_t *key, int type)
867 {
868         REQUIRE(VALID_KEY(key));
869         REQUIRE(type <= DST_MAX_NUMERIC);
870         key->numset[type] = ISC_FALSE;
871 }
872
873 isc_result_t
874 dst_key_gettime(const dst_key_t *key, int type, isc_stdtime_t *timep) {
875         REQUIRE(VALID_KEY(key));
876         REQUIRE(timep != NULL);
877         REQUIRE(type <= DST_MAX_TIMES);
878         if (!key->timeset[type])
879                 return (ISC_R_NOTFOUND);
880         *timep = key->times[type];
881         return (ISC_R_SUCCESS);
882 }
883
884 void
885 dst_key_settime(dst_key_t *key, int type, isc_stdtime_t when) {
886         REQUIRE(VALID_KEY(key));
887         REQUIRE(type <= DST_MAX_TIMES);
888         key->times[type] = when;
889         key->timeset[type] = ISC_TRUE;
890 }
891
892 void
893 dst_key_unsettime(dst_key_t *key, int type) {
894         REQUIRE(VALID_KEY(key));
895         REQUIRE(type <= DST_MAX_TIMES);
896         key->timeset[type] = ISC_FALSE;
897 }
898
899 isc_result_t
900 dst_key_getprivateformat(const dst_key_t *key, int *majorp, int *minorp) {
901         REQUIRE(VALID_KEY(key));
902         REQUIRE(majorp != NULL);
903         REQUIRE(minorp != NULL);
904         *majorp = key->fmt_major;
905         *minorp = key->fmt_minor;
906         return (ISC_R_SUCCESS);
907 }
908
909 void
910 dst_key_setprivateformat(dst_key_t *key, int major, int minor) {
911         REQUIRE(VALID_KEY(key));
912         key->fmt_major = major;
913         key->fmt_minor = minor;
914 }
915
916 static isc_boolean_t
917 comparekeys(const dst_key_t *key1, const dst_key_t *key2,
918             isc_boolean_t match_revoked_key,
919             isc_boolean_t (*compare)(const dst_key_t *key1,
920                                      const dst_key_t *key2))
921 {
922         REQUIRE(dst_initialized == ISC_TRUE);
923         REQUIRE(VALID_KEY(key1));
924         REQUIRE(VALID_KEY(key2));
925
926         if (key1 == key2)
927                 return (ISC_TRUE);
928
929         if (key1 == NULL || key2 == NULL)
930                 return (ISC_FALSE);
931
932         if (key1->key_alg != key2->key_alg)
933                 return (ISC_FALSE);
934
935         if (key1->key_id != key2->key_id) {
936                 if (!match_revoked_key)
937                         return (ISC_FALSE);
938                 if (key1->key_alg == DST_ALG_RSAMD5)
939                         return (ISC_FALSE);
940                 if ((key1->key_flags & DNS_KEYFLAG_REVOKE) ==
941                     (key2->key_flags & DNS_KEYFLAG_REVOKE))
942                         return (ISC_FALSE);
943                 if (key1->key_id != key2->key_rid &&
944                     key1->key_rid != key2->key_id)
945                         return (ISC_FALSE);
946         }
947
948         if (compare != NULL)
949                 return (compare(key1, key2));
950         else
951                 return (ISC_FALSE);
952 }
953
954
955 /*
956  * Compares only the public portion of two keys, by converting them
957  * both to wire format and comparing the results.
958  */
959 static isc_boolean_t
960 pub_compare(const dst_key_t *key1, const dst_key_t *key2) {
961         isc_result_t result;
962         unsigned char buf1[DST_KEY_MAXSIZE], buf2[DST_KEY_MAXSIZE];
963         isc_buffer_t b1, b2;
964         isc_region_t r1, r2;
965
966         isc_buffer_init(&b1, buf1, sizeof(buf1));
967         result = dst_key_todns(key1, &b1);
968         if (result != ISC_R_SUCCESS)
969                 return (ISC_FALSE);
970         /* Zero out flags. */
971         buf1[0] = buf1[1] = 0;
972         if ((key1->key_flags & DNS_KEYFLAG_EXTENDED) != 0)
973                 isc_buffer_subtract(&b1, 2);
974
975         isc_buffer_init(&b2, buf2, sizeof(buf2));
976         result = dst_key_todns(key2, &b2);
977         if (result != ISC_R_SUCCESS)
978                 return (ISC_FALSE);
979         /* Zero out flags. */
980         buf2[0] = buf2[1] = 0;
981         if ((key2->key_flags & DNS_KEYFLAG_EXTENDED) != 0)
982                 isc_buffer_subtract(&b2, 2);
983
984         isc_buffer_usedregion(&b1, &r1);
985         /* Remove extended flags. */
986         if ((key1->key_flags & DNS_KEYFLAG_EXTENDED) != 0) {
987                 memmove(&buf1[4], &buf1[6], r1.length - 6);
988                 r1.length -= 2;
989         }
990
991         isc_buffer_usedregion(&b2, &r2);
992         /* Remove extended flags. */
993         if ((key2->key_flags & DNS_KEYFLAG_EXTENDED) != 0) {
994                 memmove(&buf2[4], &buf2[6], r2.length - 6);
995                 r2.length -= 2;
996         }
997         return (ISC_TF(isc_region_compare(&r1, &r2) == 0));
998 }
999
1000 isc_boolean_t
1001 dst_key_compare(const dst_key_t *key1, const dst_key_t *key2) {
1002         return (comparekeys(key1, key2, ISC_FALSE, key1->func->compare));
1003 }
1004
1005 isc_boolean_t
1006 dst_key_pubcompare(const dst_key_t *key1, const dst_key_t *key2,
1007                    isc_boolean_t match_revoked_key)
1008 {
1009         return (comparekeys(key1, key2, match_revoked_key, pub_compare));
1010 }
1011
1012
1013 isc_boolean_t
1014 dst_key_paramcompare(const dst_key_t *key1, const dst_key_t *key2) {
1015         REQUIRE(dst_initialized == ISC_TRUE);
1016         REQUIRE(VALID_KEY(key1));
1017         REQUIRE(VALID_KEY(key2));
1018
1019         if (key1 == key2)
1020                 return (ISC_TRUE);
1021         if (key1 == NULL || key2 == NULL)
1022                 return (ISC_FALSE);
1023         if (key1->key_alg == key2->key_alg &&
1024             key1->func->paramcompare != NULL &&
1025             key1->func->paramcompare(key1, key2) == ISC_TRUE)
1026                 return (ISC_TRUE);
1027         else
1028                 return (ISC_FALSE);
1029 }
1030
1031 void
1032 dst_key_attach(dst_key_t *source, dst_key_t **target) {
1033
1034         REQUIRE(dst_initialized == ISC_TRUE);
1035         REQUIRE(target != NULL && *target == NULL);
1036         REQUIRE(VALID_KEY(source));
1037
1038         isc_refcount_increment(&source->refs, NULL);
1039         *target = source;
1040 }
1041
1042 void
1043 dst_key_free(dst_key_t **keyp) {
1044         isc_mem_t *mctx;
1045         dst_key_t *key;
1046         unsigned int refs;
1047
1048         REQUIRE(dst_initialized == ISC_TRUE);
1049         REQUIRE(keyp != NULL && VALID_KEY(*keyp));
1050
1051         key = *keyp;
1052         mctx = key->mctx;
1053
1054         isc_refcount_decrement(&key->refs, &refs);
1055         if (refs != 0)
1056                 return;
1057
1058         isc_refcount_destroy(&key->refs);
1059         if (key->keydata.generic != NULL) {
1060                 INSIST(key->func->destroy != NULL);
1061                 key->func->destroy(key);
1062         }
1063         if (key->engine != NULL)
1064                 isc_mem_free(mctx, key->engine);
1065         if (key->label != NULL)
1066                 isc_mem_free(mctx, key->label);
1067         dns_name_free(key->key_name, mctx);
1068         isc_mem_put(mctx, key->key_name, sizeof(dns_name_t));
1069         if (key->key_tkeytoken) {
1070                 isc_buffer_free(&key->key_tkeytoken);
1071         }
1072         memset(key, 0, sizeof(dst_key_t));
1073         isc_mem_put(mctx, key, sizeof(dst_key_t));
1074         *keyp = NULL;
1075 }
1076
1077 isc_boolean_t
1078 dst_key_isprivate(const dst_key_t *key) {
1079         REQUIRE(VALID_KEY(key));
1080         INSIST(key->func->isprivate != NULL);
1081         return (key->func->isprivate(key));
1082 }
1083
1084 isc_result_t
1085 dst_key_buildfilename(const dst_key_t *key, int type,
1086                       const char *directory, isc_buffer_t *out) {
1087
1088         REQUIRE(VALID_KEY(key));
1089         REQUIRE(type == DST_TYPE_PRIVATE || type == DST_TYPE_PUBLIC ||
1090                 type == 0);
1091
1092         return (buildfilename(key->key_name, key->key_id, key->key_alg,
1093                               type, directory, out));
1094 }
1095
1096 isc_result_t
1097 dst_key_sigsize(const dst_key_t *key, unsigned int *n) {
1098         REQUIRE(dst_initialized == ISC_TRUE);
1099         REQUIRE(VALID_KEY(key));
1100         REQUIRE(n != NULL);
1101
1102         /* XXXVIX this switch statement is too sparse to gen a jump table. */
1103         switch (key->key_alg) {
1104         case DST_ALG_RSAMD5:
1105         case DST_ALG_RSASHA1:
1106         case DST_ALG_NSEC3RSASHA1:
1107         case DST_ALG_RSASHA256:
1108         case DST_ALG_RSASHA512:
1109                 *n = (key->key_size + 7) / 8;
1110                 break;
1111         case DST_ALG_DSA:
1112         case DST_ALG_NSEC3DSA:
1113                 *n = DNS_SIG_DSASIGSIZE;
1114                 break;
1115         case DST_ALG_ECCGOST:
1116                 *n = DNS_SIG_GOSTSIGSIZE;
1117                 break;
1118         case DST_ALG_ECDSA256:
1119                 *n = DNS_SIG_ECDSA256SIZE;
1120                 break;
1121         case DST_ALG_ECDSA384:
1122                 *n = DNS_SIG_ECDSA384SIZE;
1123                 break;
1124         case DST_ALG_HMACMD5:
1125                 *n = 16;
1126                 break;
1127         case DST_ALG_HMACSHA1:
1128                 *n = ISC_SHA1_DIGESTLENGTH;
1129                 break;
1130         case DST_ALG_HMACSHA224:
1131                 *n = ISC_SHA224_DIGESTLENGTH;
1132                 break;
1133         case DST_ALG_HMACSHA256:
1134                 *n = ISC_SHA256_DIGESTLENGTH;
1135                 break;
1136         case DST_ALG_HMACSHA384:
1137                 *n = ISC_SHA384_DIGESTLENGTH;
1138                 break;
1139         case DST_ALG_HMACSHA512:
1140                 *n = ISC_SHA512_DIGESTLENGTH;
1141                 break;
1142         case DST_ALG_GSSAPI:
1143                 *n = 128; /*%< XXX */
1144                 break;
1145         case DST_ALG_DH:
1146         default:
1147                 return (DST_R_UNSUPPORTEDALG);
1148         }
1149         return (ISC_R_SUCCESS);
1150 }
1151
1152 isc_result_t
1153 dst_key_secretsize(const dst_key_t *key, unsigned int *n) {
1154         REQUIRE(dst_initialized == ISC_TRUE);
1155         REQUIRE(VALID_KEY(key));
1156         REQUIRE(n != NULL);
1157
1158         if (key->key_alg == DST_ALG_DH)
1159                 *n = (key->key_size + 7) / 8;
1160         else
1161                 return (DST_R_UNSUPPORTEDALG);
1162         return (ISC_R_SUCCESS);
1163 }
1164
1165 /*%
1166  * Set the flags on a key, then recompute the key ID
1167  */
1168 isc_result_t
1169 dst_key_setflags(dst_key_t *key, isc_uint32_t flags) {
1170         REQUIRE(VALID_KEY(key));
1171         key->key_flags = flags;
1172         return (computeid(key));
1173 }
1174
1175 void
1176 dst_key_format(const dst_key_t *key, char *cp, unsigned int size) {
1177         char namestr[DNS_NAME_FORMATSIZE];
1178         char algstr[DNS_NAME_FORMATSIZE];
1179
1180         dns_name_format(dst_key_name(key), namestr, sizeof(namestr));
1181         dns_secalg_format((dns_secalg_t) dst_key_alg(key), algstr,
1182                           sizeof(algstr));
1183         snprintf(cp, size, "%s/%s/%d", namestr, algstr, dst_key_id(key));
1184 }
1185
1186 isc_result_t
1187 dst_key_dump(dst_key_t *key, isc_mem_t *mctx, char **buffer, int *length) {
1188
1189         REQUIRE(buffer != NULL && *buffer == NULL);
1190         REQUIRE(length != NULL && *length == 0);
1191         REQUIRE(VALID_KEY(key));
1192
1193         if (key->func->isprivate == NULL)
1194                 return (ISC_R_NOTIMPLEMENTED);
1195         return (key->func->dump(key, mctx, buffer, length));
1196 }
1197
1198 isc_result_t
1199 dst_key_restore(dns_name_t *name, unsigned int alg, unsigned int flags,
1200                 unsigned int protocol, dns_rdataclass_t rdclass,
1201                 isc_mem_t *mctx, const char *keystr, dst_key_t **keyp)
1202 {
1203         isc_result_t result;
1204         dst_key_t *key;
1205
1206         REQUIRE(dst_initialized == ISC_TRUE);
1207         REQUIRE(keyp != NULL && *keyp == NULL);
1208
1209         if (alg >= DST_MAX_ALGS || dst_t_func[alg] == NULL)
1210                 return (DST_R_UNSUPPORTEDALG);
1211
1212         if (dst_t_func[alg]->restore == NULL)
1213                 return (ISC_R_NOTIMPLEMENTED);
1214
1215         key = get_key_struct(name, alg, flags, protocol, 0, rdclass, mctx);
1216         if (key == NULL)
1217                 return (ISC_R_NOMEMORY);
1218
1219         result = (dst_t_func[alg]->restore)(key, keystr);
1220         if (result == ISC_R_SUCCESS)
1221                 *keyp = key;
1222         else
1223                 dst_key_free(&key);
1224
1225         return (result);
1226 }
1227
1228 /***
1229  *** Static methods
1230  ***/
1231
1232 /*%
1233  * Allocates a key structure and fills in some of the fields.
1234  */
1235 static dst_key_t *
1236 get_key_struct(dns_name_t *name, unsigned int alg,
1237                unsigned int flags, unsigned int protocol,
1238                unsigned int bits, dns_rdataclass_t rdclass,
1239                isc_mem_t *mctx)
1240 {
1241         dst_key_t *key;
1242         isc_result_t result;
1243         int i;
1244
1245         key = (dst_key_t *) isc_mem_get(mctx, sizeof(dst_key_t));
1246         if (key == NULL)
1247                 return (NULL);
1248
1249         memset(key, 0, sizeof(dst_key_t));
1250         key->magic = KEY_MAGIC;
1251
1252         result = isc_refcount_init(&key->refs, 1);
1253         if (result != ISC_R_SUCCESS) {
1254                 isc_mem_put(mctx, key, sizeof(dst_key_t));
1255                 return (NULL);
1256         }
1257
1258         key->key_name = isc_mem_get(mctx, sizeof(dns_name_t));
1259         if (key->key_name == NULL) {
1260                 isc_refcount_destroy(&key->refs);
1261                 isc_mem_put(mctx, key, sizeof(dst_key_t));
1262                 return (NULL);
1263         }
1264         dns_name_init(key->key_name, NULL);
1265         result = dns_name_dup(name, mctx, key->key_name);
1266         if (result != ISC_R_SUCCESS) {
1267                 isc_refcount_destroy(&key->refs);
1268                 isc_mem_put(mctx, key->key_name, sizeof(dns_name_t));
1269                 isc_mem_put(mctx, key, sizeof(dst_key_t));
1270                 return (NULL);
1271         }
1272         key->key_alg = alg;
1273         key->key_flags = flags;
1274         key->key_proto = protocol;
1275         key->mctx = mctx;
1276         key->keydata.generic = NULL;
1277         key->key_size = bits;
1278         key->key_class = rdclass;
1279         key->func = dst_t_func[alg];
1280         key->fmt_major = 0;
1281         key->fmt_minor = 0;
1282         for (i = 0; i < (DST_MAX_TIMES + 1); i++) {
1283                 key->times[i] = 0;
1284                 key->timeset[i] = ISC_FALSE;
1285         }
1286         return (key);
1287 }
1288
1289 /*%
1290  * Reads a public key from disk
1291  */
1292 isc_result_t
1293 dst_key_read_public(const char *filename, int type,
1294                     isc_mem_t *mctx, dst_key_t **keyp)
1295 {
1296         u_char rdatabuf[DST_KEY_MAXSIZE];
1297         isc_buffer_t b;
1298         dns_fixedname_t name;
1299         isc_lex_t *lex = NULL;
1300         isc_token_t token;
1301         isc_result_t ret;
1302         dns_rdata_t rdata = DNS_RDATA_INIT;
1303         unsigned int opt = ISC_LEXOPT_DNSMULTILINE;
1304         dns_rdataclass_t rdclass = dns_rdataclass_in;
1305         isc_lexspecials_t specials;
1306         isc_uint32_t ttl;
1307         isc_result_t result;
1308         dns_rdatatype_t keytype;
1309
1310         /*
1311          * Open the file and read its formatted contents
1312          * File format:
1313          *    domain.name [ttl] [class] [KEY|DNSKEY] <flags> <protocol> <algorithm> <key>
1314          */
1315
1316         /* 1500 should be large enough for any key */
1317         ret = isc_lex_create(mctx, 1500, &lex);
1318         if (ret != ISC_R_SUCCESS)
1319                 goto cleanup;
1320
1321         memset(specials, 0, sizeof(specials));
1322         specials['('] = 1;
1323         specials[')'] = 1;
1324         specials['"'] = 1;
1325         isc_lex_setspecials(lex, specials);
1326         isc_lex_setcomments(lex, ISC_LEXCOMMENT_DNSMASTERFILE);
1327
1328         ret = isc_lex_openfile(lex, filename);
1329         if (ret != ISC_R_SUCCESS)
1330                 goto cleanup;
1331
1332 #define NEXTTOKEN(lex, opt, token) { \
1333         ret = isc_lex_gettoken(lex, opt, token); \
1334         if (ret != ISC_R_SUCCESS) \
1335                 goto cleanup; \
1336         }
1337
1338 #define BADTOKEN() { \
1339         ret = ISC_R_UNEXPECTEDTOKEN; \
1340         goto cleanup; \
1341         }
1342
1343         /* Read the domain name */
1344         NEXTTOKEN(lex, opt, &token);
1345         if (token.type != isc_tokentype_string)
1346                 BADTOKEN();
1347
1348         /*
1349          * We don't support "@" in .key files.
1350          */
1351         if (!strcmp(DST_AS_STR(token), "@"))
1352                 BADTOKEN();
1353
1354         dns_fixedname_init(&name);
1355         isc_buffer_init(&b, DST_AS_STR(token), strlen(DST_AS_STR(token)));
1356         isc_buffer_add(&b, strlen(DST_AS_STR(token)));
1357         ret = dns_name_fromtext(dns_fixedname_name(&name), &b, dns_rootname,
1358                                 0, NULL);
1359         if (ret != ISC_R_SUCCESS)
1360                 goto cleanup;
1361
1362         /* Read the next word: either TTL, class, or 'KEY' */
1363         NEXTTOKEN(lex, opt, &token);
1364
1365         if (token.type != isc_tokentype_string)
1366                 BADTOKEN();
1367
1368         /* If it's a TTL, read the next one */
1369         result = dns_ttl_fromtext(&token.value.as_textregion, &ttl);
1370         if (result == ISC_R_SUCCESS)
1371                 NEXTTOKEN(lex, opt, &token);
1372
1373         if (token.type != isc_tokentype_string)
1374                 BADTOKEN();
1375
1376         ret = dns_rdataclass_fromtext(&rdclass, &token.value.as_textregion);
1377         if (ret == ISC_R_SUCCESS)
1378                 NEXTTOKEN(lex, opt, &token);
1379
1380         if (token.type != isc_tokentype_string)
1381                 BADTOKEN();
1382
1383         if (strcasecmp(DST_AS_STR(token), "DNSKEY") == 0)
1384                 keytype = dns_rdatatype_dnskey;
1385         else if (strcasecmp(DST_AS_STR(token), "KEY") == 0)
1386                 keytype = dns_rdatatype_key; /*%< SIG(0), TKEY */
1387         else
1388                 BADTOKEN();
1389
1390         if (((type & DST_TYPE_KEY) != 0 && keytype != dns_rdatatype_key) ||
1391             ((type & DST_TYPE_KEY) == 0 && keytype != dns_rdatatype_dnskey)) {
1392                 ret = DST_R_BADKEYTYPE;
1393                 goto cleanup;
1394         }
1395
1396         isc_buffer_init(&b, rdatabuf, sizeof(rdatabuf));
1397         ret = dns_rdata_fromtext(&rdata, rdclass, keytype, lex, NULL,
1398                                  ISC_FALSE, mctx, &b, NULL);
1399         if (ret != ISC_R_SUCCESS)
1400                 goto cleanup;
1401
1402         ret = dst_key_fromdns(dns_fixedname_name(&name), rdclass, &b, mctx,
1403                               keyp);
1404         if (ret != ISC_R_SUCCESS)
1405                 goto cleanup;
1406
1407  cleanup:
1408         if (lex != NULL)
1409                 isc_lex_destroy(&lex);
1410         return (ret);
1411 }
1412
1413 static isc_boolean_t
1414 issymmetric(const dst_key_t *key) {
1415         REQUIRE(dst_initialized == ISC_TRUE);
1416         REQUIRE(VALID_KEY(key));
1417
1418         /* XXXVIX this switch statement is too sparse to gen a jump table. */
1419         switch (key->key_alg) {
1420         case DST_ALG_RSAMD5:
1421         case DST_ALG_RSASHA1:
1422         case DST_ALG_NSEC3RSASHA1:
1423         case DST_ALG_RSASHA256:
1424         case DST_ALG_RSASHA512:
1425         case DST_ALG_DSA:
1426         case DST_ALG_NSEC3DSA:
1427         case DST_ALG_DH:
1428         case DST_ALG_ECCGOST:
1429         case DST_ALG_ECDSA256:
1430         case DST_ALG_ECDSA384:
1431                 return (ISC_FALSE);
1432         case DST_ALG_HMACMD5:
1433         case DST_ALG_GSSAPI:
1434                 return (ISC_TRUE);
1435         default:
1436                 return (ISC_FALSE);
1437         }
1438 }
1439
1440 /*%
1441  * Write key timing metadata to a file pointer, preceded by 'tag'
1442  */
1443 static void
1444 printtime(const dst_key_t *key, int type, const char *tag, FILE *stream) {
1445         isc_result_t result;
1446 #ifdef ISC_PLATFORM_USETHREADS
1447         char output[26]; /* Minimum buffer as per ctime_r() specification. */
1448 #else
1449         const char *output;
1450 #endif
1451         isc_stdtime_t when;
1452         time_t t;
1453         char utc[sizeof("YYYYMMDDHHSSMM")];
1454         isc_buffer_t b;
1455         isc_region_t r;
1456
1457         result = dst_key_gettime(key, type, &when);
1458         if (result == ISC_R_NOTFOUND)
1459                 return;
1460
1461         /* time_t and isc_stdtime_t might be different sizes */
1462         t = when;
1463 #ifdef ISC_PLATFORM_USETHREADS
1464 #ifdef WIN32
1465         if (ctime_s(output, sizeof(output), &t) != 0)
1466                 goto error;
1467 #else
1468         if (ctime_r(&t, output) == NULL)
1469                 goto error;
1470 #endif
1471 #else
1472         output = ctime(&t);
1473 #endif
1474
1475         isc_buffer_init(&b, utc, sizeof(utc));
1476         result = dns_time32_totext(when, &b);
1477         if (result != ISC_R_SUCCESS)
1478                 goto error;
1479
1480         isc_buffer_usedregion(&b, &r);
1481         fprintf(stream, "%s: %.*s (%.*s)\n", tag, (int)r.length, r.base,
1482                  (int)strlen(output) - 1, output);
1483         return;
1484
1485  error:
1486         fprintf(stream, "%s: (set, unable to display)\n", tag);
1487 }
1488
1489 /*%
1490  * Writes a public key to disk in DNS format.
1491  */
1492 static isc_result_t
1493 write_public_key(const dst_key_t *key, int type, const char *directory) {
1494         FILE *fp;
1495         isc_buffer_t keyb, textb, fileb, classb;
1496         isc_region_t r;
1497         char filename[ISC_DIR_NAMEMAX];
1498         unsigned char key_array[DST_KEY_MAXSIZE];
1499         char text_array[DST_KEY_MAXTEXTSIZE];
1500         char class_array[10];
1501         isc_result_t ret;
1502         dns_rdata_t rdata = DNS_RDATA_INIT;
1503         isc_fsaccess_t access;
1504
1505         REQUIRE(VALID_KEY(key));
1506
1507         isc_buffer_init(&keyb, key_array, sizeof(key_array));
1508         isc_buffer_init(&textb, text_array, sizeof(text_array));
1509         isc_buffer_init(&classb, class_array, sizeof(class_array));
1510
1511         ret = dst_key_todns(key, &keyb);
1512         if (ret != ISC_R_SUCCESS)
1513                 return (ret);
1514
1515         isc_buffer_usedregion(&keyb, &r);
1516         dns_rdata_fromregion(&rdata, key->key_class, dns_rdatatype_dnskey, &r);
1517
1518         ret = dns_rdata_totext(&rdata, (dns_name_t *) NULL, &textb);
1519         if (ret != ISC_R_SUCCESS)
1520                 return (DST_R_INVALIDPUBLICKEY);
1521
1522         ret = dns_rdataclass_totext(key->key_class, &classb);
1523         if (ret != ISC_R_SUCCESS)
1524                 return (DST_R_INVALIDPUBLICKEY);
1525
1526         /*
1527          * Make the filename.
1528          */
1529         isc_buffer_init(&fileb, filename, sizeof(filename));
1530         ret = dst_key_buildfilename(key, DST_TYPE_PUBLIC, directory, &fileb);
1531         if (ret != ISC_R_SUCCESS)
1532                 return (ret);
1533
1534         /*
1535          * Create public key file.
1536          */
1537         if ((fp = fopen(filename, "w")) == NULL)
1538                 return (DST_R_WRITEERROR);
1539
1540         if (issymmetric(key)) {
1541                 access = 0;
1542                 isc_fsaccess_add(ISC_FSACCESS_OWNER,
1543                                  ISC_FSACCESS_READ | ISC_FSACCESS_WRITE,
1544                                  &access);
1545                 (void)isc_fsaccess_set(filename, access);
1546         }
1547
1548         /* Write key information in comments */
1549         if ((type & DST_TYPE_KEY) == 0) {
1550                 fprintf(fp, "; This is a %s%s-signing key, keyid %d, for ",
1551                         (key->key_flags & DNS_KEYFLAG_REVOKE) != 0 ?
1552                                 "revoked " :
1553                                 "",
1554                         (key->key_flags & DNS_KEYFLAG_KSK) != 0 ?
1555                                 "key" :
1556                                 "zone",
1557                         key->key_id);
1558                 ret = dns_name_print(key->key_name, fp);
1559                 if (ret != ISC_R_SUCCESS) {
1560                         fclose(fp);
1561                         return (ret);
1562                 }
1563                 fputc('\n', fp);
1564
1565                 printtime(key, DST_TIME_CREATED, "; Created", fp);
1566                 printtime(key, DST_TIME_PUBLISH, "; Publish", fp);
1567                 printtime(key, DST_TIME_ACTIVATE, "; Activate", fp);
1568                 printtime(key, DST_TIME_REVOKE, "; Revoke", fp);
1569                 printtime(key, DST_TIME_INACTIVE, "; Inactive", fp);
1570                 printtime(key, DST_TIME_DELETE, "; Delete", fp);
1571         }
1572
1573         /* Now print the actual key */
1574         ret = dns_name_print(key->key_name, fp);
1575
1576         fprintf(fp, " ");
1577
1578         isc_buffer_usedregion(&classb, &r);
1579         if ((unsigned) fwrite(r.base, 1, r.length, fp) != r.length)
1580                ret = DST_R_WRITEERROR;
1581
1582         if ((type & DST_TYPE_KEY) != 0)
1583                 fprintf(fp, " KEY ");
1584         else
1585                 fprintf(fp, " DNSKEY ");
1586
1587         isc_buffer_usedregion(&textb, &r);
1588         if ((unsigned) fwrite(r.base, 1, r.length, fp) != r.length)
1589                ret = DST_R_WRITEERROR;
1590
1591         fputc('\n', fp);
1592         fflush(fp);
1593         if (ferror(fp))
1594                 ret = DST_R_WRITEERROR;
1595         fclose(fp);
1596
1597         return (ret);
1598 }
1599
1600 static isc_result_t
1601 buildfilename(dns_name_t *name, dns_keytag_t id,
1602               unsigned int alg, unsigned int type,
1603               const char *directory, isc_buffer_t *out)
1604 {
1605         const char *suffix = "";
1606         unsigned int len;
1607         isc_result_t result;
1608
1609         REQUIRE(out != NULL);
1610         if ((type & DST_TYPE_PRIVATE) != 0)
1611                 suffix = ".private";
1612         else if (type == DST_TYPE_PUBLIC)
1613                 suffix = ".key";
1614         if (directory != NULL) {
1615                 if (isc_buffer_availablelength(out) < strlen(directory))
1616                         return (ISC_R_NOSPACE);
1617                 isc_buffer_putstr(out, directory);
1618                 if (strlen(directory) > 0U &&
1619                     directory[strlen(directory) - 1] != '/')
1620                         isc_buffer_putstr(out, "/");
1621         }
1622         if (isc_buffer_availablelength(out) < 1)
1623                 return (ISC_R_NOSPACE);
1624         isc_buffer_putstr(out, "K");
1625         result = dns_name_tofilenametext(name, ISC_FALSE, out);
1626         if (result != ISC_R_SUCCESS)
1627                 return (result);
1628         len = 1 + 3 + 1 + 5 + strlen(suffix) + 1;
1629         if (isc_buffer_availablelength(out) < len)
1630                 return (ISC_R_NOSPACE);
1631         sprintf((char *) isc_buffer_used(out), "+%03d+%05d%s", alg, id,
1632                 suffix);
1633         isc_buffer_add(out, len);
1634
1635         return (ISC_R_SUCCESS);
1636 }
1637
1638 static isc_result_t
1639 computeid(dst_key_t *key) {
1640         isc_buffer_t dnsbuf;
1641         unsigned char dns_array[DST_KEY_MAXSIZE];
1642         isc_region_t r;
1643         isc_result_t ret;
1644
1645         isc_buffer_init(&dnsbuf, dns_array, sizeof(dns_array));
1646         ret = dst_key_todns(key, &dnsbuf);
1647         if (ret != ISC_R_SUCCESS)
1648                 return (ret);
1649
1650         isc_buffer_usedregion(&dnsbuf, &r);
1651         key->key_id = dst_region_computeid(&r, key->key_alg);
1652         key->key_rid = dst_region_computerid(&r, key->key_alg);
1653         return (ISC_R_SUCCESS);
1654 }
1655
1656 static isc_result_t
1657 frombuffer(dns_name_t *name, unsigned int alg, unsigned int flags,
1658            unsigned int protocol, dns_rdataclass_t rdclass,
1659            isc_buffer_t *source, isc_mem_t *mctx, dst_key_t **keyp)
1660 {
1661         dst_key_t *key;
1662         isc_result_t ret;
1663
1664         REQUIRE(dns_name_isabsolute(name));
1665         REQUIRE(source != NULL);
1666         REQUIRE(mctx != NULL);
1667         REQUIRE(keyp != NULL && *keyp == NULL);
1668
1669         key = get_key_struct(name, alg, flags, protocol, 0, rdclass, mctx);
1670         if (key == NULL)
1671                 return (ISC_R_NOMEMORY);
1672
1673         if (isc_buffer_remaininglength(source) > 0) {
1674                 ret = algorithm_status(alg);
1675                 if (ret != ISC_R_SUCCESS) {
1676                         dst_key_free(&key);
1677                         return (ret);
1678                 }
1679                 if (key->func->fromdns == NULL) {
1680                         dst_key_free(&key);
1681                         return (DST_R_UNSUPPORTEDALG);
1682                 }
1683
1684                 ret = key->func->fromdns(key, source);
1685                 if (ret != ISC_R_SUCCESS) {
1686                         dst_key_free(&key);
1687                         return (ret);
1688                 }
1689         }
1690
1691         *keyp = key;
1692         return (ISC_R_SUCCESS);
1693 }
1694
1695 static isc_result_t
1696 algorithm_status(unsigned int alg) {
1697         REQUIRE(dst_initialized == ISC_TRUE);
1698
1699         if (dst_algorithm_supported(alg))
1700                 return (ISC_R_SUCCESS);
1701 #ifndef OPENSSL
1702         if (alg == DST_ALG_RSAMD5 || alg == DST_ALG_RSASHA1 ||
1703             alg == DST_ALG_DSA || alg == DST_ALG_DH ||
1704             alg == DST_ALG_HMACMD5 || alg == DST_ALG_NSEC3DSA ||
1705             alg == DST_ALG_NSEC3RSASHA1 ||
1706             alg == DST_ALG_RSASHA256 || alg == DST_ALG_RSASHA512 ||
1707             alg == DST_ALG_ECCGOST ||
1708             alg == DST_ALG_ECDSA256 || alg == DST_ALG_ECDSA384)
1709                 return (DST_R_NOCRYPTO);
1710 #endif
1711         return (DST_R_UNSUPPORTEDALG);
1712 }
1713
1714 static isc_result_t
1715 addsuffix(char *filename, int len, const char *odirname,
1716           const char *ofilename, const char *suffix)
1717 {
1718         int olen = strlen(ofilename);
1719         int n;
1720
1721         if (olen > 1 && ofilename[olen - 1] == '.')
1722                 olen -= 1;
1723         else if (olen > 8 && strcmp(ofilename + olen - 8, ".private") == 0)
1724                 olen -= 8;
1725         else if (olen > 4 && strcmp(ofilename + olen - 4, ".key") == 0)
1726                 olen -= 4;
1727
1728         if (odirname == NULL)
1729                 n = snprintf(filename, len, "%.*s%s", olen, ofilename, suffix);
1730         else
1731                 n = snprintf(filename, len, "%s/%.*s%s",
1732                              odirname, olen, ofilename, suffix);
1733         if (n < 0)
1734                 return (ISC_R_FAILURE);
1735         if (n >= len)
1736                 return (ISC_R_NOSPACE);
1737         return (ISC_R_SUCCESS);
1738 }
1739
1740 isc_result_t
1741 dst__entropy_getdata(void *buf, unsigned int len, isc_boolean_t pseudo) {
1742 #ifdef BIND9
1743         unsigned int flags = dst_entropy_flags;
1744
1745         if (len == 0)
1746                 return (ISC_R_SUCCESS);
1747         if (pseudo)
1748                 flags &= ~ISC_ENTROPY_GOODONLY;
1749         else
1750                 flags |= ISC_ENTROPY_BLOCKING;
1751         return (isc_entropy_getdata(dst_entropy_pool, buf, len, NULL, flags));
1752 #else
1753         UNUSED(buf);
1754         UNUSED(len);
1755         UNUSED(pseudo);
1756
1757         return (ISC_R_NOTIMPLEMENTED);
1758 #endif
1759 }
1760
1761 unsigned int
1762 dst__entropy_status(void) {
1763 #ifdef BIND9
1764 #ifdef GSSAPI
1765         unsigned int flags = dst_entropy_flags;
1766         isc_result_t ret;
1767         unsigned char buf[32];
1768         static isc_boolean_t first = ISC_TRUE;
1769
1770         if (first) {
1771                 /* Someone believes RAND_status() initializes the PRNG */
1772                 flags &= ~ISC_ENTROPY_GOODONLY;
1773                 ret = isc_entropy_getdata(dst_entropy_pool, buf,
1774                                           sizeof(buf), NULL, flags);
1775                 INSIST(ret == ISC_R_SUCCESS);
1776                 isc_entropy_putdata(dst_entropy_pool, buf,
1777                                     sizeof(buf), 2 * sizeof(buf));
1778                 first = ISC_FALSE;
1779         }
1780 #endif
1781         return (isc_entropy_status(dst_entropy_pool));
1782 #else
1783         return (0);
1784 #endif
1785 }
1786
1787 isc_buffer_t *
1788 dst_key_tkeytoken(const dst_key_t *key) {
1789         REQUIRE(VALID_KEY(key));
1790         return (key->key_tkeytoken);
1791 }