Detect FPU by checking CPUID features.
[dragonfly.git] / contrib / bind-9.5.2 / lib / dns / dst_api.c
1 /*
2  * Portions Copyright (C) 2004-2009  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: dst_api.c,v 1.11.92.7 2009/07/29 23:55:00 each Exp $
35  */
36
37 /*! \file */
38
39 #include <config.h>
40
41 #include <stdlib.h>
42
43 #include <isc/buffer.h>
44 #include <isc/dir.h>
45 #include <isc/entropy.h>
46 #include <isc/fsaccess.h>
47 #include <isc/hmacsha.h>
48 #include <isc/lex.h>
49 #include <isc/mem.h>
50 #include <isc/once.h>
51 #include <isc/print.h>
52 #include <isc/random.h>
53 #include <isc/string.h>
54 #include <isc/time.h>
55 #include <isc/util.h>
56
57 #include <dns/fixedname.h>
58 #include <dns/keyvalues.h>
59 #include <dns/name.h>
60 #include <dns/rdata.h>
61 #include <dns/rdataclass.h>
62 #include <dns/ttl.h>
63 #include <dns/types.h>
64
65 #include <dst/result.h>
66
67 #include "dst_internal.h"
68
69 #define DST_AS_STR(t) ((t).value.as_textregion.base)
70
71 static dst_func_t *dst_t_func[DST_MAX_ALGS];
72 static isc_entropy_t *dst_entropy_pool = NULL;
73 static unsigned int dst_entropy_flags = 0;
74 static isc_boolean_t dst_initialized = ISC_FALSE;
75
76 void gss_log(int level, const char *fmt, ...) ISC_FORMAT_PRINTF(2, 3);
77
78 isc_mem_t *dst__memory_pool = NULL;
79
80 /*
81  * Static functions.
82  */
83 static dst_key_t *      get_key_struct(dns_name_t *name,
84                                        unsigned int alg,
85                                        unsigned int flags,
86                                        unsigned int protocol,
87                                        unsigned int bits,
88                                        dns_rdataclass_t rdclass,
89                                        isc_mem_t *mctx);
90 static isc_result_t     write_public_key(const dst_key_t *key, int type,
91                                          const char *directory);
92 static isc_result_t     buildfilename(dns_name_t *name,
93                                       dns_keytag_t id,
94                                       unsigned int alg,
95                                       unsigned int type,
96                                       const char *directory,
97                                       isc_buffer_t *out);
98 static isc_result_t     computeid(dst_key_t *key);
99 static isc_result_t     frombuffer(dns_name_t *name,
100                                    unsigned int alg,
101                                    unsigned int flags,
102                                    unsigned int protocol,
103                                    dns_rdataclass_t rdclass,
104                                    isc_buffer_t *source,
105                                    isc_mem_t *mctx,
106                                    dst_key_t **keyp);
107
108 static isc_result_t     algorithm_status(unsigned int alg);
109
110 static isc_result_t     addsuffix(char *filename, unsigned int len,
111                                   const char *ofilename, const char *suffix);
112
113 #define RETERR(x)                               \
114         do {                                    \
115                 result = (x);                   \
116                 if (result != ISC_R_SUCCESS)    \
117                         goto out;               \
118         } while (0)
119
120 #define CHECKALG(alg)                           \
121         do {                                    \
122                 isc_result_t _r;                \
123                 _r = algorithm_status(alg);     \
124                 if (_r != ISC_R_SUCCESS)        \
125                         return (_r);            \
126         } while (0);                            \
127
128 #ifdef OPENSSL
129 static void *
130 default_memalloc(void *arg, size_t size) {
131         UNUSED(arg);
132         if (size == 0U)
133                 size = 1;
134         return (malloc(size));
135 }
136
137 static void
138 default_memfree(void *arg, void *ptr) {
139         UNUSED(arg);
140         free(ptr);
141 }
142 #endif
143
144 isc_result_t
145 dst_lib_init(isc_mem_t *mctx, isc_entropy_t *ectx, unsigned int eflags) {
146         isc_result_t result;
147
148         REQUIRE(mctx != NULL && ectx != NULL);
149         REQUIRE(dst_initialized == ISC_FALSE);
150
151         dst__memory_pool = NULL;
152
153 #ifdef OPENSSL
154         UNUSED(mctx);
155         /*
156          * When using --with-openssl, there seems to be no good way of not
157          * leaking memory due to the openssl error handling mechanism.
158          * Avoid assertions by using a local memory context and not checking
159          * for leaks on exit.  Note: as there are leaks we cannot use
160          * ISC_MEMFLAG_INTERNAL as it will free up memory still being used
161          * by libcrypto.
162          */
163         result = isc_mem_createx2(0, 0, default_memalloc, default_memfree,
164                                   NULL, &dst__memory_pool, 0);
165         if (result != ISC_R_SUCCESS)
166                 return (result);
167         isc_mem_setname(dst__memory_pool, "dst", NULL);
168         isc_mem_setdestroycheck(dst__memory_pool, ISC_FALSE);
169 #else
170         isc_mem_attach(mctx, &dst__memory_pool);
171 #endif
172         isc_entropy_attach(ectx, &dst_entropy_pool);
173         dst_entropy_flags = eflags;
174
175         dst_result_register();
176
177         memset(dst_t_func, 0, sizeof(dst_t_func));
178         RETERR(dst__hmacmd5_init(&dst_t_func[DST_ALG_HMACMD5]));
179         RETERR(dst__hmacsha1_init(&dst_t_func[DST_ALG_HMACSHA1]));
180         RETERR(dst__hmacsha224_init(&dst_t_func[DST_ALG_HMACSHA224]));
181         RETERR(dst__hmacsha256_init(&dst_t_func[DST_ALG_HMACSHA256]));
182         RETERR(dst__hmacsha384_init(&dst_t_func[DST_ALG_HMACSHA384]));
183         RETERR(dst__hmacsha512_init(&dst_t_func[DST_ALG_HMACSHA512]));
184 #ifdef OPENSSL
185         RETERR(dst__openssl_init());
186         RETERR(dst__opensslrsa_init(&dst_t_func[DST_ALG_RSAMD5]));
187         RETERR(dst__opensslrsa_init(&dst_t_func[DST_ALG_RSASHA1]));
188 #ifdef HAVE_OPENSSL_DSA
189         RETERR(dst__openssldsa_init(&dst_t_func[DST_ALG_DSA]));
190 #endif
191         RETERR(dst__openssldh_init(&dst_t_func[DST_ALG_DH]));
192 #endif /* OPENSSL */
193 #ifdef GSSAPI
194         RETERR(dst__gssapi_init(&dst_t_func[DST_ALG_GSSAPI]));
195 #endif
196         dst_initialized = ISC_TRUE;
197         return (ISC_R_SUCCESS);
198
199  out:
200         dst_lib_destroy();
201         return (result);
202 }
203
204 void
205 dst_lib_destroy(void) {
206         int i;
207         RUNTIME_CHECK(dst_initialized == ISC_TRUE);
208         dst_initialized = ISC_FALSE;
209
210         for (i = 0; i < DST_MAX_ALGS; i++)
211                 if (dst_t_func[i] != NULL && dst_t_func[i]->cleanup != NULL)
212                         dst_t_func[i]->cleanup();
213 #ifdef OPENSSL
214         dst__openssl_destroy();
215 #endif
216         if (dst__memory_pool != NULL)
217                 isc_mem_detach(&dst__memory_pool);
218         if (dst_entropy_pool != NULL)
219                 isc_entropy_detach(&dst_entropy_pool);
220
221 }
222
223 isc_boolean_t
224 dst_algorithm_supported(unsigned int alg) {
225         REQUIRE(dst_initialized == ISC_TRUE);
226
227         if (alg >= DST_MAX_ALGS || dst_t_func[alg] == NULL)
228                 return (ISC_FALSE);
229         return (ISC_TRUE);
230 }
231
232 isc_result_t
233 dst_context_create(dst_key_t *key, isc_mem_t *mctx, dst_context_t **dctxp) {
234         dst_context_t *dctx;
235         isc_result_t result;
236
237         REQUIRE(dst_initialized == ISC_TRUE);
238         REQUIRE(VALID_KEY(key));
239         REQUIRE(mctx != NULL);
240         REQUIRE(dctxp != NULL && *dctxp == NULL);
241
242         if (key->func->createctx == NULL)
243                 return (DST_R_UNSUPPORTEDALG);
244         if (key->keydata.generic == NULL)
245                 return (DST_R_NULLKEY);
246
247         dctx = isc_mem_get(mctx, sizeof(dst_context_t));
248         if (dctx == NULL)
249                 return (ISC_R_NOMEMORY);
250         dctx->key = key;
251         dctx->mctx = mctx;
252         result = key->func->createctx(key, dctx);
253         if (result != ISC_R_SUCCESS) {
254                 isc_mem_put(mctx, dctx, sizeof(dst_context_t));
255                 return (result);
256         }
257         dctx->magic = CTX_MAGIC;
258         *dctxp = dctx;
259         return (ISC_R_SUCCESS);
260 }
261
262 void
263 dst_context_destroy(dst_context_t **dctxp) {
264         dst_context_t *dctx;
265
266         REQUIRE(dctxp != NULL && VALID_CTX(*dctxp));
267
268         dctx = *dctxp;
269         INSIST(dctx->key->func->destroyctx != NULL);
270         dctx->key->func->destroyctx(dctx);
271         dctx->magic = 0;
272         isc_mem_put(dctx->mctx, dctx, sizeof(dst_context_t));
273         *dctxp = NULL;
274 }
275
276 isc_result_t
277 dst_context_adddata(dst_context_t *dctx, const isc_region_t *data) {
278         REQUIRE(VALID_CTX(dctx));
279         REQUIRE(data != NULL);
280         INSIST(dctx->key->func->adddata != NULL);
281
282         return (dctx->key->func->adddata(dctx, data));
283 }
284
285 isc_result_t
286 dst_context_sign(dst_context_t *dctx, isc_buffer_t *sig) {
287         dst_key_t *key;
288
289         REQUIRE(VALID_CTX(dctx));
290         REQUIRE(sig != NULL);
291
292         key = dctx->key;
293         CHECKALG(key->key_alg);
294         if (key->keydata.generic == NULL)
295                 return (DST_R_NULLKEY);
296         if (key->func->sign == NULL)
297                 return (DST_R_NOTPRIVATEKEY);
298         if (key->func->isprivate == NULL ||
299             key->func->isprivate(key) == ISC_FALSE)
300                 return (DST_R_NOTPRIVATEKEY);
301
302         return (key->func->sign(dctx, sig));
303 }
304
305 isc_result_t
306 dst_context_verify(dst_context_t *dctx, isc_region_t *sig) {
307         REQUIRE(VALID_CTX(dctx));
308         REQUIRE(sig != NULL);
309
310         CHECKALG(dctx->key->key_alg);
311         if (dctx->key->keydata.generic == NULL)
312                 return (DST_R_NULLKEY);
313         if (dctx->key->func->verify == NULL)
314                 return (DST_R_NOTPUBLICKEY);
315
316         return (dctx->key->func->verify(dctx, sig));
317 }
318
319 isc_result_t
320 dst_key_computesecret(const dst_key_t *pub, const dst_key_t *priv,
321                       isc_buffer_t *secret)
322 {
323         REQUIRE(dst_initialized == ISC_TRUE);
324         REQUIRE(VALID_KEY(pub) && VALID_KEY(priv));
325         REQUIRE(secret != NULL);
326
327         CHECKALG(pub->key_alg);
328         CHECKALG(priv->key_alg);
329
330         if (pub->keydata.generic == NULL || priv->keydata.generic == NULL)
331                 return (DST_R_NULLKEY);
332
333         if (pub->key_alg != priv->key_alg ||
334             pub->func->computesecret == NULL ||
335             priv->func->computesecret == NULL)
336                 return (DST_R_KEYCANNOTCOMPUTESECRET);
337
338         if (dst_key_isprivate(priv) == ISC_FALSE)
339                 return (DST_R_NOTPRIVATEKEY);
340
341         return (pub->func->computesecret(pub, priv, secret));
342 }
343
344 isc_result_t
345 dst_key_tofile(const dst_key_t *key, int type, const char *directory) {
346         isc_result_t ret = ISC_R_SUCCESS;
347
348         REQUIRE(dst_initialized == ISC_TRUE);
349         REQUIRE(VALID_KEY(key));
350         REQUIRE((type & (DST_TYPE_PRIVATE | DST_TYPE_PUBLIC)) != 0);
351
352         CHECKALG(key->key_alg);
353
354         if (key->func->tofile == NULL)
355                 return (DST_R_UNSUPPORTEDALG);
356
357         if (type & DST_TYPE_PUBLIC) {
358                 ret = write_public_key(key, type, directory);
359                 if (ret != ISC_R_SUCCESS)
360                         return (ret);
361         }
362
363         if ((type & DST_TYPE_PRIVATE) &&
364             (key->key_flags & DNS_KEYFLAG_TYPEMASK) != DNS_KEYTYPE_NOKEY)
365                 return (key->func->tofile(key, directory));
366         else
367                 return (ISC_R_SUCCESS);
368 }
369
370 isc_result_t
371 dst_key_fromfile(dns_name_t *name, dns_keytag_t id,
372                  unsigned int alg, int type, const char *directory,
373                  isc_mem_t *mctx, dst_key_t **keyp)
374 {
375         char filename[ISC_DIR_NAMEMAX];
376         isc_buffer_t b;
377         dst_key_t *key;
378         isc_result_t result;
379
380         REQUIRE(dst_initialized == ISC_TRUE);
381         REQUIRE(dns_name_isabsolute(name));
382         REQUIRE((type & (DST_TYPE_PRIVATE | DST_TYPE_PUBLIC)) != 0);
383         REQUIRE(mctx != NULL);
384         REQUIRE(keyp != NULL && *keyp == NULL);
385
386         CHECKALG(alg);
387
388         isc_buffer_init(&b, filename, sizeof(filename));
389         result = buildfilename(name, id, alg, type, directory, &b);
390         if (result != ISC_R_SUCCESS)
391                 return (result);
392
393         key = NULL;
394         result = dst_key_fromnamedfile(filename, type, mctx, &key);
395         if (result != ISC_R_SUCCESS)
396                 return (result);
397
398         result = computeid(key);
399         if (result != ISC_R_SUCCESS) {
400                 dst_key_free(&key);
401                 return (result);
402         }
403
404         if (!dns_name_equal(name, key->key_name) || id != key->key_id ||
405             alg != key->key_alg) {
406                 dst_key_free(&key);
407                 return (DST_R_INVALIDPRIVATEKEY);
408         }
409         key->key_id = id;
410
411         *keyp = key;
412         return (ISC_R_SUCCESS);
413 }
414
415 isc_result_t
416 dst_key_fromnamedfile(const char *filename, int type, isc_mem_t *mctx,
417                       dst_key_t **keyp)
418 {
419         isc_result_t result;
420         dst_key_t *pubkey = NULL, *key = NULL;
421         dns_keytag_t id;
422         char *newfilename = NULL;
423         int newfilenamelen = 0;
424         isc_lex_t *lex = NULL;
425
426         REQUIRE(dst_initialized == ISC_TRUE);
427         REQUIRE(filename != NULL);
428         REQUIRE((type & (DST_TYPE_PRIVATE | DST_TYPE_PUBLIC)) != 0);
429         REQUIRE(mctx != NULL);
430         REQUIRE(keyp != NULL && *keyp == NULL);
431
432         newfilenamelen = strlen(filename) + 5;
433         newfilename = isc_mem_get(mctx, newfilenamelen);
434         if (newfilename == NULL)
435                 return (ISC_R_NOMEMORY);
436         result = addsuffix(newfilename, newfilenamelen, filename, ".key");
437         INSIST(result == ISC_R_SUCCESS);
438
439         result = dst_key_read_public(newfilename, type, mctx, &pubkey);
440         isc_mem_put(mctx, newfilename, newfilenamelen);
441         newfilename = NULL;
442         if (result != ISC_R_SUCCESS)
443                 return (result);
444
445         if ((type & (DST_TYPE_PRIVATE | DST_TYPE_PUBLIC)) == DST_TYPE_PUBLIC ||
446             (pubkey->key_flags & DNS_KEYFLAG_TYPEMASK) == DNS_KEYTYPE_NOKEY) {
447                 result = computeid(pubkey);
448                 if (result != ISC_R_SUCCESS) {
449                         dst_key_free(&pubkey);
450                         return (result);
451                 }
452
453                 *keyp = pubkey;
454                 return (ISC_R_SUCCESS);
455         }
456
457         result = algorithm_status(pubkey->key_alg);
458         if (result != ISC_R_SUCCESS) {
459                 dst_key_free(&pubkey);
460                 return (result);
461         }
462
463         key = get_key_struct(pubkey->key_name, pubkey->key_alg,
464                              pubkey->key_flags, pubkey->key_proto, 0,
465                              pubkey->key_class, mctx);
466         id = pubkey->key_id;
467         dst_key_free(&pubkey);
468
469         if (key == NULL)
470                 return (ISC_R_NOMEMORY);
471
472         if (key->func->parse == NULL)
473                 RETERR(DST_R_UNSUPPORTEDALG);
474
475         newfilenamelen = strlen(filename) + 9;
476         newfilename = isc_mem_get(mctx, newfilenamelen);
477         if (newfilename == NULL)
478                 RETERR(ISC_R_NOMEMORY);
479         result = addsuffix(newfilename, newfilenamelen, filename, ".private");
480         INSIST(result == ISC_R_SUCCESS);
481
482         RETERR(isc_lex_create(mctx, 1500, &lex));
483         RETERR(isc_lex_openfile(lex, newfilename));
484         isc_mem_put(mctx, newfilename, newfilenamelen);
485
486         RETERR(key->func->parse(key, lex));
487         isc_lex_destroy(&lex);
488
489         RETERR(computeid(key));
490
491         if (id != key->key_id)
492                 RETERR(DST_R_INVALIDPRIVATEKEY);
493
494         *keyp = key;
495         return (ISC_R_SUCCESS);
496  out:
497         if (newfilename != NULL)
498                 isc_mem_put(mctx, newfilename, newfilenamelen);
499         if (lex != NULL)
500                 isc_lex_destroy(&lex);
501         dst_key_free(&key);
502         return (result);
503 }
504
505 isc_result_t
506 dst_key_todns(const dst_key_t *key, isc_buffer_t *target) {
507         REQUIRE(dst_initialized == ISC_TRUE);
508         REQUIRE(VALID_KEY(key));
509         REQUIRE(target != NULL);
510
511         CHECKALG(key->key_alg);
512
513         if (key->func->todns == NULL)
514                 return (DST_R_UNSUPPORTEDALG);
515
516         if (isc_buffer_availablelength(target) < 4)
517                 return (ISC_R_NOSPACE);
518         isc_buffer_putuint16(target, (isc_uint16_t)(key->key_flags & 0xffff));
519         isc_buffer_putuint8(target, (isc_uint8_t)key->key_proto);
520         isc_buffer_putuint8(target, (isc_uint8_t)key->key_alg);
521
522         if (key->key_flags & DNS_KEYFLAG_EXTENDED) {
523                 if (isc_buffer_availablelength(target) < 2)
524                         return (ISC_R_NOSPACE);
525                 isc_buffer_putuint16(target,
526                                      (isc_uint16_t)((key->key_flags >> 16)
527                                                     & 0xffff));
528         }
529
530         if (key->keydata.generic == NULL) /*%< NULL KEY */
531                 return (ISC_R_SUCCESS);
532
533         return (key->func->todns(key, target));
534 }
535
536 isc_result_t
537 dst_key_fromdns(dns_name_t *name, dns_rdataclass_t rdclass,
538                 isc_buffer_t *source, isc_mem_t *mctx, dst_key_t **keyp)
539 {
540         isc_uint8_t alg, proto;
541         isc_uint32_t flags, extflags;
542         dst_key_t *key = NULL;
543         dns_keytag_t id;
544         isc_region_t r;
545         isc_result_t result;
546
547         REQUIRE(dst_initialized);
548
549         isc_buffer_remainingregion(source, &r);
550
551         if (isc_buffer_remaininglength(source) < 4)
552                 return (DST_R_INVALIDPUBLICKEY);
553         flags = isc_buffer_getuint16(source);
554         proto = isc_buffer_getuint8(source);
555         alg = isc_buffer_getuint8(source);
556
557         id = dst_region_computeid(&r, alg);
558
559         if (flags & DNS_KEYFLAG_EXTENDED) {
560                 if (isc_buffer_remaininglength(source) < 2)
561                         return (DST_R_INVALIDPUBLICKEY);
562                 extflags = isc_buffer_getuint16(source);
563                 flags |= (extflags << 16);
564         }
565
566         result = frombuffer(name, alg, flags, proto, rdclass, source,
567                             mctx, &key);
568         if (result != ISC_R_SUCCESS)
569                 return (result);
570         key->key_id = id;
571
572         *keyp = key;
573         return (ISC_R_SUCCESS);
574 }
575
576 isc_result_t
577 dst_key_frombuffer(dns_name_t *name, unsigned int alg,
578                    unsigned int flags, unsigned int protocol,
579                    dns_rdataclass_t rdclass,
580                    isc_buffer_t *source, isc_mem_t *mctx, dst_key_t **keyp)
581 {
582         dst_key_t *key = NULL;
583         isc_result_t result;
584
585         REQUIRE(dst_initialized);
586
587         result = frombuffer(name, alg, flags, protocol, rdclass, source,
588                             mctx, &key);
589         if (result != ISC_R_SUCCESS)
590                 return (result);
591
592         result = computeid(key);
593         if (result != ISC_R_SUCCESS) {
594                 dst_key_free(&key);
595                 return (result);
596         }
597
598         *keyp = key;
599         return (ISC_R_SUCCESS);
600 }
601
602 isc_result_t
603 dst_key_tobuffer(const dst_key_t *key, isc_buffer_t *target) {
604         REQUIRE(dst_initialized == ISC_TRUE);
605         REQUIRE(VALID_KEY(key));
606         REQUIRE(target != NULL);
607
608         CHECKALG(key->key_alg);
609
610         if (key->func->todns == NULL)
611                 return (DST_R_UNSUPPORTEDALG);
612
613         return (key->func->todns(key, target));
614 }
615
616 isc_result_t
617 dst_key_privatefrombuffer(dst_key_t *key, isc_buffer_t *buffer) {
618         isc_lex_t *lex = NULL;
619         isc_result_t result = ISC_R_SUCCESS;
620
621         REQUIRE(dst_initialized == ISC_TRUE);
622         REQUIRE(VALID_KEY(key));
623         REQUIRE(!dst_key_isprivate(key));
624         REQUIRE(buffer != NULL);
625
626         if (key->func->parse == NULL)
627                 RETERR(DST_R_UNSUPPORTEDALG);
628
629         RETERR(isc_lex_create(key->mctx, 1500, &lex));
630         RETERR(isc_lex_openbuffer(lex, buffer));
631         RETERR(key->func->parse(key, lex));
632  out:
633         if (lex != NULL)
634                 isc_lex_destroy(&lex);
635         return (result);
636 }
637
638 gss_ctx_id_t
639 dst_key_getgssctx(const dst_key_t *key)
640 {
641         REQUIRE(key != NULL);
642
643         return (key->keydata.gssctx);
644 }
645
646 isc_result_t
647 dst_key_fromgssapi(dns_name_t *name, gss_ctx_id_t gssctx, isc_mem_t *mctx,
648                    dst_key_t **keyp)
649 {
650         dst_key_t *key;
651
652         REQUIRE(gssctx != NULL);
653         REQUIRE(keyp != NULL && *keyp == NULL);
654
655         key = get_key_struct(name, DST_ALG_GSSAPI, 0, DNS_KEYPROTO_DNSSEC,
656                              0, dns_rdataclass_in, mctx);
657         if (key == NULL)
658                 return (ISC_R_NOMEMORY);
659
660         key->keydata.gssctx = gssctx;
661         *keyp = key;
662         return (ISC_R_SUCCESS);
663 }
664
665 isc_result_t
666 dst_key_generate(dns_name_t *name, unsigned int alg,
667                  unsigned int bits, unsigned int param,
668                  unsigned int flags, unsigned int protocol,
669                  dns_rdataclass_t rdclass,
670                  isc_mem_t *mctx, dst_key_t **keyp)
671 {
672         dst_key_t *key;
673         isc_result_t ret;
674
675         REQUIRE(dst_initialized == ISC_TRUE);
676         REQUIRE(dns_name_isabsolute(name));
677         REQUIRE(mctx != NULL);
678         REQUIRE(keyp != NULL && *keyp == NULL);
679
680         CHECKALG(alg);
681
682         key = get_key_struct(name, alg, flags, protocol, bits, rdclass, mctx);
683         if (key == NULL)
684                 return (ISC_R_NOMEMORY);
685
686         if (bits == 0) { /*%< NULL KEY */
687                 key->key_flags |= DNS_KEYTYPE_NOKEY;
688                 *keyp = key;
689                 return (ISC_R_SUCCESS);
690         }
691
692         if (key->func->generate == NULL) {
693                 dst_key_free(&key);
694                 return (DST_R_UNSUPPORTEDALG);
695         }
696
697         ret = key->func->generate(key, param);
698         if (ret != ISC_R_SUCCESS) {
699                 dst_key_free(&key);
700                 return (ret);
701         }
702
703         ret = computeid(key);
704         if (ret != ISC_R_SUCCESS) {
705                 dst_key_free(&key);
706                 return (ret);
707         }
708
709         *keyp = key;
710         return (ISC_R_SUCCESS);
711 }
712
713 isc_boolean_t
714 dst_key_compare(const dst_key_t *key1, const dst_key_t *key2) {
715         REQUIRE(dst_initialized == ISC_TRUE);
716         REQUIRE(VALID_KEY(key1));
717         REQUIRE(VALID_KEY(key2));
718
719         if (key1 == key2)
720                 return (ISC_TRUE);
721         if (key1 == NULL || key2 == NULL)
722                 return (ISC_FALSE);
723         if (key1->key_alg == key2->key_alg &&
724             key1->key_id == key2->key_id &&
725             key1->func->compare != NULL &&
726             key1->func->compare(key1, key2) == ISC_TRUE)
727                 return (ISC_TRUE);
728         else
729                 return (ISC_FALSE);
730 }
731
732 isc_boolean_t
733 dst_key_paramcompare(const dst_key_t *key1, const dst_key_t *key2) {
734         REQUIRE(dst_initialized == ISC_TRUE);
735         REQUIRE(VALID_KEY(key1));
736         REQUIRE(VALID_KEY(key2));
737
738         if (key1 == key2)
739                 return (ISC_TRUE);
740         if (key1 == NULL || key2 == NULL)
741                 return (ISC_FALSE);
742         if (key1->key_alg == key2->key_alg &&
743             key1->func->paramcompare != NULL &&
744             key1->func->paramcompare(key1, key2) == ISC_TRUE)
745                 return (ISC_TRUE);
746         else
747                 return (ISC_FALSE);
748 }
749
750 void
751 dst_key_free(dst_key_t **keyp) {
752         isc_mem_t *mctx;
753         dst_key_t *key;
754
755         REQUIRE(dst_initialized == ISC_TRUE);
756         REQUIRE(keyp != NULL && VALID_KEY(*keyp));
757
758         key = *keyp;
759         mctx = key->mctx;
760
761         if (key->keydata.generic != NULL) {
762                 INSIST(key->func->destroy != NULL);
763                 key->func->destroy(key);
764         }
765
766         dns_name_free(key->key_name, mctx);
767         isc_mem_put(mctx, key->key_name, sizeof(dns_name_t));
768         memset(key, 0, sizeof(dst_key_t));
769         isc_mem_put(mctx, key, sizeof(dst_key_t));
770         *keyp = NULL;
771 }
772
773 isc_boolean_t
774 dst_key_isprivate(const dst_key_t *key) {
775         REQUIRE(VALID_KEY(key));
776         INSIST(key->func->isprivate != NULL);
777         return (key->func->isprivate(key));
778 }
779
780 isc_result_t
781 dst_key_buildfilename(const dst_key_t *key, int type,
782                       const char *directory, isc_buffer_t *out) {
783
784         REQUIRE(VALID_KEY(key));
785         REQUIRE(type == DST_TYPE_PRIVATE || type == DST_TYPE_PUBLIC ||
786                 type == 0);
787
788         return (buildfilename(key->key_name, key->key_id, key->key_alg,
789                               type, directory, out));
790 }
791
792 isc_result_t
793 dst_key_sigsize(const dst_key_t *key, unsigned int *n) {
794         REQUIRE(dst_initialized == ISC_TRUE);
795         REQUIRE(VALID_KEY(key));
796         REQUIRE(n != NULL);
797
798         /* XXXVIX this switch statement is too sparse to gen a jump table. */
799         switch (key->key_alg) {
800         case DST_ALG_RSAMD5:
801         case DST_ALG_RSASHA1:
802                 *n = (key->key_size + 7) / 8;
803                 break;
804         case DST_ALG_DSA:
805                 *n = DNS_SIG_DSASIGSIZE;
806                 break;
807         case DST_ALG_HMACMD5:
808                 *n = 16;
809                 break;
810         case DST_ALG_HMACSHA1:
811                 *n = ISC_SHA1_DIGESTLENGTH;
812                 break;
813         case DST_ALG_HMACSHA224:
814                 *n = ISC_SHA224_DIGESTLENGTH;
815                 break;
816         case DST_ALG_HMACSHA256:
817                 *n = ISC_SHA256_DIGESTLENGTH;
818                 break;
819         case DST_ALG_HMACSHA384:
820                 *n = ISC_SHA384_DIGESTLENGTH;
821                 break;
822         case DST_ALG_HMACSHA512:
823                 *n = ISC_SHA512_DIGESTLENGTH;
824                 break;
825         case DST_ALG_GSSAPI:
826                 *n = 128; /*%< XXX */
827                 break;
828         case DST_ALG_DH:
829         default:
830                 return (DST_R_UNSUPPORTEDALG);
831         }
832         return (ISC_R_SUCCESS);
833 }
834
835 isc_result_t
836 dst_key_secretsize(const dst_key_t *key, unsigned int *n) {
837         REQUIRE(dst_initialized == ISC_TRUE);
838         REQUIRE(VALID_KEY(key));
839         REQUIRE(n != NULL);
840
841         if (key->key_alg == DST_ALG_DH)
842                 *n = (key->key_size + 7) / 8;
843         else
844                 return (DST_R_UNSUPPORTEDALG);
845         return (ISC_R_SUCCESS);
846 }
847
848 /***
849  *** Static methods
850  ***/
851
852 /*%
853  * Allocates a key structure and fills in some of the fields.
854  */
855 static dst_key_t *
856 get_key_struct(dns_name_t *name, unsigned int alg,
857                unsigned int flags, unsigned int protocol,
858                unsigned int bits, dns_rdataclass_t rdclass,
859                isc_mem_t *mctx)
860 {
861         dst_key_t *key;
862         isc_result_t result;
863
864         key = (dst_key_t *) isc_mem_get(mctx, sizeof(dst_key_t));
865         if (key == NULL)
866                 return (NULL);
867
868         memset(key, 0, sizeof(dst_key_t));
869         key->magic = KEY_MAGIC;
870
871         key->key_name = isc_mem_get(mctx, sizeof(dns_name_t));
872         if (key->key_name == NULL) {
873                 isc_mem_put(mctx, key, sizeof(dst_key_t));
874                 return (NULL);
875         }
876         dns_name_init(key->key_name, NULL);
877         result = dns_name_dup(name, mctx, key->key_name);
878         if (result != ISC_R_SUCCESS) {
879                 isc_mem_put(mctx, key->key_name, sizeof(dns_name_t));
880                 isc_mem_put(mctx, key, sizeof(dst_key_t));
881                 return (NULL);
882         }
883         key->key_alg = alg;
884         key->key_flags = flags;
885         key->key_proto = protocol;
886         key->mctx = mctx;
887         key->keydata.generic = NULL;
888         key->key_size = bits;
889         key->key_class = rdclass;
890         key->func = dst_t_func[alg];
891         return (key);
892 }
893
894 /*%
895  * Reads a public key from disk
896  */
897 isc_result_t
898 dst_key_read_public(const char *filename, int type,
899                     isc_mem_t *mctx, dst_key_t **keyp)
900 {
901         u_char rdatabuf[DST_KEY_MAXSIZE];
902         isc_buffer_t b;
903         dns_fixedname_t name;
904         isc_lex_t *lex = NULL;
905         isc_token_t token;
906         isc_result_t ret;
907         dns_rdata_t rdata = DNS_RDATA_INIT;
908         unsigned int opt = ISC_LEXOPT_DNSMULTILINE;
909         dns_rdataclass_t rdclass = dns_rdataclass_in;
910         isc_lexspecials_t specials;
911         isc_uint32_t ttl;
912         isc_result_t result;
913         dns_rdatatype_t keytype;
914
915         /*
916          * Open the file and read its formatted contents
917          * File format:
918          *    domain.name [ttl] [class] [KEY|DNSKEY] <flags> <protocol> <algorithm> <key>
919          */
920
921         /* 1500 should be large enough for any key */
922         ret = isc_lex_create(mctx, 1500, &lex);
923         if (ret != ISC_R_SUCCESS)
924                 goto cleanup;
925
926         memset(specials, 0, sizeof(specials));
927         specials['('] = 1;
928         specials[')'] = 1;
929         specials['"'] = 1;
930         isc_lex_setspecials(lex, specials);
931         isc_lex_setcomments(lex, ISC_LEXCOMMENT_DNSMASTERFILE);
932
933         ret = isc_lex_openfile(lex, filename);
934         if (ret != ISC_R_SUCCESS)
935                 goto cleanup;
936
937 #define NEXTTOKEN(lex, opt, token) { \
938         ret = isc_lex_gettoken(lex, opt, token); \
939         if (ret != ISC_R_SUCCESS) \
940                 goto cleanup; \
941         }
942
943 #define BADTOKEN() { \
944         ret = ISC_R_UNEXPECTEDTOKEN; \
945         goto cleanup; \
946         }
947
948         /* Read the domain name */
949         NEXTTOKEN(lex, opt, &token);
950         if (token.type != isc_tokentype_string)
951                 BADTOKEN();
952
953         /*
954          * We don't support "@" in .key files.
955          */
956         if (!strcmp(DST_AS_STR(token), "@"))
957                 BADTOKEN();
958
959         dns_fixedname_init(&name);
960         isc_buffer_init(&b, DST_AS_STR(token), strlen(DST_AS_STR(token)));
961         isc_buffer_add(&b, strlen(DST_AS_STR(token)));
962         ret = dns_name_fromtext(dns_fixedname_name(&name), &b, dns_rootname,
963                                 ISC_FALSE, NULL);
964         if (ret != ISC_R_SUCCESS)
965                 goto cleanup;
966
967         /* Read the next word: either TTL, class, or 'KEY' */
968         NEXTTOKEN(lex, opt, &token);
969
970         if (token.type != isc_tokentype_string)
971                 BADTOKEN();
972
973         /* If it's a TTL, read the next one */
974         result = dns_ttl_fromtext(&token.value.as_textregion, &ttl);
975         if (result == ISC_R_SUCCESS)
976                 NEXTTOKEN(lex, opt, &token);
977
978         if (token.type != isc_tokentype_string)
979                 BADTOKEN();
980
981         ret = dns_rdataclass_fromtext(&rdclass, &token.value.as_textregion);
982         if (ret == ISC_R_SUCCESS)
983                 NEXTTOKEN(lex, opt, &token);
984
985         if (token.type != isc_tokentype_string)
986                 BADTOKEN();
987
988         if (strcasecmp(DST_AS_STR(token), "DNSKEY") == 0)
989                 keytype = dns_rdatatype_dnskey;
990         else if (strcasecmp(DST_AS_STR(token), "KEY") == 0)
991                 keytype = dns_rdatatype_key; /*%< SIG(0), TKEY */
992         else
993                 BADTOKEN();
994
995         if (((type & DST_TYPE_KEY) != 0 && keytype != dns_rdatatype_key) ||
996             ((type & DST_TYPE_KEY) == 0 && keytype != dns_rdatatype_dnskey)) {
997                 ret = DST_R_BADKEYTYPE;
998                 goto cleanup;
999         }
1000
1001         isc_buffer_init(&b, rdatabuf, sizeof(rdatabuf));
1002         ret = dns_rdata_fromtext(&rdata, rdclass, keytype, lex, NULL,
1003                                  ISC_FALSE, mctx, &b, NULL);
1004         if (ret != ISC_R_SUCCESS)
1005                 goto cleanup;
1006
1007         ret = dst_key_fromdns(dns_fixedname_name(&name), rdclass, &b, mctx,
1008                               keyp);
1009         if (ret != ISC_R_SUCCESS)
1010                 goto cleanup;
1011
1012  cleanup:
1013         if (lex != NULL)
1014                 isc_lex_destroy(&lex);
1015         return (ret);
1016 }
1017
1018 static isc_boolean_t
1019 issymmetric(const dst_key_t *key) {
1020         REQUIRE(dst_initialized == ISC_TRUE);
1021         REQUIRE(VALID_KEY(key));
1022
1023         /* XXXVIX this switch statement is too sparse to gen a jump table. */
1024         switch (key->key_alg) {
1025         case DST_ALG_RSAMD5:
1026         case DST_ALG_RSASHA1:
1027         case DST_ALG_DSA:
1028         case DST_ALG_DH:
1029                 return (ISC_FALSE);
1030         case DST_ALG_HMACMD5:
1031         case DST_ALG_GSSAPI:
1032                 return (ISC_TRUE);
1033         default:
1034                 return (ISC_FALSE);
1035         }
1036 }
1037
1038 /*%
1039  * Writes a public key to disk in DNS format.
1040  */
1041 static isc_result_t
1042 write_public_key(const dst_key_t *key, int type, const char *directory) {
1043         FILE *fp;
1044         isc_buffer_t keyb, textb, fileb, classb;
1045         isc_region_t r;
1046         char filename[ISC_DIR_NAMEMAX];
1047         unsigned char key_array[DST_KEY_MAXSIZE];
1048         char text_array[DST_KEY_MAXTEXTSIZE];
1049         char class_array[10];
1050         isc_result_t ret;
1051         dns_rdata_t rdata = DNS_RDATA_INIT;
1052         isc_fsaccess_t access;
1053
1054         REQUIRE(VALID_KEY(key));
1055
1056         isc_buffer_init(&keyb, key_array, sizeof(key_array));
1057         isc_buffer_init(&textb, text_array, sizeof(text_array));
1058         isc_buffer_init(&classb, class_array, sizeof(class_array));
1059
1060         ret = dst_key_todns(key, &keyb);
1061         if (ret != ISC_R_SUCCESS)
1062                 return (ret);
1063
1064         isc_buffer_usedregion(&keyb, &r);
1065         dns_rdata_fromregion(&rdata, key->key_class, dns_rdatatype_dnskey, &r);
1066
1067         ret = dns_rdata_totext(&rdata, (dns_name_t *) NULL, &textb);
1068         if (ret != ISC_R_SUCCESS)
1069                 return (DST_R_INVALIDPUBLICKEY);
1070
1071         ret = dns_rdataclass_totext(key->key_class, &classb);
1072         if (ret != ISC_R_SUCCESS)
1073                 return (DST_R_INVALIDPUBLICKEY);
1074
1075         /*
1076          * Make the filename.
1077          */
1078         isc_buffer_init(&fileb, filename, sizeof(filename));
1079         ret = dst_key_buildfilename(key, DST_TYPE_PUBLIC, directory, &fileb);
1080         if (ret != ISC_R_SUCCESS)
1081                 return (ret);
1082
1083         /*
1084          * Create public key file.
1085          */
1086         if ((fp = fopen(filename, "w")) == NULL)
1087                 return (DST_R_WRITEERROR);
1088
1089         if (issymmetric(key)) {
1090                 access = 0;
1091                 isc_fsaccess_add(ISC_FSACCESS_OWNER,
1092                                  ISC_FSACCESS_READ | ISC_FSACCESS_WRITE,
1093                                  &access);
1094                 (void)isc_fsaccess_set(filename, access);
1095         }
1096
1097         ret = dns_name_print(key->key_name, fp);
1098         if (ret != ISC_R_SUCCESS) {
1099                 fclose(fp);
1100                 return (ret);
1101         }
1102
1103         fprintf(fp, " ");
1104
1105         isc_buffer_usedregion(&classb, &r);
1106         fwrite(r.base, 1, r.length, fp);
1107
1108         if ((type & DST_TYPE_KEY) != 0)
1109                 fprintf(fp, " KEY ");
1110         else
1111                 fprintf(fp, " DNSKEY ");
1112
1113         isc_buffer_usedregion(&textb, &r);
1114         fwrite(r.base, 1, r.length, fp);
1115
1116         fputc('\n', fp);
1117         fflush(fp);
1118         if (ferror(fp))
1119                 ret = DST_R_WRITEERROR;
1120         fclose(fp);
1121
1122         return (ret);
1123 }
1124
1125 static isc_result_t
1126 buildfilename(dns_name_t *name, dns_keytag_t id,
1127               unsigned int alg, unsigned int type,
1128               const char *directory, isc_buffer_t *out)
1129 {
1130         const char *suffix = "";
1131         unsigned int len;
1132         isc_result_t result;
1133
1134         REQUIRE(out != NULL);
1135         if ((type & DST_TYPE_PRIVATE) != 0)
1136                 suffix = ".private";
1137         else if (type == DST_TYPE_PUBLIC)
1138                 suffix = ".key";
1139         if (directory != NULL) {
1140                 if (isc_buffer_availablelength(out) < strlen(directory))
1141                         return (ISC_R_NOSPACE);
1142                 isc_buffer_putstr(out, directory);
1143                 if (strlen(directory) > 0U &&
1144                     directory[strlen(directory) - 1] != '/')
1145                         isc_buffer_putstr(out, "/");
1146         }
1147         if (isc_buffer_availablelength(out) < 1)
1148                 return (ISC_R_NOSPACE);
1149         isc_buffer_putstr(out, "K");
1150         result = dns_name_tofilenametext(name, ISC_FALSE, out);
1151         if (result != ISC_R_SUCCESS)
1152                 return (result);
1153         len = 1 + 3 + 1 + 5 + strlen(suffix) + 1;
1154         if (isc_buffer_availablelength(out) < len)
1155                 return (ISC_R_NOSPACE);
1156         sprintf((char *) isc_buffer_used(out), "+%03d+%05d%s", alg, id,
1157                 suffix);
1158         isc_buffer_add(out, len);
1159
1160         return (ISC_R_SUCCESS);
1161 }
1162
1163 static isc_result_t
1164 computeid(dst_key_t *key) {
1165         isc_buffer_t dnsbuf;
1166         unsigned char dns_array[DST_KEY_MAXSIZE];
1167         isc_region_t r;
1168         isc_result_t ret;
1169
1170         isc_buffer_init(&dnsbuf, dns_array, sizeof(dns_array));
1171         ret = dst_key_todns(key, &dnsbuf);
1172         if (ret != ISC_R_SUCCESS)
1173                 return (ret);
1174
1175         isc_buffer_usedregion(&dnsbuf, &r);
1176         key->key_id = dst_region_computeid(&r, key->key_alg);
1177         return (ISC_R_SUCCESS);
1178 }
1179
1180 static isc_result_t
1181 frombuffer(dns_name_t *name, unsigned int alg, unsigned int flags,
1182            unsigned int protocol, dns_rdataclass_t rdclass,
1183            isc_buffer_t *source, isc_mem_t *mctx, dst_key_t **keyp)
1184 {
1185         dst_key_t *key;
1186         isc_result_t ret;
1187
1188         REQUIRE(dns_name_isabsolute(name));
1189         REQUIRE(source != NULL);
1190         REQUIRE(mctx != NULL);
1191         REQUIRE(keyp != NULL && *keyp == NULL);
1192
1193         key = get_key_struct(name, alg, flags, protocol, 0, rdclass, mctx);
1194         if (key == NULL)
1195                 return (ISC_R_NOMEMORY);
1196
1197         if (isc_buffer_remaininglength(source) > 0) {
1198                 ret = algorithm_status(alg);
1199                 if (ret != ISC_R_SUCCESS) {
1200                         dst_key_free(&key);
1201                         return (ret);
1202                 }
1203                 if (key->func->fromdns == NULL) {
1204                         dst_key_free(&key);
1205                         return (DST_R_UNSUPPORTEDALG);
1206                 }
1207
1208                 ret = key->func->fromdns(key, source);
1209                 if (ret != ISC_R_SUCCESS) {
1210                         dst_key_free(&key);
1211                         return (ret);
1212                 }
1213         }
1214
1215         *keyp = key;
1216         return (ISC_R_SUCCESS);
1217 }
1218
1219 static isc_result_t
1220 algorithm_status(unsigned int alg) {
1221         REQUIRE(dst_initialized == ISC_TRUE);
1222
1223         if (dst_algorithm_supported(alg))
1224                 return (ISC_R_SUCCESS);
1225 #ifndef OPENSSL
1226         if (alg == DST_ALG_RSAMD5 || alg == DST_ALG_RSASHA1 ||
1227             alg == DST_ALG_DSA || alg == DST_ALG_DH ||
1228             alg == DST_ALG_HMACMD5)
1229                 return (DST_R_NOCRYPTO);
1230 #endif
1231         return (DST_R_UNSUPPORTEDALG);
1232 }
1233
1234 static isc_result_t
1235 addsuffix(char *filename, unsigned int len, const char *ofilename,
1236           const char *suffix)
1237 {
1238         int olen = strlen(ofilename);
1239         int n;
1240
1241         if (olen > 1 && ofilename[olen - 1] == '.')
1242                 olen -= 1;
1243         else if (olen > 8 && strcmp(ofilename + olen - 8, ".private") == 0)
1244                 olen -= 8;
1245         else if (olen > 4 && strcmp(ofilename + olen - 4, ".key") == 0)
1246                 olen -= 4;
1247
1248         n = snprintf(filename, len, "%.*s%s", olen, ofilename, suffix);
1249         if (n < 0)
1250                 return (ISC_R_NOSPACE);
1251         return (ISC_R_SUCCESS);
1252 }
1253
1254 isc_result_t
1255 dst__entropy_getdata(void *buf, unsigned int len, isc_boolean_t pseudo) {
1256         unsigned int flags = dst_entropy_flags;
1257         if (pseudo)
1258                 flags &= ~ISC_ENTROPY_GOODONLY;
1259         return (isc_entropy_getdata(dst_entropy_pool, buf, len, NULL, flags));
1260 }
1261
1262 unsigned int
1263 dst__entropy_status(void) {
1264         return (isc_entropy_status(dst_entropy_pool));
1265 }