1 /*        $NetBSD: dst_api.c,v 1.1.1.2 2012/09/09 16:07:47 christos Exp $       */
2 
3 #ifndef LINT
4 static const char rcsid[] = "Header: /proj/cvs/prod/libbind/dst/dst_api.c,v 1.17 2007/09/24 17:18:25 each Exp ";
5 #endif
6 
7 /*
8  * Portions Copyright (c) 1995-1998 by Trusted Information Systems, Inc.
9  *
10  * Permission to use, copy modify, and distribute this software for any
11  * purpose with or without fee is hereby granted, provided that the above
12  * copyright notice and this permission notice appear in all copies.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS" AND TRUSTED INFORMATION SYSTEMS
15  * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL
17  * TRUSTED INFORMATION SYSTEMS BE LIABLE FOR ANY SPECIAL, DIRECT,
18  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
19  * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
20  * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
21  * WITH THE USE OR PERFORMANCE OF THE SOFTWARE.
22  */
23 /*
24  * This file contains the interface between the DST API and the crypto API.
25  * This is the only file that needs to be changed if the crypto system is
26  * changed.  Exported functions are:
27  * void dst_init()   Initialize the toolkit
28  * int  dst_check_algorithm()   Function to determines if alg is suppored.
29  * int  dst_compare_keys()      Function to compare two keys for equality.
30  * int  dst_sign_data()         Incremental signing routine.
31  * int  dst_verify_data()       Incremental verify routine.
32  * int  dst_generate_key()      Function to generate new KEY
33  * DST_KEY *dst_read_key()      Function to retrieve private/public KEY.
34  * void dst_write_key()         Function to write out a key.
35  * DST_KEY *dst_dnskey_to_key() Function to convert DNS KEY RR to a DST
36  *                                      KEY structure.
37  * int dst_key_to_dnskey()    Function to return a public key in DNS
38  *                                      format binary
39  * DST_KEY *dst_buffer_to_key() Converst a data in buffer to KEY
40  * int *dst_key_to_buffer()   Writes out DST_KEY key matterial in buffer
41  * void dst_free_key()        Releases all memory referenced by key structure
42  */
43 
44 #include "port_before.h"
45 #include <stdio.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <stdlib.h>
49 #include <unistd.h>
50 #include <string.h>
51 #include <memory.h>
52 #include <ctype.h>
53 #include <time.h>
54 #include <sys/param.h>
55 #include <sys/stat.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <arpa/nameser.h>
59 #include <resolv.h>
60 
61 #include "dst_internal.h"
62 #include "port_after.h"
63 
64 /* static variables */
65 static int done_init = 0;
66 dst_func *dst_t_func[DST_MAX_ALGS];
67 const char *key_file_fmt_str = "Private-key-format: v%s\nAlgorithm: %d (%s)\n";
68 const char *dst_path = "";
69 
70 /* internal I/O functions */
71 static DST_KEY *dst_s_read_public_key(const char *in_name,
72                                               const u_int16_t in_id, int in_alg);
73 static int dst_s_read_private_key_file(char *name, DST_KEY *pk_key,
74                                                u_int16_t in_id, int in_alg);
75 static int dst_s_write_public_key(const DST_KEY *key);
76 static int dst_s_write_private_key(const DST_KEY *key);
77 
78 /* internal function to set up data structure */
79 static DST_KEY *dst_s_get_key_struct(const char *name, const int alg,
80                                              const int flags, const int protocol,
81                                              const int bits);
82 
83 /*%
84  *  dst_init
85  *        This function initializes the Digital Signature Toolkit.
86  *        Right now, it just checks the DSTKEYPATH environment variable.
87  *  Parameters
88  *        none
89  *  Returns
90  *        none
91  */
92 void
dst_init()93 dst_init()
94 {
95           char *s;
96           int len;
97 
98           if (done_init != 0)
99                     return;
100           done_init = 1;
101 
102           s = getenv("DSTKEYPATH");
103           len = 0;
104           if (s) {
105                     struct stat statbuf;
106 
107                     len = strlen(s);
108                     if (len > PATH_MAX) {
109                               EREPORT(("%s is longer than %d characters, ignoring\n",
110                                          s, PATH_MAX));
111                     } else if (stat(s, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode)) {
112                               EREPORT(("%s is not a valid directory\n", s));
113                     } else {
114                               char *tmp;
115                               tmp = (char *) malloc(len + 2);
116                               memcpy(tmp, s, len + 1);
117                               if (tmp[strlen(tmp) - 1] != '/') {
118                                         tmp[strlen(tmp) + 1] = 0;
119                                         tmp[strlen(tmp)] = '/';
120                               }
121                               dst_path = tmp;
122                     }
123           }
124           memset(dst_t_func, 0, sizeof(dst_t_func));
125           /* first one is selected */
126           dst_hmac_md5_init();
127 }
128 
129 /*%
130  *  dst_check_algorithm
131  *        This function determines if the crypto system for the specified
132  *        algorithm is present.
133  *  Parameters
134  *        alg     1       KEY_RSA
135  *                  3       KEY_DSA
136  *              157     KEY_HMAC_MD5
137  *                        future algorithms TBD and registered with IANA.
138  *  Returns
139  *        1 - The algorithm is available.
140  *        0 - The algorithm is not available.
141  */
142 int
dst_check_algorithm(const int alg)143 dst_check_algorithm(const int alg)
144 {
145           return (dst_t_func[alg] != NULL);
146 }
147 
148 /*%
149  * dst_s_get_key_struct
150  *        This function allocates key structure and fills in some of the
151  *        fields of the structure.
152  * Parameters:
153  *        name:     the name of the key
154  *        alg:      the algorithm number
155  *        flags:    the dns flags of the key
156  *        protocol: the dns protocol of the key
157  *        bits:     the size of the key
158  * Returns:
159  *       NULL if error
160  *       valid pointer otherwise
161  */
162 static DST_KEY *
dst_s_get_key_struct(const char * name,const int alg,const int flags,const int protocol,const int bits)163 dst_s_get_key_struct(const char *name, const int alg, const int flags,
164                          const int protocol, const int bits)
165 {
166           DST_KEY *new_key = NULL;
167 
168           if (dst_check_algorithm(alg)) /*%< make sure alg is available */
169                     new_key = (DST_KEY *) malloc(sizeof(*new_key));
170           if (new_key == NULL)
171                     return (NULL);
172 
173           memset(new_key, 0, sizeof(*new_key));
174           new_key->dk_key_name = strdup(name);
175           if (new_key->dk_key_name == NULL) {
176                     free(new_key);
177                     return (NULL);
178           }
179           new_key->dk_alg = alg;
180           new_key->dk_flags = flags;
181           new_key->dk_proto = protocol;
182           new_key->dk_KEY_struct = NULL;
183           new_key->dk_key_size = bits;
184           new_key->dk_func = dst_t_func[alg];
185           return (new_key);
186 }
187 
188 /*%
189  *  dst_compare_keys
190  *        Compares two keys for equality.
191  *  Parameters
192  *        key1, key2      Two keys to be compared.
193  *  Returns
194  *        0                The keys are equal.
195  *        non-zero  The keys are not equal.
196  */
197 
198 int
dst_compare_keys(const DST_KEY * key1,const DST_KEY * key2)199 dst_compare_keys(const DST_KEY *key1, const DST_KEY *key2)
200 {
201           if (key1 == key2)
202                     return (0);
203           if (key1 == NULL || key2 == NULL)
204                     return (4);
205           if (key1->dk_alg != key2->dk_alg)
206                     return (1);
207           if (key1->dk_key_size != key2->dk_key_size)
208                     return (2);
209           if (key1->dk_id != key2->dk_id)
210                     return (3);
211           return (key1->dk_func->compare(key1, key2));
212 }
213 
214 /*%
215  * dst_sign_data
216  *        An incremental signing function.  Data is signed in steps.
217  *        First the context must be initialized (SIG_MODE_INIT).
218  *        Then data is hashed (SIG_MODE_UPDATE).  Finally the signature
219  *        itself is created (SIG_MODE_FINAL).  This function can be called
220  *        once with INIT, UPDATE and FINAL modes all set, or it can be
221  *        called separately with a different mode set for each step.  The
222  *        UPDATE step can be repeated.
223  * Parameters
224  *        mode    A bit mask used to specify operation(s) to be performed.
225  *                    SIG_MODE_INIT        1   Initialize digest
226  *                    SIG_MODE_UPDATE    2   Add data to digest
227  *                    SIG_MODE_FINAL      4   Generate signature
228  *                                                      from signature
229  *                    SIG_MODE_ALL (SIG_MODE_INIT,SIG_MODE_UPDATE,SIG_MODE_FINAL
230  *        data    Data to be signed.
231  *        len     The length in bytes of data to be signed.
232  *        in_key  Contains a private key to sign with.
233  *                    KEY structures should be handled (created, converted,
234  *                    compared, stored, freed) by the DST.
235  *        signature
236  *              The location to which the signature will be written.
237  *        sig_len Length of the signature field in bytes.
238  * Return
239  *         0      Successfull INIT or Update operation
240  *        &gt;0      success FINAL (sign) operation
241  *        &lt;0      failure
242  */
243 
244 int
dst_sign_data(const int mode,DST_KEY * in_key,void ** context,const u_char * data,const int len,u_char * signature,const int sig_len)245 dst_sign_data(const int mode, DST_KEY *in_key, void **context,
246                 const u_char *data, const int len,
247                 u_char *signature, const int sig_len)
248 {
249           DUMP(data, mode, len, "dst_sign_data()");
250 
251           if (mode & SIG_MODE_FINAL &&
252               (in_key->dk_KEY_struct == NULL || signature == NULL))
253                     return (MISSING_KEY_OR_SIGNATURE);
254 
255           if (in_key->dk_func && in_key->dk_func->sign)
256                     return (in_key->dk_func->sign(mode, in_key, context, data, len,
257                                                         signature, sig_len));
258           return (UNKNOWN_KEYALG);
259 }
260 
261 /*%
262  *  dst_verify_data
263  *        An incremental verify function.  Data is verified in steps.
264  *        First the context must be initialized (SIG_MODE_INIT).
265  *        Then data is hashed (SIG_MODE_UPDATE).  Finally the signature
266  *        is verified (SIG_MODE_FINAL).  This function can be called
267  *        once with INIT, UPDATE and FINAL modes all set, or it can be
268  *        called separately with a different mode set for each step.  The
269  *        UPDATE step can be repeated.
270  *  Parameters
271  *        mode      Operations to perform this time.
272  *                        SIG_MODE_INIT       1   Initialize digest
273  *                        SIG_MODE_UPDATE     2   add data to digest
274  *                        SIG_MODE_FINAL      4   verify signature
275  *                        SIG_MODE_ALL
276  *                              (SIG_MODE_INIT,SIG_MODE_UPDATE,SIG_MODE_FINAL)
277  *        data      Data to pass through the hash function.
278  *        len        Length of the data in bytes.
279  *        in_key      Key for verification.
280  *        signature   Location of signature.
281  *        sig_len     Length of the signature in bytes.
282  *  Returns
283  *        0            Verify success
284  *        Non-Zero    Verify Failure
285  */
286 
287 int
dst_verify_data(const int mode,DST_KEY * in_key,void ** context,const u_char * data,const int len,const u_char * signature,const int sig_len)288 dst_verify_data(const int mode, DST_KEY *in_key, void **context,
289                     const u_char *data, const int len,
290                     const u_char *signature, const int sig_len)
291 {
292           DUMP(data, mode, len, "dst_verify_data()");
293           if (mode & SIG_MODE_FINAL &&
294               (in_key->dk_KEY_struct == NULL || signature == NULL))
295                     return (MISSING_KEY_OR_SIGNATURE);
296 
297           if (in_key->dk_func == NULL || in_key->dk_func->verify == NULL)
298                     return (UNSUPPORTED_KEYALG);
299           return (in_key->dk_func->verify(mode, in_key, context, data, len,
300                                                   signature, sig_len));
301 }
302 
303 /*%
304  *  dst_read_private_key
305  *        Access a private key.  First the list of private keys that have
306  *        already been read in is searched, then the key accessed on disk.
307  *        If the private key can be found, it is returned.  If the key cannot
308  *        be found, a null pointer is returned.  The options specify required
309  *        key characteristics.  If the private key requested does not have
310  *        these characteristics, it will not be read.
311  *  Parameters
312  *        in_keyname  The private key name.
313  *        in_id         The id of the private key.
314  *        options     DST_FORCE_READ  Read from disk - don't use a previously
315  *                                            read key.
316  *                    DST_CAN_SIGN    The key must be useable for signing.
317  *                    DST_NO_AUTHEN   The key must be useable for authentication.
318  *                    DST_STANDARD    Return any key
319  *  Returns
320  *        NULL      If there is no key found in the current directory or
321  *                        this key has not been loaded before.
322  *        !NULL       Success - KEY structure returned.
323  */
324 
325 DST_KEY *
dst_read_key(const char * in_keyname,const u_int16_t in_id,const int in_alg,const int type)326 dst_read_key(const char *in_keyname, const u_int16_t in_id,
327                const int in_alg, const int type)
328 {
329           char keyname[PATH_MAX];
330           DST_KEY *dg_key = NULL, *pubkey = NULL;
331 
332           if (!dst_check_algorithm(in_alg)) { /*%< make sure alg is available */
333                     EREPORT(("dst_read_private_key(): Algorithm %d not suppored\n",
334                                in_alg));
335                     return (NULL);
336           }
337           if ((type & (DST_PUBLIC | DST_PRIVATE)) == 0)
338                     return (NULL);
339           if (in_keyname == NULL) {
340                     EREPORT(("dst_read_private_key(): Null key name passed in\n"));
341                     return (NULL);
342           } else if (strlen(in_keyname) >= sizeof(keyname)) {
343                     EREPORT(("dst_read_private_key(): keyname too big\n"));
344                     return (NULL);
345           } else
346                     strcpy(keyname, in_keyname);
347 
348           /* before I read in the public key, check if it is allowed to sign */
349           if ((pubkey = dst_s_read_public_key(keyname, in_id, in_alg)) == NULL)
350                     return (NULL);
351 
352           if (type == DST_PUBLIC)
353                     return pubkey;
354 
355           if (!(dg_key = dst_s_get_key_struct(keyname, pubkey->dk_alg,
356                                                       pubkey->dk_flags, pubkey->dk_proto,
357                                                       0)))
358                     return (dg_key);
359           /* Fill in private key and some fields in the general key structure */
360           if (dst_s_read_private_key_file(keyname, dg_key, pubkey->dk_id,
361                                                   pubkey->dk_alg) == 0)
362                     dg_key = dst_free_key(dg_key);
363 
364           (void)dst_free_key(pubkey);
365           return (dg_key);
366 }
367 
368 int
dst_write_key(const DST_KEY * key,const int type)369 dst_write_key(const DST_KEY *key, const int type)
370 {
371           int pub = 0, priv = 0;
372 
373           if (key == NULL)
374                     return (0);
375           if (!dst_check_algorithm(key->dk_alg)) { /*%< make sure alg is available */
376                     EREPORT(("dst_write_key(): Algorithm %d not suppored\n",
377                                key->dk_alg));
378                     return (UNSUPPORTED_KEYALG);
379           }
380           if ((type & (DST_PRIVATE|DST_PUBLIC)) == 0)
381                     return (0);
382 
383           if (type & DST_PUBLIC)
384                     if ((pub = dst_s_write_public_key(key)) < 0)
385                               return (pub);
386           if (type & DST_PRIVATE)
387                     if ((priv = dst_s_write_private_key(key)) < 0)
388                               return (priv);
389           return (priv+pub);
390 }
391 
392 /*%
393  *  dst_write_private_key
394  *        Write a private key to disk.  The filename will be of the form:
395  *        K&lt;key-&gt;dk_name&gt;+&lt;key-&gt;dk_alg+&gt;&lt;key-d&gt;k_id.&gt;&lt;private key suffix&gt;.
396  *        If there is already a file with this name, an error is returned.
397  *
398  *  Parameters
399  *        key     A DST managed key structure that contains
400  *              all information needed about a key.
401  *  Return
402  *        &gt;= 0    Correct behavior.  Returns length of encoded key value
403  *                    written to disk.
404  *        &lt;  0    error.
405  */
406 
407 static int
dst_s_write_private_key(const DST_KEY * key)408 dst_s_write_private_key(const DST_KEY *key)
409 {
410           u_char encoded_block[RAW_KEY_SIZE];
411           char file[PATH_MAX];
412           int len;
413           FILE *fp;
414 
415           /* First encode the key into the portable key format */
416           if (key == NULL)
417                     return (-1);
418           if (key->dk_KEY_struct == NULL)
419                     return (0);         /*%< null key has no private key */
420           if (key->dk_func == NULL || key->dk_func->to_file_fmt == NULL) {
421                     EREPORT(("dst_write_private_key(): Unsupported operation %d\n",
422                                key->dk_alg));
423                     return (-5);
424           } else if ((len = key->dk_func->to_file_fmt(key, (char *)encoded_block,
425                                                        sizeof(encoded_block))) <= 0) {
426                     EREPORT(("dst_write_private_key(): Failed encoding private RSA bsafe key %d\n", len));
427                     return (-8);
428           }
429           /* Now I can create the file I want to use */
430           dst_s_build_filename(file, key->dk_key_name, key->dk_id, key->dk_alg,
431                                    PRIVATE_KEY, PATH_MAX);
432 
433           /* Do not overwrite an existing file */
434           if ((fp = dst_s_fopen(file, "w", 0600)) != NULL) {
435                     int nn;
436                     if ((nn = fwrite(encoded_block, 1, len, fp)) != len) {
437                               EREPORT(("dst_write_private_key(): Write failure on %s %d != %d errno=%d\n",
438                                          file, len, nn, errno));
439                               fclose(fp);
440                               return (-5);
441                     }
442                     fclose(fp);
443           } else {
444                     EREPORT(("dst_write_private_key(): Can not create file %s\n"
445                                ,file));
446                     return (-6);
447           }
448           memset(encoded_block, 0, len);
449           return (len);
450 }
451 
452 /*%
453 *
454  *  dst_read_public_key
455  *        Read a public key from disk and store in a DST key structure.
456  *  Parameters
457  *        in_name    K&lt;in_name&gt;&lt;in_id&gt;.&lt;public key suffix&gt; is the
458  *                        filename of the key file to be read.
459  *  Returns
460  *        NULL          If the key does not exist or no name is supplied.
461  *        NON-NULL  Initialized key structure if the key exists.
462  */
463 
464 static DST_KEY *
dst_s_read_public_key(const char * in_name,const u_int16_t in_id,int in_alg)465 dst_s_read_public_key(const char *in_name, const u_int16_t in_id, int in_alg)
466 {
467           int flags, proto, alg, len, dlen;
468           int c;
469           char name[PATH_MAX], enckey[RAW_KEY_SIZE], *notspace;
470           u_char deckey[RAW_KEY_SIZE];
471           FILE *fp;
472 
473           if (in_name == NULL) {
474                     EREPORT(("dst_read_public_key(): No key name given\n"));
475                     return (NULL);
476           }
477           if (dst_s_build_filename(name, in_name, in_id, in_alg, PUBLIC_KEY,
478                                          PATH_MAX) == -1) {
479                     EREPORT(("dst_read_public_key(): Cannot make filename from %s, %d, and %s\n",
480                                in_name, in_id, PUBLIC_KEY));
481                     return (NULL);
482           }
483           /*
484            * Open the file and read it's formatted contents up to key
485            * File format:
486            *    domain.name [ttl] [IN] KEY  &lt;flags&gt; &lt;protocol&gt; &lt;algorithm&gt; &lt;key&gt;
487            * flags, proto, alg stored as decimal (or hex numbers FIXME).
488            * (FIXME: handle parentheses for line continuation.)
489            */
490           if ((fp = dst_s_fopen(name, "r", 0)) == NULL) {
491                     EREPORT(("dst_read_public_key(): Public Key not found %s\n",
492                                name));
493                     return (NULL);
494           }
495           /* Skip domain name, which ends at first blank */
496           while ((c = getc(fp)) != EOF)
497                     if (isspace(c))
498                               break;
499           /* Skip blank to get to next field */
500           while ((c = getc(fp)) != EOF)
501                     if (!isspace(c))
502                               break;
503 
504           /* Skip optional TTL -- if initial digit, skip whole word. */
505           if (isdigit(c)) {
506                     while ((c = getc(fp)) != EOF)
507                               if (isspace(c))
508                                         break;
509                     while ((c = getc(fp)) != EOF)
510                               if (!isspace(c))
511                                         break;
512           }
513           /* Skip optional "IN" */
514           if (c == 'I' || c == 'i') {
515                     while ((c = getc(fp)) != EOF)
516                               if (isspace(c))
517                                         break;
518                     while ((c = getc(fp)) != EOF)
519                               if (!isspace(c))
520                                         break;
521           }
522           /* Locate and skip "KEY" */
523           if (c != 'K' && c != 'k') {
524                     EREPORT(("\"KEY\" doesn't appear in file: %s", name));
525                     return NULL;
526           }
527           while ((c = getc(fp)) != EOF)
528                     if (isspace(c))
529                               break;
530           while ((c = getc(fp)) != EOF)
531                     if (!isspace(c))
532                               break;
533           ungetc(c, fp);                /*%< return the charcter to the input field */
534           /* Handle hex!! FIXME.  */
535 
536           if (fscanf(fp, "%d %d %d", &flags, &proto, &alg) != 3) {
537                     EREPORT(("dst_read_public_key(): Can not read flag/proto/alg field from %s\n"
538                                ,name));
539                     return (NULL);
540           }
541           /* read in the key string */
542           fgets(enckey, sizeof(enckey), fp);
543 
544           /* If we aren't at end-of-file, something is wrong.  */
545           while ((c = getc(fp)) != EOF)
546                     if (!isspace(c))
547                               break;
548           if (!feof(fp)) {
549                     EREPORT(("Key too long in file: %s", name));
550                     return NULL;
551           }
552           fclose(fp);
553 
554           if ((len = strlen(enckey)) <= 0)
555                     return (NULL);
556 
557           /* discard \n */
558           enckey[--len] = '\0';
559 
560           /* remove leading spaces */
561           for (notspace = (char *) enckey; isspace((*notspace)&0xff); len--)
562                     notspace++;
563 
564           dlen = b64_pton(notspace, deckey, sizeof(deckey));
565           if (dlen < 0) {
566                     EREPORT(("dst_read_public_key: bad return from b64_pton = %d",
567                                dlen));
568                     return (NULL);
569           }
570           /* store key and info in a key structure that is returned */
571 /*        return dst_store_public_key(in_name, alg, proto, 666, flags, deckey,
572                                             dlen);*/
573           return dst_buffer_to_key(in_name, alg, flags, proto, deckey, dlen);
574 }
575 
576 /*%
577  *  dst_write_public_key
578  *        Write a key to disk in DNS format.
579  *  Parameters
580  *        key     Pointer to a DST key structure.
581  *  Returns
582  *        0       Failure
583  *        1       Success
584  */
585 
586 static int
dst_s_write_public_key(const DST_KEY * key)587 dst_s_write_public_key(const DST_KEY *key)
588 {
589           FILE *fp;
590           char filename[PATH_MAX];
591           u_char out_key[RAW_KEY_SIZE];
592           char enc_key[RAW_KEY_SIZE];
593           int len = 0;
594           int mode;
595 
596           memset(out_key, 0, sizeof(out_key));
597           if (key == NULL) {
598                     EREPORT(("dst_write_public_key(): No key specified \n"));
599                     return (0);
600           } else if ((len = dst_key_to_dnskey(key, out_key, sizeof(out_key)))< 0)
601                     return (0);
602 
603           /* Make the filename */
604           if (dst_s_build_filename(filename, key->dk_key_name, key->dk_id,
605                                          key->dk_alg, PUBLIC_KEY, PATH_MAX) == -1) {
606                     EREPORT(("dst_write_public_key(): Cannot make filename from %s, %d, and %s\n",
607                                key->dk_key_name, key->dk_id, PUBLIC_KEY));
608                     return (0);
609           }
610           /* XXX in general this should be a check for symmetric keys */
611           mode = (key->dk_alg == KEY_HMAC_MD5) ? 0600 : 0644;
612           /* create public key file */
613           if ((fp = dst_s_fopen(filename, "w+", mode)) == NULL) {
614                     EREPORT(("DST_write_public_key: open of file:%s failed (errno=%d)\n",
615                                filename, errno));
616                     return (0);
617           }
618           /*write out key first base64 the key data */
619           if (key->dk_flags & DST_EXTEND_FLAG)
620                     b64_ntop(&out_key[6], len - 6, enc_key, sizeof(enc_key));
621           else
622                     b64_ntop(&out_key[4], len - 4, enc_key, sizeof(enc_key));
623           fprintf(fp, "%s IN KEY %d %d %d %s\n",
624                     key->dk_key_name,
625                     key->dk_flags, key->dk_proto, key->dk_alg, enc_key);
626           fclose(fp);
627           return (1);
628 }
629 
630 /*%
631  *  dst_dnskey_to_public_key
632  *        This function converts the contents of a DNS KEY RR into a DST
633  *        key structure.
634  *  Paramters
635  *        len        Length of the RDATA of the KEY RR RDATA
636  *        rdata      A pointer to the the KEY RR RDATA.
637  *        in_name     Key name to be stored in key structure.
638  *  Returns
639  *        NULL          Failure
640  *        NON-NULL  Success.  Pointer to key structure.
641  *                            Caller's responsibility to free() it.
642  */
643 
644 DST_KEY *
dst_dnskey_to_key(const char * in_name,const u_char * rdata,const int len)645 dst_dnskey_to_key(const char *in_name, const u_char *rdata, const int len)
646 {
647           DST_KEY *key_st;
648           int alg ;
649           int start = DST_KEY_START;
650 
651           if (rdata == NULL || len <= DST_KEY_ALG) /*%< no data */
652                     return (NULL);
653           alg = (u_int8_t) rdata[DST_KEY_ALG];
654           if (!dst_check_algorithm(alg)) { /*%< make sure alg is available */
655                     EREPORT(("dst_dnskey_to_key(): Algorithm %d not suppored\n",
656                                alg));
657                     return (NULL);
658           }
659 
660           if (in_name == NULL)
661                     return (NULL);
662 
663           if ((key_st = dst_s_get_key_struct(in_name, alg, 0, 0, 0)) == NULL)
664                     return (NULL);
665 
666           key_st->dk_id = dst_s_dns_key_id(rdata, len);
667           key_st->dk_flags = dst_s_get_int16(rdata);
668           key_st->dk_proto = (u_int16_t) rdata[DST_KEY_PROT];
669           if (key_st->dk_flags & DST_EXTEND_FLAG) {
670                     u_int32_t ext_flags;
671                     ext_flags = (u_int32_t) dst_s_get_int16(&rdata[DST_EXT_FLAG]);
672                     key_st->dk_flags = key_st->dk_flags | (ext_flags << 16);
673                     start += 2;
674           }
675           /*
676            * now point to the begining of the data representing the encoding
677            * of the key
678            */
679           if (key_st->dk_func && key_st->dk_func->from_dns_key) {
680                     if (key_st->dk_func->from_dns_key(key_st, &rdata[start],
681                                                               len - start) > 0)
682                               return (key_st);
683           } else
684                     EREPORT(("dst_dnskey_to_public_key(): unsuppored alg %d\n",
685                                alg));
686 
687           SAFE_FREE(key_st);
688           return (key_st);
689 }
690 
691 /*%
692  *  dst_public_key_to_dnskey
693  *        Function to encode a public key into DNS KEY wire format
694  *  Parameters
695  *        key            Key structure to encode.
696  *        out_storage     Location to write the encoded key to.
697  *        out_len    Size of the output array.
698  *  Returns
699  *        <0      Failure
700  *        >=0     Number of bytes written to out_storage
701  */
702 
703 int
dst_key_to_dnskey(const DST_KEY * key,u_char * out_storage,const int out_len)704 dst_key_to_dnskey(const DST_KEY *key, u_char *out_storage,
705                                const int out_len)
706 {
707           u_int16_t val;
708           int loc = 0;
709           int enc_len = 0;
710           if (key == NULL)
711                     return (-1);
712 
713           if (!dst_check_algorithm(key->dk_alg)) { /*%< make sure alg is available */
714                     EREPORT(("dst_key_to_dnskey(): Algorithm %d not suppored\n",
715                                key->dk_alg));
716                     return (UNSUPPORTED_KEYALG);
717           }
718           memset(out_storage, 0, out_len);
719           val = (u_int16_t)(key->dk_flags & 0xffff);
720           dst_s_put_int16(out_storage, val);
721           loc += 2;
722 
723           out_storage[loc++] = (u_char) key->dk_proto;
724           out_storage[loc++] = (u_char) key->dk_alg;
725 
726           if (key->dk_flags > 0xffff) { /*%< Extended flags */
727                     val = (u_int16_t)((key->dk_flags >> 16) & 0xffff);
728                     dst_s_put_int16(&out_storage[loc], val);
729                     loc += 2;
730           }
731           if (key->dk_KEY_struct == NULL)
732                     return (loc);
733           if (key->dk_func && key->dk_func->to_dns_key) {
734                     enc_len = key->dk_func->to_dns_key(key,
735                                                              (u_char *) &out_storage[loc],
736                                                                out_len - loc);
737                     if (enc_len > 0)
738                               return (enc_len + loc);
739                     else
740                               return (-1);
741           } else
742                     EREPORT(("dst_key_to_dnskey(): Unsupported ALG %d\n",
743                                key->dk_alg));
744           return (-1);
745 }
746 
747 /*%
748  *  dst_buffer_to_key
749  *        Function to encode a string of raw data into a DST key
750  *  Parameters
751  *        alg                 The algorithm (HMAC only)
752  *        key                 A pointer to the data
753  *        keylen              The length of the data
754  *  Returns
755  *        NULL          an error occurred
756  *        NON-NULL  the DST key
757  */
758 DST_KEY *
dst_buffer_to_key(const char * key_name,const int alg,const int flags,const int protocol,const u_char * key_buf,const int key_len)759 dst_buffer_to_key(const char *key_name,           /*!< name of the key  */
760                       const int alg,              /*!< algorithm  */
761                       const int flags,            /*!< dns flags  */
762                       const int protocol,                   /*!< dns protocol  */
763                       const u_char *key_buf,      /*!< key in dns wire fmt  */
764                       const int key_len)                    /*!< size of key  */
765 {
766 
767           DST_KEY *dkey = NULL;
768           int dnslen;
769           u_char dns[2048];
770 
771           if (!dst_check_algorithm(alg)) { /*%< make sure alg is available */
772                     EREPORT(("dst_buffer_to_key(): Algorithm %d not suppored\n", alg));
773                     return (NULL);
774           }
775 
776           dkey = dst_s_get_key_struct(key_name, alg, flags, protocol, -1);
777 
778           if (dkey == NULL || dkey->dk_func == NULL ||
779               dkey->dk_func->from_dns_key == NULL)
780                     return (dst_free_key(dkey));
781 
782           if (dkey->dk_func->from_dns_key(dkey, key_buf, key_len) < 0) {
783                     EREPORT(("dst_buffer_to_key(): dst_buffer_to_hmac failed\n"));
784                     return (dst_free_key(dkey));
785           }
786 
787           dnslen = dst_key_to_dnskey(dkey, dns, sizeof(dns));
788           dkey->dk_id = dst_s_dns_key_id(dns, dnslen);
789           return (dkey);
790 }
791 
792 int
dst_key_to_buffer(DST_KEY * key,u_char * out_buff,int buf_len)793 dst_key_to_buffer(DST_KEY *key, u_char *out_buff, int buf_len)
794 {
795           int len;
796   /* this function will extrac the secret of HMAC into a buffer */
797           if (key == NULL)
798                     return (0);
799           if (key->dk_func != NULL && key->dk_func->to_dns_key != NULL) {
800                     len = key->dk_func->to_dns_key(key, out_buff, buf_len);
801                     if (len < 0)
802                               return (0);
803                     return (len);
804           }
805           return (0);
806 }
807 
808 /*%
809  * dst_s_read_private_key_file
810  *     Function reads in private key from a file.
811  *     Fills out the KEY structure.
812  * Parameters
813  *     name    Name of the key to be read.
814  *     pk_key  Structure that the key is returned in.
815  *     in_id   Key identifier (tag)
816  * Return
817  *     1 if everthing works
818  *     0 if there is any problem
819  */
820 
821 static int
dst_s_read_private_key_file(char * name,DST_KEY * pk_key,u_int16_t in_id,int in_alg)822 dst_s_read_private_key_file(char *name, DST_KEY *pk_key, u_int16_t in_id,
823                                   int in_alg)
824 {
825           int cnt, alg, len, major, minor, file_major, file_minor;
826           int ret, id;
827           char filename[PATH_MAX];
828           u_char in_buff[RAW_KEY_SIZE], *p;
829           FILE *fp;
830           int dnslen;
831           u_char dns[2048];
832 
833           if (name == NULL || pk_key == NULL) {
834                     EREPORT(("dst_read_private_key_file(): No key name given\n"));
835                     return (0);
836           }
837           /* Make the filename */
838           if (dst_s_build_filename(filename, name, in_id, in_alg, PRIVATE_KEY,
839                                          PATH_MAX) == -1) {
840                     EREPORT(("dst_read_private_key(): Cannot make filename from %s, %d, and %s\n",
841                                name, in_id, PRIVATE_KEY));
842                     return (0);
843           }
844           /* first check if we can find the key file */
845           if ((fp = dst_s_fopen(filename, "r", 0)) == NULL) {
846                     EREPORT(("dst_s_read_private_key_file: Could not open file %s in directory %s\n",
847                                filename, dst_path[0] ? dst_path :
848                                (char *) getcwd(NULL, PATH_MAX - 1)));
849                     return (0);
850           }
851           /* now read the header info from the file */
852           if ((cnt = fread(in_buff, 1, sizeof(in_buff), fp)) < 5) {
853                     fclose(fp);
854                     EREPORT(("dst_s_read_private_key_file: error reading file %s (empty file)\n",
855                                filename));
856                     return (0);
857           }
858           /* decrypt key */
859           fclose(fp);
860           if (memcmp(in_buff, "Private-key-format: v", 20) != 0)
861                     goto fail;
862           len = cnt;
863           p = in_buff;
864 
865           if (!dst_s_verify_str((const char **) (void *)&p,
866                                      "Private-key-format: v")) {
867                     EREPORT(("dst_s_read_private_key_file(): Not a Key file/Decrypt failed %s\n", name));
868                     goto fail;
869           }
870           /* read in file format */
871           sscanf((char *)p, "%d.%d", &file_major, &file_minor);
872           sscanf(KEY_FILE_FORMAT, "%d.%d", &major, &minor);
873           if (file_major < 1) {
874                     EREPORT(("dst_s_read_private_key_file(): Unknown keyfile %d.%d version for %s\n",
875                                file_major, file_minor, name));
876                     goto fail;
877           } else if (file_major > major || file_minor > minor)
878                     EREPORT((
879                                         "dst_s_read_private_key_file(): Keyfile %s version higher than mine %d.%d MAY FAIL\n",
880                                         name, file_major, file_minor));
881 
882           while (*p++ != '\n') ;        /*%< skip to end of line */
883 
884           if (!dst_s_verify_str((const char **) (void *)&p, "Algorithm: "))
885                     goto fail;
886 
887           if (sscanf((char *)p, "%d", &alg) != 1)
888                     goto fail;
889           while (*p++ != '\n') ;        /*%< skip to end of line */
890 
891           if (pk_key->dk_key_name && !strcmp(pk_key->dk_key_name, name))
892                     SAFE_FREE2(pk_key->dk_key_name, strlen(pk_key->dk_key_name));
893           pk_key->dk_key_name = (char *) strdup(name);
894 
895           /* allocate and fill in key structure */
896           if (pk_key->dk_func == NULL || pk_key->dk_func->from_file_fmt == NULL)
897                     goto fail;
898 
899           ret = pk_key->dk_func->from_file_fmt(pk_key, (char *)p, &in_buff[len] - p);
900           if (ret < 0)
901                     goto fail;
902 
903           dnslen = dst_key_to_dnskey(pk_key, dns, sizeof(dns));
904           id = dst_s_dns_key_id(dns, dnslen);
905 
906           /* Make sure the actual key tag matches the input tag used in the filename
907            */
908           if (id != in_id) {
909                     EREPORT(("dst_s_read_private_key_file(): actual tag of key read %d != input tag used to build filename %d.\n", id, in_id));
910                     goto fail;
911           }
912           pk_key->dk_id = (u_int16_t) id;
913           pk_key->dk_alg = alg;
914           memset(in_buff, 0, cnt);
915           return (1);
916 
917  fail:
918           memset(in_buff, 0, cnt);
919           return (0);
920 }
921 
922 /*%
923  *        Generate and store a public/private keypair.
924  *        Keys will be stored in formatted files.
925  *
926  *  Parameters
927  &
928  *\par    name    Name of the new key.  Used to create key files
929  *\li                 K&lt;name&gt;+&lt;alg&gt;+&lt;id&gt;.public and K&lt;name&gt;+&lt;alg&gt;+&lt;id&gt;.private.
930  *\par    bits    Size of the new key in bits.
931  *\par    exp     What exponent to use:
932  *\li                 0          use exponent 3
933  *\li                 non-zero    use Fermant4
934  *\par    flags   The default value of the DNS Key flags.
935  *\li                 The DNS Key RR Flag field is defined in RFC2065,
936  *                    section 3.3.  The field has 16 bits.
937  *\par    protocol
938  *\li           Default value of the DNS Key protocol field.
939  *\li                 The DNS Key protocol field is defined in RFC2065,
940  *                    section 3.4.  The field has 8 bits.
941  *\par    alg     What algorithm to use.  Currently defined:
942  *\li                 KEY_RSA       1
943  *\li                 KEY_DSA       3
944  *\li                 KEY_HMAC    157
945  *\par    out_id The key tag is returned.
946  *
947  *  Return
948  *\li     NULL                Failure
949  *\li     non-NULL  the generated key pair
950  *                            Caller frees the result, and its dk_name pointer.
951  */
952 DST_KEY *
dst_generate_key(const char * name,const int bits,const int exp,const int flags,const int protocol,const int alg)953 dst_generate_key(const char *name, const int bits, const int exp,
954                      const int flags, const int protocol, const int alg)
955 {
956           DST_KEY *new_key = NULL;
957           int dnslen;
958           u_char dns[2048];
959 
960           if (name == NULL)
961                     return (NULL);
962 
963           if (!dst_check_algorithm(alg)) { /*%< make sure alg is available */
964                     EREPORT(("dst_generate_key(): Algorithm %d not suppored\n", alg));
965                     return (NULL);
966           }
967 
968           new_key = dst_s_get_key_struct(name, alg, flags, protocol, bits);
969           if (new_key == NULL)
970                     return (NULL);
971           if (bits == 0) /*%< null key we are done */
972                     return (new_key);
973           if (new_key->dk_func == NULL || new_key->dk_func->generate == NULL) {
974                     EREPORT(("dst_generate_key_pair():Unsupported algorithm %d\n",
975                                alg));
976                     return (dst_free_key(new_key));
977           }
978           if (new_key->dk_func->generate(new_key, exp) <= 0) {
979                     EREPORT(("dst_generate_key_pair(): Key generation failure %s %d %d %d\n",
980                                new_key->dk_key_name, new_key->dk_alg,
981                                new_key->dk_key_size, exp));
982                     return (dst_free_key(new_key));
983           }
984 
985           dnslen = dst_key_to_dnskey(new_key, dns, sizeof(dns));
986           if (dnslen != UNSUPPORTED_KEYALG)
987                     new_key->dk_id = dst_s_dns_key_id(dns, dnslen);
988           else
989                     new_key->dk_id = 0;
990 
991           return (new_key);
992 }
993 
994 /*%
995  *        Release all data structures pointed to by a key structure.
996  *
997  *  Parameters
998  *\li     f_key   Key structure to be freed.
999  */
1000 
1001 DST_KEY *
dst_free_key(DST_KEY * f_key)1002 dst_free_key(DST_KEY *f_key)
1003 {
1004 
1005           if (f_key == NULL)
1006                     return (f_key);
1007           if (f_key->dk_func && f_key->dk_func->destroy)
1008                     f_key->dk_KEY_struct =
1009                               f_key->dk_func->destroy(f_key->dk_KEY_struct);
1010           else {
1011                     EREPORT(("dst_free_key(): Unknown key alg %d\n",
1012                                f_key->dk_alg));
1013           }
1014           if (f_key->dk_KEY_struct) {
1015                     free(f_key->dk_KEY_struct);
1016                     f_key->dk_KEY_struct = NULL;
1017           }
1018           if (f_key->dk_key_name)
1019                     SAFE_FREE(f_key->dk_key_name);
1020           SAFE_FREE(f_key);
1021           return (NULL);
1022 }
1023 
1024 /*%
1025  *        Return the maximim size of signature from the key specified in bytes
1026  *
1027  * Parameters
1028  *\li      key
1029  *
1030  * Returns
1031  *  \li   bytes
1032  */
1033 int
dst_sig_size(DST_KEY * key)1034 dst_sig_size(DST_KEY *key) {
1035           switch (key->dk_alg) {
1036               case KEY_HMAC_MD5:
1037                     return (16);
1038               case KEY_HMAC_SHA1:
1039                     return (20);
1040               case KEY_RSA:
1041                     return (key->dk_key_size + 7) / 8;
1042               case KEY_DSA:
1043                     return (40);
1044               default:
1045                     EREPORT(("dst_sig_size(): Unknown key alg %d\n", key->dk_alg));
1046                     return -1;
1047           }
1048 }
1049 
1050 /*! \file */
1051