]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - 6/contrib/bind9/lib/bind/dst/dst_api.c
merge fix for boot-time hang on centos' xen
[FreeBSD/FreeBSD.git] / 6 / contrib / bind9 / 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.6 2007/09/24 17:26:10 each 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         if (new_key->dk_key_name == NULL) {
174                 free(new_key);
175                 return (NULL);
176         }
177         new_key->dk_alg = alg;
178         new_key->dk_flags = flags;
179         new_key->dk_proto = protocol;
180         new_key->dk_KEY_struct = NULL;
181         new_key->dk_key_size = bits;
182         new_key->dk_func = dst_t_func[alg];
183         return (new_key);
184 }
185
186 /*
187  *  dst_compare_keys
188  *      Compares two keys for equality.
189  *  Parameters
190  *      key1, key2      Two keys to be compared.
191  *  Returns
192  *      0              The keys are equal.
193  *      non-zero        The keys are not equal.
194  */
195
196 int
197 dst_compare_keys(const DST_KEY *key1, const DST_KEY *key2)
198 {
199         if (key1 == key2)
200                 return (0);
201         if (key1 == NULL || key2 == NULL)
202                 return (4);
203         if (key1->dk_alg != key2->dk_alg)
204                 return (1);
205         if (key1->dk_key_size != key2->dk_key_size)
206                 return (2);
207         if (key1->dk_id != key2->dk_id)
208                 return (3);
209         return (key1->dk_func->compare(key1, key2));
210 }
211
212
213 /*
214  * dst_sign_data
215  *      An incremental signing function.  Data is signed in steps.
216  *      First the context must be initialized (SIG_MODE_INIT).
217  *      Then data is hashed (SIG_MODE_UPDATE).  Finally the signature
218  *      itself is created (SIG_MODE_FINAL).  This function can be called
219  *      once with INIT, UPDATE and FINAL modes all set, or it can be
220  *      called separately with a different mode set for each step.  The
221  *      UPDATE step can be repeated.
222  * Parameters
223  *      mode    A bit mask used to specify operation(s) to be performed.
224  *                SIG_MODE_INIT    1   Initialize digest
225  *                SIG_MODE_UPDATE        2   Add data to digest
226  *                SIG_MODE_FINAL          4   Generate signature
227  *                                            from signature
228  *                SIG_MODE_ALL (SIG_MODE_INIT,SIG_MODE_UPDATE,SIG_MODE_FINAL
229  *      data    Data to be signed.
230  *      len     The length in bytes of data to be signed.
231  *      in_key  Contains a private key to sign with.
232  *                KEY structures should be handled (created, converted,
233  *                compared, stored, freed) by the DST.
234  *      signature
235  *            The location to which the signature will be written.
236  *      sig_len Length of the signature field in bytes.
237  * Return
238  *       0      Successfull INIT or Update operation
239  *      >0      success FINAL (sign) operation
240  *      <0      failure
241  */
242
243 int
244 dst_sign_data(const int mode, DST_KEY *in_key, void **context, 
245               const u_char *data, const int len,
246               u_char *signature, const int sig_len)
247 {
248         DUMP(data, mode, len, "dst_sign_data()");
249
250         if (mode & SIG_MODE_FINAL &&
251             (in_key->dk_KEY_struct == NULL || signature == NULL))
252                 return (MISSING_KEY_OR_SIGNATURE);
253
254         if (in_key->dk_func && in_key->dk_func->sign)
255                 return (in_key->dk_func->sign(mode, in_key, context, data, len,
256                                               signature, sig_len));
257         return (UNKNOWN_KEYALG);
258 }
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
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 /*
305  *  dst_read_private_key
306  *      Access a private key.  First the list of private keys that have
307  *      already been read in is searched, then the key accessed on disk.
308  *      If the private key can be found, it is returned.  If the key cannot
309  *      be found, a null pointer is returned.  The options specify required
310  *      key characteristics.  If the private key requested does not have
311  *      these characteristics, it will not be read.
312  *  Parameters
313  *      in_keyname  The private key name.
314  *      in_id       The id of the private key.
315  *      options     DST_FORCE_READ  Read from disk - don't use a previously
316  *                                    read key.
317  *                DST_CAN_SIGN    The key must be useable for signing.
318  *                DST_NO_AUTHEN   The key must be useable for authentication.
319  *                DST_STANDARD    Return any key 
320  *  Returns
321  *      NULL    If there is no key found in the current directory or
322  *                    this key has not been loaded before.
323  *      !NULL       Success - KEY structure returned.
324  */
325
326 DST_KEY *
327 dst_read_key(const char *in_keyname, const u_int16_t in_id, 
328              const int in_alg, const int type)
329 {
330         char keyname[PATH_MAX];
331         DST_KEY *dg_key = NULL, *pubkey = NULL;
332
333         if (!dst_check_algorithm(in_alg)) { /* make sure alg is available */
334                 EREPORT(("dst_read_private_key(): Algorithm %d not suppored\n",
335                          in_alg));
336                 return (NULL);
337         }
338         if ((type & (DST_PUBLIC | DST_PRIVATE)) == 0) 
339                 return (NULL);
340         if (in_keyname == NULL) {
341                 EREPORT(("dst_read_private_key(): Null key name passed in\n"));
342                 return (NULL);
343         } else if (strlen(in_keyname) >= sizeof(keyname)) {
344                 EREPORT(("dst_read_private_key(): keyname too big\n"));
345                 return (NULL);
346         } else 
347                 strcpy(keyname, in_keyname);
348
349         /* before I read in the public key, check if it is allowed to sign */
350         if ((pubkey = dst_s_read_public_key(keyname, in_id, in_alg)) == NULL)
351                 return (NULL);
352
353         if (type == DST_PUBLIC) 
354                 return pubkey; 
355
356         if (!(dg_key = dst_s_get_key_struct(keyname, pubkey->dk_alg,
357                                             pubkey->dk_flags, pubkey->dk_proto,
358                                             0)))
359                 return (dg_key);
360         /* Fill in private key and some fields in the general key structure */
361         if (dst_s_read_private_key_file(keyname, dg_key, pubkey->dk_id,
362                                         pubkey->dk_alg) == 0)
363                 dg_key = dst_free_key(dg_key);
364
365         (void)dst_free_key(pubkey);
366         return (dg_key);
367 }
368
369 int 
370 dst_write_key(const DST_KEY *key, const int type)
371 {
372         int pub = 0, priv = 0;
373
374         if (key == NULL) 
375                 return (0);
376         if (!dst_check_algorithm(key->dk_alg)) { /* make sure alg is available */
377                 EREPORT(("dst_write_key(): Algorithm %d not suppored\n", 
378                          key->dk_alg));
379                 return (UNSUPPORTED_KEYALG);
380         }
381         if ((type & (DST_PRIVATE|DST_PUBLIC)) == 0)
382                 return (0);
383
384         if (type & DST_PUBLIC) 
385                 if ((pub = dst_s_write_public_key(key)) < 0)
386                         return (pub);
387         if (type & DST_PRIVATE)
388                 if ((priv = dst_s_write_private_key(key)) < 0)
389                         return (priv);
390         return (priv+pub);
391 }
392
393 /*
394  *  dst_write_private_key
395  *      Write a private key to disk.  The filename will be of the form:
396  *      K<key->dk_name>+<key->dk_alg>+<key->dk_id>.<private key suffix>.
397  *      If there is already a file with this name, an error is returned.
398  *
399  *  Parameters
400  *      key     A DST managed key structure that contains
401  *            all information needed about a key.
402  *  Return
403  *      >= 0    Correct behavior.  Returns length of encoded key value
404  *                written to disk.
405  *      <  0    error.
406  */
407
408 static int
409 dst_s_write_private_key(const DST_KEY *key)
410 {
411         u_char encoded_block[RAW_KEY_SIZE];
412         char file[PATH_MAX];
413         int len;
414         FILE *fp;
415
416         /* First encode the key into the portable key format */
417         if (key == NULL)
418                 return (-1);
419         if (key->dk_KEY_struct == NULL)
420                 return (0);     /* null key has no private key */
421
422         if (key->dk_func == NULL || key->dk_func->to_file_fmt == NULL) {
423                 EREPORT(("dst_write_private_key(): Unsupported operation %d\n",
424                          key->dk_alg));
425                 return (-5);
426         } else if ((len = key->dk_func->to_file_fmt(key, (char *)encoded_block,
427                                              sizeof(encoded_block))) <= 0) {
428                 EREPORT(("dst_write_private_key(): Failed encoding private RSA bsafe key %d\n", len));
429                 return (-8);
430         }
431         /* Now I can create the file I want to use */
432         dst_s_build_filename(file, key->dk_key_name, key->dk_id, key->dk_alg,
433                              PRIVATE_KEY, PATH_MAX);
434
435         /* Do not overwrite an existing file */
436         if ((fp = dst_s_fopen(file, "w", 0600)) != NULL) {
437                 int nn;
438                 if ((nn = fwrite(encoded_block, 1, len, fp)) != len) {
439                         EREPORT(("dst_write_private_key(): Write failure on %s %d != %d errno=%d\n",
440                                  file, len, nn, errno));
441                         fclose(fp);
442                         return (-5);
443                 }
444                 fclose(fp);
445         } else {
446                 EREPORT(("dst_write_private_key(): Can not create file %s\n"
447                          ,file));
448                 return (-6);
449         }
450         memset(encoded_block, 0, len);
451         return (len);
452 }
453
454 /*
455 *
456  *  dst_read_public_key
457  *      Read a public key from disk and store in a DST key structure.
458  *  Parameters
459  *      in_name  K<in_name><in_id>.<public key suffix> is the
460  *                    filename of the key file to be read.
461  *  Returns
462  *      NULL        If the key does not exist or no name is supplied.
463  *      NON-NULL        Initialized key structure if the key exists.
464  */
465
466 static DST_KEY *
467 dst_s_read_public_key(const char *in_name, const u_int16_t in_id, int in_alg)
468 {
469         int flags, proto, alg, len, dlen;
470         int c;
471         char name[PATH_MAX], enckey[RAW_KEY_SIZE], *notspace;
472         u_char deckey[RAW_KEY_SIZE];
473         FILE *fp;
474
475         if (in_name == NULL) {
476                 EREPORT(("dst_read_public_key(): No key name given\n"));
477                 return (NULL);
478         }
479         if (dst_s_build_filename(name, in_name, in_id, in_alg, PUBLIC_KEY,
480                                  PATH_MAX) == -1) {
481                 EREPORT(("dst_read_public_key(): Cannot make filename from %s, %d, and %s\n",
482                          in_name, in_id, PUBLIC_KEY));
483                 return (NULL);
484         }
485         /*
486          * Open the file and read it's formatted contents up to key
487          * File format:
488          *    domain.name [ttl] [IN] KEY  <flags> <protocol> <algorithm> <key>
489          * flags, proto, alg stored as decimal (or hex numbers FIXME).
490          * (FIXME: handle parentheses for line continuation.)
491          */
492         if ((fp = dst_s_fopen(name, "r", 0)) == NULL) {
493                 EREPORT(("dst_read_public_key(): Public Key not found %s\n",
494                          name));
495                 return (NULL);
496         }
497         /* Skip domain name, which ends at first blank */
498         while ((c = getc(fp)) != EOF)
499                 if (isspace(c))
500                         break;
501         /* Skip blank to get to next field */
502         while ((c = getc(fp)) != EOF)
503                 if (!isspace(c))
504                         break;
505
506         /* Skip optional TTL -- if initial digit, skip whole word. */
507         if (isdigit(c)) {
508                 while ((c = getc(fp)) != EOF)
509                         if (isspace(c))
510                                 break;
511                 while ((c = getc(fp)) != EOF)
512                         if (!isspace(c))
513                                 break;
514         }
515         /* Skip optional "IN" */
516         if (c == 'I' || c == 'i') {
517                 while ((c = getc(fp)) != EOF)
518                         if (isspace(c))
519                                 break;
520                 while ((c = getc(fp)) != EOF)
521                         if (!isspace(c))
522                                 break;
523         }
524         /* Locate and skip "KEY" */
525         if (c != 'K' && c != 'k') {
526                 EREPORT(("\"KEY\" doesn't appear in file: %s", name));
527                 return NULL;
528         }
529         while ((c = getc(fp)) != EOF)
530                 if (isspace(c))
531                         break;
532         while ((c = getc(fp)) != EOF)
533                 if (!isspace(c))
534                         break;
535         ungetc(c, fp);          /* return the charcter to the input field */
536         /* Handle hex!! FIXME.  */
537
538         if (fscanf(fp, "%d %d %d", &flags, &proto, &alg) != 3) {
539                 EREPORT(("dst_read_public_key(): Can not read flag/proto/alg field from %s\n"
540                          ,name));
541                 return (NULL);
542         }
543         /* read in the key string */
544         fgets(enckey, sizeof(enckey), fp);
545
546         /* If we aren't at end-of-file, something is wrong.  */
547         while ((c = getc(fp)) != EOF)
548                 if (!isspace(c))
549                         break;
550         if (!feof(fp)) {
551                 EREPORT(("Key too long in file: %s", name));
552                 return NULL;
553         }
554         fclose(fp);
555
556         if ((len = strlen(enckey)) <= 0)
557                 return (NULL);
558
559         /* discard \n */
560         enckey[--len] = '\0';
561
562         /* remove leading spaces */
563         for (notspace = (char *) enckey; isspace((*notspace)&0xff); len--)
564                 notspace++;
565
566         dlen = b64_pton(notspace, deckey, sizeof(deckey));
567         if (dlen < 0) {
568                 EREPORT(("dst_read_public_key: bad return from b64_pton = %d",
569                          dlen));
570                 return (NULL);
571         }
572         /* store key and info in a key structure that is returned */
573 /*      return dst_store_public_key(in_name, alg, proto, 666, flags, deckey,
574                                     dlen);*/
575         return dst_buffer_to_key(in_name, alg, flags, proto, deckey, dlen);
576 }
577
578
579 /*
580  *  dst_write_public_key
581  *      Write a key to disk in DNS format.
582  *  Parameters
583  *      key     Pointer to a DST key structure.
584  *  Returns
585  *      0       Failure
586  *      1       Success
587  */
588
589 static int
590 dst_s_write_public_key(const DST_KEY *key)
591 {
592         FILE *fp;
593         char filename[PATH_MAX];
594         u_char out_key[RAW_KEY_SIZE];
595         char enc_key[RAW_KEY_SIZE];
596         int len = 0;
597         int mode;
598
599         memset(out_key, 0, sizeof(out_key));
600         if (key == NULL) {
601                 EREPORT(("dst_write_public_key(): No key specified \n"));
602                 return (0);
603         } else if ((len = dst_key_to_dnskey(key, out_key, sizeof(out_key)))< 0)
604                 return (0);
605
606         /* Make the filename */
607         if (dst_s_build_filename(filename, key->dk_key_name, key->dk_id,
608                                  key->dk_alg, PUBLIC_KEY, PATH_MAX) == -1) {
609                 EREPORT(("dst_write_public_key(): Cannot make filename from %s, %d, and %s\n",
610                          key->dk_key_name, key->dk_id, PUBLIC_KEY));
611                 return (0);
612         }
613         /* XXX in general this should be a check for symmetric keys */
614         mode = (key->dk_alg == KEY_HMAC_MD5) ? 0600 : 0644;
615         /* create public key file */
616         if ((fp = dst_s_fopen(filename, "w+", mode)) == NULL) {
617                 EREPORT(("DST_write_public_key: open of file:%s failed (errno=%d)\n",
618                          filename, errno));
619                 return (0);
620         }
621         /*write out key first base64 the key data */
622         if (key->dk_flags & DST_EXTEND_FLAG)
623                 b64_ntop(&out_key[6], len - 6, enc_key, sizeof(enc_key));
624         else
625                 b64_ntop(&out_key[4], len - 4, enc_key, sizeof(enc_key));
626         fprintf(fp, "%s IN KEY %d %d %d %s\n",
627                 key->dk_key_name,
628                 key->dk_flags, key->dk_proto, key->dk_alg, enc_key);
629         fclose(fp);
630         return (1);
631 }
632
633
634 /*
635  *  dst_dnskey_to_public_key
636  *      This function converts the contents of a DNS KEY RR into a DST
637  *      key structure.
638  *  Paramters
639  *      len      Length of the RDATA of the KEY RR RDATA
640  *      rdata    A pointer to the the KEY RR RDATA.
641  *      in_name     Key name to be stored in key structure.
642  *  Returns
643  *      NULL        Failure
644  *      NON-NULL        Success.  Pointer to key structure.
645  *                      Caller's responsibility to free() it.
646  */
647
648 DST_KEY *
649 dst_dnskey_to_key(const char *in_name, const u_char *rdata, const int len)
650 {
651         DST_KEY *key_st;
652         int alg ;
653         int start = DST_KEY_START;
654
655         if (rdata == NULL || len <= DST_KEY_ALG) /* no data */
656                 return (NULL);
657         alg = (u_int8_t) rdata[DST_KEY_ALG];
658         if (!dst_check_algorithm(alg)) { /* make sure alg is available */
659                 EREPORT(("dst_dnskey_to_key(): Algorithm %d not suppored\n",
660                          alg));
661                 return (NULL);
662         }
663
664         if (in_name == NULL)
665                 return (NULL);
666
667         if ((key_st = dst_s_get_key_struct(in_name, alg, 0, 0, 0)) == NULL)
668                 return (NULL);
669
670         key_st->dk_id = dst_s_dns_key_id(rdata, len);
671         key_st->dk_flags = dst_s_get_int16(rdata);
672         key_st->dk_proto = (u_int16_t) rdata[DST_KEY_PROT];
673         if (key_st->dk_flags & DST_EXTEND_FLAG) {
674                 u_int32_t ext_flags;
675                 ext_flags = (u_int32_t) dst_s_get_int16(&rdata[DST_EXT_FLAG]);
676                 key_st->dk_flags = key_st->dk_flags | (ext_flags << 16);
677                 start += 2;
678         }
679         /*
680          * now point to the begining of the data representing the encoding
681          * of the key
682          */
683         if (key_st->dk_func && key_st->dk_func->from_dns_key) {
684                 if (key_st->dk_func->from_dns_key(key_st, &rdata[start],
685                                                   len - start) > 0)
686                         return (key_st);
687         } else
688                 EREPORT(("dst_dnskey_to_public_key(): unsuppored alg %d\n",
689                          alg));
690
691         SAFE_FREE(key_st);
692         return (key_st);
693 }
694
695
696 /*
697  *  dst_public_key_to_dnskey
698  *      Function to encode a public key into DNS KEY wire format 
699  *  Parameters
700  *      key          Key structure to encode.
701  *      out_storage     Location to write the encoded key to.
702  *      out_len  Size of the output array.
703  *  Returns
704  *      <0      Failure
705  *      >=0     Number of bytes written to out_storage
706  */
707
708 int
709 dst_key_to_dnskey(const DST_KEY *key, u_char *out_storage,
710                          const int out_len)
711 {
712         u_int16_t val;
713         int loc = 0;
714         int enc_len = 0;
715         if (key == NULL)
716                 return (-1);
717
718         if (!dst_check_algorithm(key->dk_alg)) { /* make sure alg is available */
719                 EREPORT(("dst_key_to_dnskey(): Algorithm %d not suppored\n",
720                          key->dk_alg));
721                 return (UNSUPPORTED_KEYALG);
722         }
723         memset(out_storage, 0, out_len);
724         val = (u_int16_t)(key->dk_flags & 0xffff);
725         dst_s_put_int16(out_storage, val);
726         loc += 2;
727
728         out_storage[loc++] = (u_char) key->dk_proto;
729         out_storage[loc++] = (u_char) key->dk_alg;
730
731         if (key->dk_flags > 0xffff) {   /* Extended flags */
732                 val = (u_int16_t)((key->dk_flags >> 16) & 0xffff);
733                 dst_s_put_int16(&out_storage[loc], val);
734                 loc += 2;
735         }
736         if (key->dk_KEY_struct == NULL)
737                 return (loc);
738         if (key->dk_func && key->dk_func->to_dns_key) {
739                 enc_len = key->dk_func->to_dns_key(key,
740                                                  (u_char *) &out_storage[loc],
741                                                    out_len - loc);
742                 if (enc_len > 0)
743                         return (enc_len + loc);
744                 else
745                         return (-1);
746         } else
747                 EREPORT(("dst_key_to_dnskey(): Unsupported ALG %d\n",
748                          key->dk_alg));
749         return (-1);
750 }
751
752
753 /*
754  *  dst_buffer_to_key
755  *      Function to encode a string of raw data into a DST key
756  *  Parameters
757  *      alg             The algorithm (HMAC only)
758  *      key             A pointer to the data
759  *      keylen          The length of the data
760  *  Returns
761  *      NULL        an error occurred
762  *      NON-NULL        the DST key
763  */
764 DST_KEY *
765 dst_buffer_to_key(const char *key_name,         /* name of the key */
766                   const int alg,                /* algorithm */
767                   const int flags,              /* dns flags */
768                   const int protocol,           /* dns protocol */
769                   const u_char *key_buf,        /* key in dns wire fmt */
770                   const int key_len)            /* size of key */
771 {
772         
773         DST_KEY *dkey = NULL; 
774         int dnslen;
775         u_char dns[2048];
776
777         if (!dst_check_algorithm(alg)) { /* make sure alg is available */
778                 EREPORT(("dst_buffer_to_key(): Algorithm %d not suppored\n", alg));
779                 return (NULL);
780         }
781
782         dkey = dst_s_get_key_struct(key_name, alg, flags, protocol, -1);
783
784         if (dkey == NULL || dkey->dk_func == NULL ||
785             dkey->dk_func->from_dns_key == NULL) 
786                 return (dst_free_key(dkey));
787
788         if (dkey->dk_func->from_dns_key(dkey, key_buf, key_len) < 0) {
789                 EREPORT(("dst_buffer_to_key(): dst_buffer_to_hmac failed\n"));
790                 return (dst_free_key(dkey));
791         }
792
793         dnslen = dst_key_to_dnskey(dkey, dns, sizeof(dns));
794         dkey->dk_id = dst_s_dns_key_id(dns, dnslen);
795         return (dkey);
796 }
797
798 int 
799 dst_key_to_buffer(DST_KEY *key, u_char *out_buff, int buf_len)
800 {
801         int len;
802   /* this function will extrac the secret of HMAC into a buffer */
803         if (key == NULL) 
804                 return (0);
805         if (key->dk_func != NULL && key->dk_func->to_dns_key != NULL) {
806                 len = key->dk_func->to_dns_key(key, out_buff, buf_len);
807                 if (len < 0)
808                         return (0);
809                 return (len);
810         }
811         return (0);
812 }
813
814
815 /*
816  * dst_s_read_private_key_file
817  *     Function reads in private key from a file.
818  *     Fills out the KEY structure.
819  * Parameters
820  *     name    Name of the key to be read.
821  *     pk_key  Structure that the key is returned in.
822  *     in_id   Key identifier (tag)
823  * Return
824  *     1 if everthing works
825  *     0 if there is any problem
826  */
827
828 static int
829 dst_s_read_private_key_file(char *name, DST_KEY *pk_key, u_int16_t in_id,
830                             int in_alg)
831 {
832         int cnt, alg, len, major, minor, file_major, file_minor;
833         int ret, id;
834         char filename[PATH_MAX];
835         u_char in_buff[RAW_KEY_SIZE], *p;
836         FILE *fp;
837         int dnslen;
838         u_char dns[2048];
839
840         if (name == NULL || pk_key == NULL) {
841                 EREPORT(("dst_read_private_key_file(): No key name given\n"));
842                 return (0);
843         }
844         /* Make the filename */
845         if (dst_s_build_filename(filename, name, in_id, in_alg, PRIVATE_KEY,
846                                  PATH_MAX) == -1) {
847                 EREPORT(("dst_read_private_key(): Cannot make filename from %s, %d, and %s\n",
848                          name, in_id, PRIVATE_KEY));
849                 return (0);
850         }
851         /* first check if we can find the key file */
852         if ((fp = dst_s_fopen(filename, "r", 0)) == NULL) {
853                 EREPORT(("dst_s_read_private_key_file: Could not open file %s in directory %s\n",
854                          filename, dst_path[0] ? dst_path :
855                          (char *) getcwd(NULL, PATH_MAX - 1)));
856                 return (0);
857         }
858         /* now read the header info from the file */
859         if ((cnt = fread(in_buff, 1, sizeof(in_buff), fp)) < 5) {
860                 fclose(fp);
861                 EREPORT(("dst_s_read_private_key_file: error reading file %s (empty file)\n",
862                          filename));
863                 return (0);
864         }
865         /* decrypt key */
866         fclose(fp);
867         if (memcmp(in_buff, "Private-key-format: v", 20) != 0)
868                 goto fail;
869         len = cnt;
870         p = in_buff;
871
872         if (!dst_s_verify_str((const char **) (void *)&p,
873                                "Private-key-format: v")) {
874                 EREPORT(("dst_s_read_private_key_file(): Not a Key file/Decrypt failed %s\n", name));
875                 goto fail;
876         }
877         /* read in file format */
878         sscanf((char *)p, "%d.%d", &file_major, &file_minor);
879         sscanf(KEY_FILE_FORMAT, "%d.%d", &major, &minor);
880         if (file_major < 1) {
881                 EREPORT(("dst_s_read_private_key_file(): Unknown keyfile %d.%d version for %s\n",
882                          file_major, file_minor, name));
883                 goto fail;
884         } else if (file_major > major || file_minor > minor)
885                 EREPORT((
886                                 "dst_s_read_private_key_file(): Keyfile %s version higher than mine %d.%d MAY FAIL\n",
887                                 name, file_major, file_minor));
888
889         while (*p++ != '\n') ;  /* skip to end of line */
890
891         if (!dst_s_verify_str((const char **) (void *)&p, "Algorithm: "))
892                 goto fail;
893
894         if (sscanf((char *)p, "%d", &alg) != 1)
895                 goto fail;
896         while (*p++ != '\n') ;  /* skip to end of line */
897
898         if (pk_key->dk_key_name && !strcmp(pk_key->dk_key_name, name))
899                 SAFE_FREE2(pk_key->dk_key_name, strlen(pk_key->dk_key_name));
900         pk_key->dk_key_name = (char *) strdup(name);
901
902         /* allocate and fill in key structure */
903         if (pk_key->dk_func == NULL || pk_key->dk_func->from_file_fmt == NULL)
904                 goto fail;
905
906         ret = pk_key->dk_func->from_file_fmt(pk_key, (char *)p, &in_buff[len] - p);
907         if (ret < 0)
908                 goto fail;
909
910         dnslen = dst_key_to_dnskey(pk_key, dns, sizeof(dns));
911         id = dst_s_dns_key_id(dns, dnslen);
912
913         /* Make sure the actual key tag matches the input tag used in the filename
914          */
915         if (id != in_id) {
916                 EREPORT(("dst_s_read_private_key_file(): actual tag of key read %d != input tag used to build filename %d.\n", id, in_id));
917                 goto fail;
918         }
919         pk_key->dk_id = (u_int16_t) id;
920         pk_key->dk_alg = alg;
921         memset(in_buff, 0, cnt);
922         return (1);
923
924  fail:
925         memset(in_buff, 0, cnt);
926         return (0);
927 }
928
929
930 /*
931  *  dst_generate_key
932  *      Generate and store a public/private keypair.
933  *      Keys will be stored in formatted files.
934  *  Parameters
935  *      name    Name of the new key.  Used to create key files
936  *                K<name>+<alg>+<id>.public and K<name>+<alg>+<id>.private.
937  *      bits    Size of the new key in bits.
938  *      exp     What exponent to use:
939  *                0        use exponent 3
940  *                non-zero    use Fermant4
941  *      flags   The default value of the DNS Key flags.
942  *                The DNS Key RR Flag field is defined in RFC 2065,
943  *                section 3.3.  The field has 16 bits.
944  *      protocol
945  *            Default value of the DNS Key protocol field.
946  *                The DNS Key protocol field is defined in RFC 2065,
947  *                section 3.4.  The field has 8 bits.
948  *      alg     What algorithm to use.  Currently defined:
949  *                KEY_RSA       1
950  *                KEY_DSA       3
951  *                KEY_HMAC    157
952  *      out_id The key tag is returned.
953  *
954  *  Return
955  *      NULL            Failure
956  *      non-NULL        the generated key pair
957  *                      Caller frees the result, and its dk_name pointer.
958  */
959 DST_KEY *
960 dst_generate_key(const char *name, const int bits, const int exp,
961                  const int flags, const int protocol, const int alg)
962 {
963         DST_KEY *new_key = NULL;
964         int dnslen;
965         u_char dns[2048];
966
967         if (name == NULL)
968                 return (NULL);
969
970         if (!dst_check_algorithm(alg)) { /* make sure alg is available */
971                 EREPORT(("dst_generate_key(): Algorithm %d not suppored\n", alg));
972                 return (NULL);
973         }
974
975         new_key = dst_s_get_key_struct(name, alg, flags, protocol, bits);
976         if (new_key == NULL)
977                 return (NULL);
978         if (bits == 0) /* null key we are done */
979                 return (new_key);
980         if (new_key->dk_func == NULL || new_key->dk_func->generate == NULL) {
981                 EREPORT(("dst_generate_key_pair():Unsupported algorithm %d\n",
982                          alg));
983                 return (dst_free_key(new_key));
984         }
985         if (new_key->dk_func->generate(new_key, exp) <= 0) {
986                 EREPORT(("dst_generate_key_pair(): Key generation failure %s %d %d %d\n",
987                          new_key->dk_key_name, new_key->dk_alg,
988                          new_key->dk_key_size, exp));
989                 return (dst_free_key(new_key));
990         }
991
992         dnslen = dst_key_to_dnskey(new_key, dns, sizeof(dns));
993         if (dnslen != UNSUPPORTED_KEYALG)
994                 new_key->dk_id = dst_s_dns_key_id(dns, dnslen);
995         else
996                 new_key->dk_id = 0;
997
998         return (new_key);
999 }
1000
1001
1002 /*
1003  *  dst_free_key
1004  *      Release all data structures pointed to by a key structure.
1005  *  Parameters
1006  *      f_key   Key structure to be freed.
1007  */
1008
1009 DST_KEY *
1010 dst_free_key(DST_KEY *f_key)
1011 {
1012
1013         if (f_key == NULL)
1014                 return (f_key);
1015         if (f_key->dk_func && f_key->dk_func->destroy)
1016                 f_key->dk_KEY_struct =
1017                         f_key->dk_func->destroy(f_key->dk_KEY_struct);
1018         else {
1019                 EREPORT(("dst_free_key(): Unknown key alg %d\n",
1020                          f_key->dk_alg));
1021         }
1022         if (f_key->dk_KEY_struct) {
1023                 free(f_key->dk_KEY_struct);
1024                 f_key->dk_KEY_struct = NULL;
1025         }
1026         if (f_key->dk_key_name)
1027                 SAFE_FREE(f_key->dk_key_name);
1028         SAFE_FREE(f_key);
1029         return (NULL);
1030 }
1031
1032 /*
1033  * dst_sig_size
1034  *      Return the maximim size of signature from the key specified in bytes
1035  * Parameters
1036  *      key 
1037  * Returns
1038  *     bytes
1039  */
1040 int
1041 dst_sig_size(DST_KEY *key) {
1042         switch (key->dk_alg) {
1043             case KEY_HMAC_MD5:
1044                 return (16);
1045             case KEY_HMAC_SHA1:
1046                 return (20);
1047             case KEY_RSA:
1048                 return (key->dk_key_size + 7) / 8;
1049             case KEY_DSA:
1050                 return (40);
1051             default:
1052                 EREPORT(("dst_sig_size(): Unknown key alg %d\n", key->dk_alg));
1053                 return -1;
1054         }
1055 }