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