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