handle default key sizes in openssl_crypter
[strongswan.git] / src / openac / openac.c
1 /**
2 * @file openac.c
3 *
4 * @brief Generation of X.509 attribute certificates.
5 *
6 */
7
8 /*
9 * Copyright (C) 2002 Ueli Galizzi, Ariane Seiler
10 * Copyright (C) 2004,2007 Andreas Steffen
11 * Hochschule fuer Technik Rapperswil, Switzerland
12 *
13 * This program is free software; you can redistribute it and/or modify it
14 * under the terms of the GNU General Public License as published by the
15 * Free Software Foundation; either version 2 of the License, or (at your
16 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
17 *
18 * This program is distributed in the hope that it will be useful, but
19 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
20 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
21 * for more details.
22 *
23 * RCSID $Id$
24 */
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <syslog.h>
30 #include <unistd.h>
31 #include <getopt.h>
32 #include <ctype.h>
33 #include <time.h>
34 #include <gmp.h>
35
36 #include <library.h>
37 #include <debug.h>
38 #include <asn1/asn1.h>
39 #include <asn1/pem.h>
40 #include <credentials/certificates/x509.h>
41 #include <credentials/certificates/ac.h>
42 #include <utils/optionsfrom.h>
43
44 #ifdef INTEGRITY_TEST
45 #include <fips/fips.h>
46 #include <fips_signature.h>
47 #endif /* INTEGRITY_TEST */
48
49 #define OPENAC_PATH IPSEC_CONFDIR "/openac"
50 #define OPENAC_SERIAL IPSEC_CONFDIR "/openac/serial"
51
52 #define DEFAULT_VALIDITY 24*3600 /* seconds */
53
54 /**
55 * @brief prints the usage of the program to the stderr
56 */
57 static void usage(const char *message)
58 {
59 if (message != NULL && *message != '\0')
60 {
61 fprintf(stderr, "%s\n", message);
62 }
63 fprintf(stderr, "Usage: openac"
64 " [--help]"
65 " [--version]"
66 " [--optionsfrom <filename>]"
67 " [--quiet]"
68 " \\\n\t"
69 " [--debug <level 0..4>]"
70 " \\\n\t"
71 " [--days <days>]"
72 " [--hours <hours>]"
73 " \\\n\t"
74 " [--startdate <YYYYMMDDHHMMSSZ>]"
75 " [--enddate <YYYYMMDDHHMMSSZ>]"
76 " \\\n\t"
77 " --cert <certfile>"
78 " --key <keyfile>"
79 " [--password <password>]"
80 " \\\n\t"
81 " --usercert <certfile>"
82 " --groups <attr1,attr2,..>"
83 " --out <filename>"
84 "\n"
85 );
86 }
87
88
89 /**
90 * convert a chunk into a multi-precision integer
91 */
92 static void chunk_to_mpz(chunk_t chunk, mpz_t number)
93 {
94 mpz_import(number, chunk.len, 1, 1, 1, 0, chunk.ptr);
95 }
96
97 /**
98 * convert a multi-precision integer into a chunk
99 */
100 static chunk_t mpz_to_chunk(mpz_t number)
101 {
102 chunk_t chunk;
103
104 chunk.len = 1 + mpz_sizeinbase(number, 2)/BITS_PER_BYTE;
105 chunk.ptr = mpz_export(NULL, NULL, 1, chunk.len, 1, 0, number);
106 return chunk;
107 }
108
109 /**
110 * read the last serial number from file
111 */
112 static chunk_t read_serial(void)
113 {
114 mpz_t number;
115
116 char buf[BUF_LEN], buf1[BUF_LEN];
117 chunk_t hex_serial = { buf, BUF_LEN };
118 chunk_t last_serial = { buf1, BUF_LEN };
119 chunk_t serial;
120
121 FILE *fd = fopen(OPENAC_SERIAL, "r");
122
123 /* last serial number defaults to 0 */
124 *last_serial.ptr = 0x00;
125 last_serial.len = 1;
126
127 if (fd)
128 {
129 if (fscanf(fd, "%s", hex_serial.ptr))
130 {
131 hex_serial.len = strlen(hex_serial.ptr);
132 last_serial = chunk_from_hex(hex_serial, last_serial.ptr);
133 }
134 fclose(fd);
135 }
136 else
137 {
138 DBG1(" file '%s' does not exist yet - serial number set to 01", OPENAC_SERIAL);
139 }
140
141 /**
142 * conversion of read serial number to a multiprecision integer
143 * and incrementing it by one
144 * and representing it as a two's complement octet string
145 */
146 mpz_init(number);
147 chunk_to_mpz(last_serial, number);
148 mpz_add_ui(number, number, 0x01);
149 serial = mpz_to_chunk(number);
150 mpz_clear(number);
151
152 return serial;
153 }
154
155 /**
156 * write back the last serial number to file
157 */
158 static void write_serial(chunk_t serial)
159 {
160 FILE *fd = fopen(OPENAC_SERIAL, "w");
161
162 if (fd)
163 {
164 chunk_t hex_serial;
165
166 DBG1(" serial number is %#B", &serial);
167 hex_serial = chunk_to_hex(serial, NULL, FALSE);
168 fprintf(fd, "%.*s\n", hex_serial.len, hex_serial.ptr);
169 fclose(fd);
170 free(hex_serial.ptr);
171 }
172 else
173 {
174 DBG1(" could not open file '%s' for writing", OPENAC_SERIAL);
175 }
176 }
177
178 /**
179 * Load and parse a private key file
180 */
181 static private_key_t* private_key_create_from_file(char *path, chunk_t *secret)
182 {
183 bool pgp = FALSE;
184 chunk_t chunk = chunk_empty;
185 private_key_t *key = NULL;
186
187 if (!pem_asn1_load_file(path, secret, &chunk, &pgp))
188 {
189 DBG1(" could not load private key file '%s'", path);
190 return NULL;
191 }
192 key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
193 BUILD_BLOB_ASN1_DER, chunk, BUILD_END);
194 if (key == NULL)
195 {
196 DBG1(" could not parse loaded private key file '%s'", path);
197 return NULL;
198 }
199 DBG1(" loaded private key file '%s'", path);
200 return key;
201 }
202
203 /**
204 * global variables accessible by both main() and build.c
205 */
206
207 static int debug_level = 1;
208 static bool stderr_quiet = FALSE;
209
210 /**
211 * openac dbg function
212 */
213 static void openac_dbg(int level, char *fmt, ...)
214 {
215 int priority = LOG_INFO;
216 va_list args;
217
218 if (level <= debug_level)
219 {
220 va_start(args, fmt);
221 if (!stderr_quiet)
222 {
223 vfprintf(stderr, fmt, args);
224 fprintf(stderr, "\n");
225 }
226 vsyslog(priority, fmt, args);
227 va_end(args);
228 }
229 }
230
231 /**
232 * @brief openac main program
233 *
234 * @param argc number of arguments
235 * @param argv pointer to the argument values
236 */
237 int main(int argc, char **argv)
238 {
239 certificate_t *attr_cert = NULL;
240 certificate_t *userCert = NULL;
241 certificate_t *signerCert = NULL;
242 private_key_t *signerKey = NULL;
243
244 time_t notBefore = UNDEFINED_TIME;
245 time_t notAfter = UNDEFINED_TIME;
246 time_t validity = 0;
247
248 char *keyfile = NULL;
249 char *certfile = NULL;
250 char *usercertfile = NULL;
251 char *outfile = NULL;
252 char *groups = "";
253 char buf[BUF_LEN];
254
255 chunk_t passphrase = { buf, 0 };
256 chunk_t serial = chunk_empty;
257 chunk_t attr_chunk = chunk_empty;
258
259 int status = 1;
260
261 /* enable openac debugging hook */
262 dbg = openac_dbg;
263
264 passphrase.ptr[0] = '\0';
265
266 openlog("openac", 0, LOG_AUTHPRIV);
267
268 /* initialize library */
269 library_init(STRONGSWAN_CONF);
270 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
271 lib->settings->get_str(lib->settings, "openac.load", PLUGINS));
272
273 /* initialize optionsfrom */
274 options_t *options = options_create();
275
276 /* handle arguments */
277 for (;;)
278 {
279 static const struct option long_opts[] = {
280 /* name, has_arg, flag, val */
281 { "help", no_argument, NULL, 'h' },
282 { "version", no_argument, NULL, 'v' },
283 { "optionsfrom", required_argument, NULL, '+' },
284 { "quiet", no_argument, NULL, 'q' },
285 { "cert", required_argument, NULL, 'c' },
286 { "key", required_argument, NULL, 'k' },
287 { "password", required_argument, NULL, 'p' },
288 { "usercert", required_argument, NULL, 'u' },
289 { "groups", required_argument, NULL, 'g' },
290 { "days", required_argument, NULL, 'D' },
291 { "hours", required_argument, NULL, 'H' },
292 { "startdate", required_argument, NULL, 'S' },
293 { "enddate", required_argument, NULL, 'E' },
294 { "out", required_argument, NULL, 'o' },
295 { "debug", required_argument, NULL, 'd' },
296 { 0,0,0,0 }
297 };
298
299 int c = getopt_long(argc, argv, "hv+:qc:k:p;u:g:D:H:S:E:o:d:", long_opts, NULL);
300
301 /* Note: "breaking" from case terminates loop */
302 switch (c)
303 {
304 case EOF: /* end of flags */
305 break;
306
307 case 0: /* long option already handled */
308 continue;
309
310 case ':': /* diagnostic already printed by getopt_long */
311 case '?': /* diagnostic already printed by getopt_long */
312 case 'h': /* --help */
313 usage(NULL);
314 status = 1;
315 goto end;
316
317 case 'v': /* --version */
318 printf("openac (strongSwan %s)\n", VERSION);
319 status = 0;
320 goto end;
321
322 case '+': /* --optionsfrom <filename> */
323 {
324 char path[BUF_LEN];
325
326 if (*optarg == '/') /* absolute pathname */
327 {
328 strncpy(path, optarg, BUF_LEN);
329 }
330 else /* relative pathname */
331 {
332 snprintf(path, BUF_LEN, "%s/%s", OPENAC_PATH, optarg);
333 }
334 if (!options->from(options, path, &argc, &argv, optind))
335 {
336 status = 1;
337 goto end;
338 }
339 }
340 continue;
341
342 case 'q': /* --quiet */
343 stderr_quiet = TRUE;
344 continue;
345
346 case 'c': /* --cert */
347 certfile = optarg;
348 continue;
349
350 case 'k': /* --key */
351 keyfile = optarg;
352 continue;
353
354 case 'p': /* --key */
355 if (strlen(optarg) > BUF_LEN)
356 {
357 usage("passphrase too long");
358 goto end;
359 }
360 strncpy(passphrase.ptr, optarg, BUF_LEN);
361 passphrase.len = min(strlen(optarg), BUF_LEN);
362 continue;
363
364 case 'u': /* --usercert */
365 usercertfile = optarg;
366 continue;
367
368 case 'g': /* --groups */
369 groups = optarg;
370 continue;
371
372 case 'D': /* --days */
373 if (optarg == NULL || !isdigit(optarg[0]))
374 {
375 usage("missing number of days");
376 goto end;
377 }
378 else
379 {
380 char *endptr;
381 long days = strtol(optarg, &endptr, 0);
382
383 if (*endptr != '\0' || endptr == optarg || days <= 0)
384 {
385 usage("<days> must be a positive number");
386 goto end;
387 }
388 validity += 24*3600*days;
389 }
390 continue;
391
392 case 'H': /* --hours */
393 if (optarg == NULL || !isdigit(optarg[0]))
394 {
395 usage("missing number of hours");
396 goto end;
397 }
398 else
399 {
400 char *endptr;
401 long hours = strtol(optarg, &endptr, 0);
402
403 if (*endptr != '\0' || endptr == optarg || hours <= 0)
404 {
405 usage("<hours> must be a positive number");
406 goto end;
407 }
408 validity += 3600*hours;
409 }
410 continue;
411
412 case 'S': /* --startdate */
413 if (optarg == NULL || strlen(optarg) != 15 || optarg[14] != 'Z')
414 {
415 usage("date format must be YYYYMMDDHHMMSSZ");
416 goto end;
417 }
418 else
419 {
420 chunk_t date = { optarg, 15 };
421
422 notBefore = asn1_to_time(&date, ASN1_GENERALIZEDTIME);
423 }
424 continue;
425
426 case 'E': /* --enddate */
427 if (optarg == NULL || strlen(optarg) != 15 || optarg[14] != 'Z')
428 {
429 usage("date format must be YYYYMMDDHHMMSSZ");
430 goto end;
431 }
432 else
433 {
434 chunk_t date = { optarg, 15 };
435 notAfter = asn1_to_time(&date, ASN1_GENERALIZEDTIME);
436 }
437 continue;
438
439 case 'o': /* --out */
440 outfile = optarg;
441 continue;
442
443 case 'd': /* --debug */
444 debug_level = atoi(optarg);
445 continue;
446
447 default:
448 usage("");
449 status = 0;
450 goto end;
451 }
452 /* break from loop */
453 break;
454 }
455
456 if (optind != argc)
457 {
458 usage("unexpected argument");
459 goto end;
460 }
461
462 DBG1("starting openac (strongSwan Version %s)", VERSION);
463
464 #ifdef INTEGRITY_TEST
465 DBG1("integrity test of libstrongswan code");
466 if (fips_verify_hmac_signature(hmac_key, hmac_signature))
467 {
468 DBG1(" integrity test passed");
469 }
470 else
471 {
472 DBG1(" integrity test failed");
473 status = 3;
474 goto end;
475 }
476 #endif /* INTEGRITY_TEST */
477
478 /* load the signer's RSA private key */
479 if (keyfile != NULL)
480 {
481 signerKey = private_key_create_from_file(keyfile, &passphrase);
482
483 if (signerKey == NULL)
484 {
485 goto end;
486 }
487 }
488
489 /* load the signer's X.509 certificate */
490 if (certfile != NULL)
491 {
492 signerCert = lib->creds->create(lib->creds,
493 CRED_CERTIFICATE, CERT_X509,
494 BUILD_FROM_FILE, certfile,
495 BUILD_X509_FLAG, 0,
496 BUILD_END);
497 if (signerCert == NULL)
498 {
499 goto end;
500 }
501 }
502
503 /* load the users's X.509 certificate */
504 if (usercertfile != NULL)
505 {
506 userCert = lib->creds->create(lib->creds,
507 CRED_CERTIFICATE, CERT_X509,
508 BUILD_FROM_FILE, usercertfile,
509 BUILD_X509_FLAG, 0,
510 BUILD_END);
511 if (userCert == NULL)
512 {
513 goto end;
514 }
515 }
516
517 /* compute validity interval */
518 validity = (validity)? validity : DEFAULT_VALIDITY;
519 notBefore = (notBefore == UNDEFINED_TIME) ? time(NULL) : notBefore;
520 notAfter = (notAfter == UNDEFINED_TIME) ? time(NULL) + validity : notAfter;
521
522 /* build and parse attribute certificate */
523 if (userCert != NULL && signerCert != NULL && signerKey != NULL)
524 {
525 /* read the serial number and increment it by one */
526 serial = read_serial();
527
528 attr_cert = lib->creds->create(lib->creds,
529 CRED_CERTIFICATE, CERT_X509_AC,
530 BUILD_CERT, userCert->get_ref(userCert),
531 BUILD_NOT_BEFORE_TIME, notBefore,
532 BUILD_NOT_AFTER_TIME, notAfter,
533 BUILD_SERIAL, serial,
534 BUILD_IETF_GROUP_ATTR, groups,
535 BUILD_SIGNING_CERT, signerCert->get_ref(signerCert),
536 BUILD_SIGNING_KEY, signerKey->get_ref(signerKey),
537 BUILD_END);
538 if (!attr_cert)
539 {
540 goto end;
541 }
542
543 /* write the attribute certificate to file */
544 attr_chunk = attr_cert->get_encoding(attr_cert);
545 if (chunk_write(attr_chunk, outfile, 0022, TRUE))
546 {
547 DBG1(" wrote attribute cert file '%s' (%u bytes)", outfile, attr_chunk.len);
548 write_serial(serial);
549 status = 0;
550 }
551 }
552 else
553 {
554 usage("some of the mandatory parameters --usercert --cert --key "
555 "are missing");
556 }
557
558 end:
559 /* delete all dynamically allocated objects */
560 DESTROY_IF(signerKey);
561 DESTROY_IF(signerCert);
562 DESTROY_IF(userCert);
563 DESTROY_IF(attr_cert);
564 free(attr_chunk.ptr);
565 free(serial.ptr);
566 closelog();
567 dbg = dbg_default;
568 options->destroy(options);
569 library_deinit();
570 exit(status);
571 }