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