Merge from vendor branch GCC:
[dragonfly.git] / contrib / bind-9.2.4rc7 / bin / dnssec / dnssec-keygen.c
1 /*
2  * Portions Copyright (C) 2004  Internet Systems Consortium, Inc. ("ISC")
3  * Portions Copyright (C) 2000, 2001  Internet Software Consortium.
4  * Portions Copyright (C) 1995-2000 by Network Associates, Inc.
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC AND NETWORK ASSOCIATES DISCLAIMS
11  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
12  * WARRANTIES OF MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE
13  * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
16  * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 /* $Id: dnssec-keygen.c,v 1.48.2.2 2004/03/09 06:09:14 marka Exp $ */
20
21 #include <config.h>
22
23 #include <stdlib.h>
24
25 #include <isc/buffer.h>
26 #include <isc/commandline.h>
27 #include <isc/entropy.h>
28 #include <isc/mem.h>
29 #include <isc/region.h>
30 #include <isc/string.h>
31 #include <isc/util.h>
32
33 #include <dns/fixedname.h>
34 #include <dns/keyvalues.h>
35 #include <dns/log.h>
36 #include <dns/name.h>
37 #include <dns/rdataclass.h>
38 #include <dns/result.h>
39 #include <dns/secalg.h>
40
41 #include <dst/dst.h>
42
43 #include "dnssectool.h"
44
45 #define MAX_RSA 4096 /* should be long enough... */
46
47 const char *program = "dnssec-keygen";
48 int verbose;
49
50 static isc_boolean_t
51 dsa_size_ok(int size) {
52         return (ISC_TF(size >= 512 && size <= 1024 && size % 64 == 0));
53 }
54
55 static void
56 usage(void) {
57         fprintf(stderr, "Usage:\n");
58         fprintf(stderr, "    %s -a alg -b bits -n type [options] name\n\n",
59                 program);
60         fprintf(stderr, "Required options:\n");
61         fprintf(stderr, "    -a algorithm: RSA | RSAMD5 | DH | DSA | HMAC-MD5"
62                 "\n");
63         fprintf(stderr, "    -b key size, in bits:\n");
64         fprintf(stderr, "        RSA:\t\t[512..%d]\n", MAX_RSA);
65         fprintf(stderr, "        DH:\t\t[128..4096]\n");
66         fprintf(stderr, "        DSA:\t\t[512..1024] and divisible by 64\n");
67         fprintf(stderr, "        HMAC-MD5:\t[1..512]\n");
68         fprintf(stderr, "    -n nametype: ZONE | HOST | ENTITY | USER\n");
69         fprintf(stderr, "    name: owner of the key\n");
70         fprintf(stderr, "Other options:\n");
71         fprintf(stderr, "    -c class (default: IN)\n");
72         fprintf(stderr, "    -e use large exponent (RSA only)\n");
73         fprintf(stderr, "    -g use specified generator (DH only)\n");
74         fprintf(stderr, "    -t type: AUTHCONF | NOAUTHCONF | NOAUTH | NOCONF "
75                "(default: AUTHCONF)\n");
76         fprintf(stderr, "    -p protocol value "
77                "(default: 2 [email] for USER, 3 [dnssec] otherwise)\n");
78         fprintf(stderr, "    -s strength value this key signs DNS records "
79                 "with (default: 0)\n");
80         fprintf(stderr, "    -r randomdev (a file containing random data)\n");
81         fprintf(stderr, "    -v verbose level\n");
82         fprintf(stderr, "Output:\n");
83         fprintf(stderr, "     K<name>+<alg>+<id>.key, "
84                 "K<name>+<alg>+<id>.private\n");
85
86         exit (-1);
87 }
88
89 int
90 main(int argc, char **argv) {
91         char            *algname = NULL, *nametype = NULL, *type = NULL;
92         char            *classname = NULL;
93         char            *randomfile = NULL;
94         char            *prog, *endp;
95         dst_key_t       *key = NULL, *oldkey;
96         dns_fixedname_t fname;
97         dns_name_t      *name;
98         isc_uint16_t    flags = 0;
99         dns_secalg_t    alg;
100         isc_boolean_t   conflict = ISC_FALSE, null_key = ISC_FALSE;
101         isc_mem_t       *mctx = NULL;
102         int             ch, rsa_exp = 0, generator = 0, param = 0;
103         int             protocol = -1, size = -1, signatory = 0;
104         isc_result_t    ret;
105         isc_textregion_t r;
106         char            filename[255];
107         isc_buffer_t    buf;
108         isc_log_t       *log = NULL;
109         isc_entropy_t   *ectx = NULL;
110         dns_rdataclass_t rdclass;
111
112         RUNTIME_CHECK(isc_mem_create(0, 0, &mctx) == ISC_R_SUCCESS);
113
114         if ((prog = strrchr(argv[0],'/')) == NULL)
115                 prog = isc_mem_strdup(mctx, argv[0]);
116         else
117                 prog = isc_mem_strdup(mctx, ++prog);
118         if (prog == NULL)
119                 fatal("out of memory");
120
121         if (argc == 1)
122                 usage();
123
124         dns_result_register();
125
126         while ((ch = isc_commandline_parse(argc, argv,
127                                            "a:b:c:eg:n:t:p:s:hr:v:")) != -1)
128         {
129             switch (ch) {
130                 case 'a':
131                         algname = isc_commandline_argument;
132                         break;
133                 case 'b':
134                         size = strtol(isc_commandline_argument, &endp, 10);
135                         if (*endp != '\0' || size < 0)
136                                 fatal("-b requires a non-negative number");
137                         break;
138                 case 'c':
139                         classname = isc_commandline_argument;
140                         break;
141                 case 'e':
142                         rsa_exp = 1;
143                         break;
144                 case 'g':
145                         generator = strtol(isc_commandline_argument,
146                                            &endp, 10);
147                         if (*endp != '\0' || generator <= 0)
148                                 fatal("-g requires a positive number");
149                         break;
150                 case 'n':
151                         nametype = isc_commandline_argument;
152                         if (nametype == NULL)
153                                 fatal("out of memory");
154                         break;
155                 case 't':
156                         type = isc_commandline_argument;
157                         if (type == NULL)
158                                 fatal("out of memory");
159                         break;
160                 case 'p':
161                         protocol = strtol(isc_commandline_argument, &endp, 10);
162                         if (*endp != '\0' || protocol < 0 || protocol > 255)
163                                 fatal("-p must be followed by a number "
164                                       "[0..255]");
165                         break;
166                 case 's':
167                         signatory = strtol(isc_commandline_argument,
168                                            &endp, 10);
169                         if (*endp != '\0' || signatory < 0 || signatory > 15)
170                                 fatal("-s must be followed by a number "
171                                       "[0..15]");
172                         break;
173                 case 'r':
174                         randomfile = isc_commandline_argument;
175                         break;
176                 case 'v':
177                         endp = NULL;
178                         verbose = strtol(isc_commandline_argument, &endp, 0);
179                         if (*endp != '\0')
180                                 fatal("-v must be followed by a number");
181                         break;
182
183                 case 'h':
184                         usage();
185                 default:
186                         fprintf(stderr, "%s: invalid argument -%c\n",
187                                 program, ch);
188                         usage();
189                 }
190         }
191
192         setup_entropy(mctx, randomfile, &ectx);
193         ret = dst_lib_init(mctx, ectx,
194                            ISC_ENTROPY_BLOCKING | ISC_ENTROPY_GOODONLY);
195         if (ret != ISC_R_SUCCESS)
196                 fatal("could not initialize dst");
197
198         setup_logging(verbose, mctx, &log);
199
200         if (argc < isc_commandline_index + 1)
201                 fatal("the key name was not specified");
202         if (argc > isc_commandline_index + 1)
203                 fatal("extraneous arguments");
204
205         if (algname == NULL)
206                 fatal("no algorithm was specified");
207         if (strcasecmp(algname, "RSA") == 0)
208                 alg = DNS_KEYALG_RSA;
209         else if (strcasecmp(algname, "HMAC-MD5") == 0)
210                 alg = DST_ALG_HMACMD5;
211         else {
212                 r.base = algname;
213                 r.length = strlen(algname);
214                 ret = dns_secalg_fromtext(&alg, &r);
215                 if (ret != ISC_R_SUCCESS)
216                         fatal("unknown algorithm %s", algname);
217         }
218
219         if (type != NULL) {
220                 if (strcasecmp(type, "NOAUTH") == 0)
221                         flags |= DNS_KEYTYPE_NOAUTH;
222                 else if (strcasecmp(type, "NOCONF") == 0)
223                         flags |= DNS_KEYTYPE_NOCONF;
224                 else if (strcasecmp(type, "NOAUTHCONF") == 0) {
225                         flags |= (DNS_KEYTYPE_NOAUTH | DNS_KEYTYPE_NOCONF);
226                         if (size < 0)
227                                 size = 0;
228                 }
229                 else if (strcasecmp(type, "AUTHCONF") == 0)
230                         /* nothing */;
231                 else
232                         fatal("invalid type %s", type);
233         }
234
235         if (size < 0)
236                 fatal("key size not specified (-b option)");
237
238         switch (alg) {
239         case DNS_KEYALG_RSA:
240                 if (size != 0 && (size < 512 || size > MAX_RSA))
241                         fatal("RSA key size %d out of range", size);
242                 break;
243         case DNS_KEYALG_DH:
244                 if (size != 0 && (size < 128 || size > 4096))
245                         fatal("DH key size %d out of range", size);
246                 break;
247         case DNS_KEYALG_DSA:
248                 if (size != 0 && !dsa_size_ok(size))
249                         fatal("Invalid DSS key size: %d", size);
250                 break;
251         case DST_ALG_HMACMD5:
252                 if (size < 1 || size > 512)
253                         fatal("HMAC-MD5 key size %d out of range", size);
254                 break;
255         }
256
257         if (alg != DNS_KEYALG_RSA && rsa_exp != 0)
258                 fatal("specified RSA exponent without RSA");
259
260         if (alg != DNS_KEYALG_DH && generator != 0)
261                 fatal("specified DH generator without DH");
262
263         if (nametype == NULL)
264                 fatal("no nametype specified");
265         if (strcasecmp(nametype, "zone") == 0)
266                 flags |= DNS_KEYOWNER_ZONE;
267         else if (strcasecmp(nametype, "host") == 0 ||
268                  strcasecmp(nametype, "entity") == 0)
269                 flags |= DNS_KEYOWNER_ENTITY;
270         else if (strcasecmp(nametype, "user") == 0)
271                 flags |= DNS_KEYOWNER_USER;
272         else
273                 fatal("invalid nametype %s", nametype);
274
275         if (classname != NULL) {
276                 r.base = classname;
277                 r.length = strlen(classname);
278                 ret = dns_rdataclass_fromtext(&rdclass, &r);
279                 if (ret != ISC_R_SUCCESS)
280                         fatal("unknown class %s",classname);
281         } else 
282                 rdclass = dns_rdataclass_in;
283
284         flags |= signatory;
285
286         if (protocol == -1) {
287                 if ((flags & DNS_KEYFLAG_OWNERMASK) == DNS_KEYOWNER_USER)
288                         protocol = DNS_KEYPROTO_EMAIL;
289                 else
290                         protocol = DNS_KEYPROTO_DNSSEC;
291         }
292
293         if ((flags & DNS_KEYFLAG_TYPEMASK) == DNS_KEYTYPE_NOKEY) {
294                 if (size > 0)
295                         fatal("Specified null key with non-zero size");
296                 if ((flags & DNS_KEYFLAG_SIGNATORYMASK) != 0)
297                         fatal("Specified null key with signing authority");
298         }
299
300         dns_fixedname_init(&fname);
301         name = dns_fixedname_name(&fname);
302         isc_buffer_init(&buf, argv[isc_commandline_index],
303                         strlen(argv[isc_commandline_index]));
304         isc_buffer_add(&buf, strlen(argv[isc_commandline_index]));
305         ret = dns_name_fromtext(name, &buf, dns_rootname, ISC_FALSE, NULL);
306         if (ret != ISC_R_SUCCESS)
307                 fatal("Invalid key name %s: %s", argv[isc_commandline_index],
308                       isc_result_totext(ret));
309
310         switch(alg) {
311         case DNS_KEYALG_RSA:
312                 param = rsa_exp;
313                 break;
314         case DNS_KEYALG_DH:
315                 param = generator;
316                 break;
317         case DNS_KEYALG_DSA:
318         case DST_ALG_HMACMD5:
319                 param = 0;
320                 break;
321         }
322
323         if ((flags & DNS_KEYFLAG_TYPEMASK) == DNS_KEYTYPE_NOKEY)
324                 null_key = ISC_TRUE;
325
326         isc_buffer_init(&buf, filename, sizeof(filename) - 1);
327
328         do {
329                 conflict = ISC_FALSE;
330                 oldkey = NULL;
331
332                 /* generate the key */
333                 ret = dst_key_generate(name, alg, size, param, flags, protocol,
334                                        rdclass, mctx, &key);
335                 isc_entropy_stopcallbacksources(ectx);
336
337                 if (ret != ISC_R_SUCCESS) {
338                         char namestr[DNS_NAME_FORMATSIZE];
339                         char algstr[ALG_FORMATSIZE];
340                         dns_name_format(name, namestr, sizeof namestr);
341                         alg_format(alg, algstr, sizeof algstr);
342                         fatal("failed to generate key %s/%s: %s\n",
343                               namestr, algstr, isc_result_totext(ret));
344                         exit(-1);
345                 }
346
347                 /*
348                  * Try to read a key with the same name, alg and id from disk.
349                  * If there is one we must continue generating a new one
350                  * unless we were asked to generate a null key, in which
351                  * case we return failure.
352                  */
353                 ret = dst_key_fromfile(name, dst_key_id(key), alg,
354                                        DST_TYPE_PRIVATE, NULL, mctx, &oldkey);
355                 /* do not overwrite an existing key  */
356                 if (ret == ISC_R_SUCCESS) {
357                         dst_key_free(&oldkey);
358                         conflict = ISC_TRUE;
359                         if (null_key)
360                                 break;
361                 }
362                 if (conflict == ISC_TRUE) {
363                         if (verbose > 0) {
364                                 isc_buffer_clear(&buf);
365                                 ret = dst_key_buildfilename(key, 0, NULL, &buf);
366                                 fprintf(stderr,
367                                         "%s: %s already exists, "
368                                         "generating a new key\n",
369                                         program, filename);
370                         }
371                         dst_key_free(&key);
372                 }
373
374         } while (conflict == ISC_TRUE);
375
376         if (conflict)
377                 fatal("cannot generate a null key when a key with id 0 "
378                       "already exists");
379
380         ret = dst_key_tofile(key, DST_TYPE_PUBLIC | DST_TYPE_PRIVATE, NULL);
381         if (ret != ISC_R_SUCCESS) {
382                 char keystr[KEY_FORMATSIZE];
383                 key_format(key, keystr, sizeof keystr);
384                 fatal("failed to write key %s: %s\n", keystr,
385                       isc_result_totext(ret));
386         }
387
388         isc_buffer_clear(&buf);
389         ret = dst_key_buildfilename(key, 0, NULL, &buf);
390         printf("%s\n", filename);
391         isc_mem_free(mctx, prog);
392         dst_key_free(&key);
393
394         cleanup_logging(&log);
395         cleanup_entropy(&ectx);
396         dst_lib_destroy();
397         if (verbose > 10)
398                 isc_mem_stats(mctx, stdout);
399         isc_mem_destroy(&mctx);
400
401         return (0);
402 }