added missing semicolon
[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",
272 "gmp hmac md5 random sha1 sha2 pubkey x509"));
273
274 /* initialize optionsfrom */
275 options_t *options = options_create();
276
277 /* handle arguments */
278 for (;;)
279 {
280 static const struct option long_opts[] = {
281 /* name, has_arg, flag, val */
282 { "help", no_argument, NULL, 'h' },
283 { "version", no_argument, NULL, 'v' },
284 { "optionsfrom", required_argument, NULL, '+' },
285 { "quiet", no_argument, NULL, 'q' },
286 { "cert", required_argument, NULL, 'c' },
287 { "key", required_argument, NULL, 'k' },
288 { "password", required_argument, NULL, 'p' },
289 { "usercert", required_argument, NULL, 'u' },
290 { "groups", required_argument, NULL, 'g' },
291 { "days", required_argument, NULL, 'D' },
292 { "hours", required_argument, NULL, 'H' },
293 { "startdate", required_argument, NULL, 'S' },
294 { "enddate", required_argument, NULL, 'E' },
295 { "out", required_argument, NULL, 'o' },
296 { "debug", required_argument, NULL, 'd' },
297 { 0,0,0,0 }
298 };
299
300 int c = getopt_long(argc, argv, "hv+:qc:k:p;u:g:D:H:S:E:o:d:", long_opts, NULL);
301
302 /* Note: "breaking" from case terminates loop */
303 switch (c)
304 {
305 case EOF: /* end of flags */
306 break;
307
308 case 0: /* long option already handled */
309 continue;
310
311 case ':': /* diagnostic already printed by getopt_long */
312 case '?': /* diagnostic already printed by getopt_long */
313 case 'h': /* --help */
314 usage(NULL);
315 status = 1;
316 goto end;
317
318 case 'v': /* --version */
319 printf("openac (strongSwan %s)\n", VERSION);
320 status = 0;
321 goto end;
322
323 case '+': /* --optionsfrom <filename> */
324 {
325 char path[BUF_LEN];
326
327 if (*optarg == '/') /* absolute pathname */
328 {
329 strncpy(path, optarg, BUF_LEN);
330 }
331 else /* relative pathname */
332 {
333 snprintf(path, BUF_LEN, "%s/%s", OPENAC_PATH, optarg);
334 }
335 if (!options->from(options, path, &argc, &argv, optind))
336 {
337 status = 1;
338 goto end;
339 }
340 }
341 continue;
342
343 case 'q': /* --quiet */
344 stderr_quiet = TRUE;
345 continue;
346
347 case 'c': /* --cert */
348 certfile = optarg;
349 continue;
350
351 case 'k': /* --key */
352 keyfile = optarg;
353 continue;
354
355 case 'p': /* --key */
356 if (strlen(optarg) > BUF_LEN)
357 {
358 usage("passphrase too long");
359 goto end;
360 }
361 strncpy(passphrase.ptr, optarg, BUF_LEN);
362 passphrase.len = min(strlen(optarg), BUF_LEN);
363 continue;
364
365 case 'u': /* --usercert */
366 usercertfile = optarg;
367 continue;
368
369 case 'g': /* --groups */
370 groups = optarg;
371 continue;
372
373 case 'D': /* --days */
374 if (optarg == NULL || !isdigit(optarg[0]))
375 {
376 usage("missing number of days");
377 goto end;
378 }
379 else
380 {
381 char *endptr;
382 long days = strtol(optarg, &endptr, 0);
383
384 if (*endptr != '\0' || endptr == optarg || days <= 0)
385 {
386 usage("<days> must be a positive number");
387 goto end;
388 }
389 validity += 24*3600*days;
390 }
391 continue;
392
393 case 'H': /* --hours */
394 if (optarg == NULL || !isdigit(optarg[0]))
395 {
396 usage("missing number of hours");
397 goto end;
398 }
399 else
400 {
401 char *endptr;
402 long hours = strtol(optarg, &endptr, 0);
403
404 if (*endptr != '\0' || endptr == optarg || hours <= 0)
405 {
406 usage("<hours> must be a positive number");
407 goto end;
408 }
409 validity += 3600*hours;
410 }
411 continue;
412
413 case 'S': /* --startdate */
414 if (optarg == NULL || strlen(optarg) != 15 || optarg[14] != 'Z')
415 {
416 usage("date format must be YYYYMMDDHHMMSSZ");
417 goto end;
418 }
419 else
420 {
421 chunk_t date = { optarg, 15 };
422
423 notBefore = asn1_to_time(&date, ASN1_GENERALIZEDTIME);
424 }
425 continue;
426
427 case 'E': /* --enddate */
428 if (optarg == NULL || strlen(optarg) != 15 || optarg[14] != 'Z')
429 {
430 usage("date format must be YYYYMMDDHHMMSSZ");
431 goto end;
432 }
433 else
434 {
435 chunk_t date = { optarg, 15 };
436 notAfter = asn1_to_time(&date, ASN1_GENERALIZEDTIME);
437 }
438 continue;
439
440 case 'o': /* --out */
441 outfile = optarg;
442 continue;
443
444 case 'd': /* --debug */
445 debug_level = atoi(optarg);
446 continue;
447
448 default:
449 usage("");
450 status = 0;
451 goto end;
452 }
453 /* break from loop */
454 break;
455 }
456
457 if (optind != argc)
458 {
459 usage("unexpected argument");
460 goto end;
461 }
462
463 DBG1("starting openac (strongSwan Version %s)", VERSION);
464
465 #ifdef INTEGRITY_TEST
466 DBG1("integrity test of libstrongswan code");
467 if (fips_verify_hmac_signature(hmac_key, hmac_signature))
468 {
469 DBG1(" integrity test passed");
470 }
471 else
472 {
473 DBG1(" integrity test failed");
474 status = 3;
475 goto end;
476 }
477 #endif /* INTEGRITY_TEST */
478
479 /* load the signer's RSA private key */
480 if (keyfile != NULL)
481 {
482 signerKey = private_key_create_from_file(keyfile, &passphrase);
483
484 if (signerKey == NULL)
485 {
486 goto end;
487 }
488 }
489
490 /* load the signer's X.509 certificate */
491 if (certfile != NULL)
492 {
493 signerCert = lib->creds->create(lib->creds,
494 CRED_CERTIFICATE, CERT_X509,
495 BUILD_FROM_FILE, certfile,
496 BUILD_X509_FLAG, 0,
497 BUILD_END);
498 if (signerCert == NULL)
499 {
500 goto end;
501 }
502 }
503
504 /* load the users's X.509 certificate */
505 if (usercertfile != NULL)
506 {
507 userCert = lib->creds->create(lib->creds,
508 CRED_CERTIFICATE, CERT_X509,
509 BUILD_FROM_FILE, usercertfile,
510 BUILD_X509_FLAG, 0,
511 BUILD_END);
512 if (userCert == NULL)
513 {
514 goto end;
515 }
516 }
517
518 /* compute validity interval */
519 validity = (validity)? validity : DEFAULT_VALIDITY;
520 notBefore = (notBefore == UNDEFINED_TIME) ? time(NULL) : notBefore;
521 notAfter = (notAfter == UNDEFINED_TIME) ? time(NULL) + validity : notAfter;
522
523 /* build and parse attribute certificate */
524 if (userCert != NULL && signerCert != NULL && signerKey != NULL)
525 {
526 /* read the serial number and increment it by one */
527 serial = read_serial();
528
529 attr_cert = lib->creds->create(lib->creds,
530 CRED_CERTIFICATE, CERT_X509_AC,
531 BUILD_CERT, userCert->get_ref(userCert),
532 BUILD_NOT_BEFORE_TIME, notBefore,
533 BUILD_NOT_AFTER_TIME, notAfter,
534 BUILD_SERIAL, serial,
535 BUILD_IETF_GROUP_ATTR, groups,
536 BUILD_SIGNING_CERT, signerCert->get_ref(signerCert),
537 BUILD_SIGNING_KEY, signerKey->get_ref(signerKey),
538 BUILD_END);
539 if (!attr_cert)
540 {
541 goto end;
542 }
543
544 /* write the attribute certificate to file */
545 attr_chunk = attr_cert->get_encoding(attr_cert);
546 if (chunk_write(attr_chunk, outfile, 0022, TRUE))
547 {
548 DBG1(" wrote attribute cert file '%s' (%u bytes)", outfile, attr_chunk.len);
549 write_serial(serial);
550 status = 0;
551 }
552 }
553 else
554 {
555 usage("some of the mandatory parameters --usercert --cert --key "
556 "are missing");
557 }
558
559 end:
560 /* delete all dynamically allocated objects */
561 DESTROY_IF(signerKey);
562 DESTROY_IF(signerCert);
563 DESTROY_IF(userCert);
564 DESTROY_IF(attr_cert);
565 free(attr_chunk.ptr);
566 free(serial.ptr);
567 closelog();
568 dbg = dbg_default;
569 options->destroy(options);
570 library_deinit();
571 exit(status);
572 }