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