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