Add a scepclient option to specify a CA identifier to fetch certs for
[strongswan.git] / src / scepclient / scepclient.c
1 /*
2 * Copyright (C) 2012 Tobias Brunner
3 * Copyright (C) 2005 Jan Hutter, Martin Willi
4 * Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 */
16
17 #include <stdarg.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <getopt.h>
22 #include <ctype.h>
23 #include <unistd.h>
24 #include <time.h>
25 #include <limits.h>
26 #include <syslog.h>
27
28 #include <library.h>
29 #include <utils/debug.h>
30 #include <asn1/asn1.h>
31 #include <asn1/oid.h>
32 #include <utils/optionsfrom.h>
33 #include <collections/enumerator.h>
34 #include <collections/linked_list.h>
35 #include <crypto/hashers/hasher.h>
36 #include <crypto/crypters/crypter.h>
37 #include <crypto/proposal/proposal_keywords.h>
38 #include <credentials/keys/private_key.h>
39 #include <credentials/keys/public_key.h>
40 #include <credentials/certificates/certificate.h>
41 #include <credentials/certificates/x509.h>
42 #include <credentials/certificates/pkcs10.h>
43 #include <plugins/plugin.h>
44
45 #include "scep.h"
46
47 /*
48 * definition of some defaults
49 */
50
51 /* some paths */
52 #define REQ_PATH IPSEC_CONFDIR "/ipsec.d/reqs"
53 #define HOST_CERT_PATH IPSEC_CONFDIR "/ipsec.d/certs"
54 #define CA_CERT_PATH IPSEC_CONFDIR "/ipsec.d/cacerts"
55 #define PRIVATE_KEY_PATH IPSEC_CONFDIR "/ipsec.d/private"
56
57 /* default name of DER-encoded PKCS#1 private key file */
58 #define DEFAULT_FILENAME_PKCS1 "myKey.der"
59
60 /* default name of DER-encoded PKCS#10 certificate request file */
61 #define DEFAULT_FILENAME_PKCS10 "myReq.der"
62
63 /* default name of DER-encoded PKCS#7 file */
64 #define DEFAULT_FILENAME_PKCS7 "pkcs7.der"
65
66 /* default name of DER-encoded self-signed X.509 certificate file */
67 #define DEFAULT_FILENAME_CERT_SELF "selfCert.der"
68
69 /* default name of DER-encoded X.509 certificate file */
70 #define DEFAULT_FILENAME_CERT "myCert.der"
71
72 /* default name of DER-encoded CA cert file used for key encipherment */
73 #define DEFAULT_FILENAME_CACERT_ENC "caCert.der"
74
75 /* default name of the der encoded CA cert file used for signature verification */
76 #define DEFAULT_FILENAME_CACERT_SIG "caCert.der"
77
78 /* default prefix of the der encoded CA certificates received from the SCEP server */
79 #define DEFAULT_FILENAME_PREFIX_CACERT "caCert.der"
80
81 /* default certificate validity */
82 #define DEFAULT_CERT_VALIDITY 5 * 3600 * 24 * 365 /* seconds */
83
84 /* default polling time interval in SCEP manual mode */
85 #define DEFAULT_POLL_INTERVAL 20 /* seconds */
86
87 /* default key length for self-generated RSA keys */
88 #define DEFAULT_RSA_KEY_LENGTH 2048 /* bits */
89
90 /* default distinguished name */
91 #define DEFAULT_DN "C=CH, O=Linux strongSwan, CN="
92
93 /* minimum RSA key size */
94 #define RSA_MIN_OCTETS (512 / BITS_PER_BYTE)
95
96 /* challenge password buffer size */
97 #define MAX_PASSWORD_LENGTH 256
98
99 /* Max length of filename for tempfile */
100 #define MAX_TEMP_FILENAME_LENGTH 256
101
102
103 /* current scepclient version */
104 static const char *scepclient_version = "1.0";
105
106 /* by default the CRL policy is lenient */
107 bool strict_crl_policy = FALSE;
108
109 /* by default pluto does not check crls dynamically */
110 long crl_check_interval = 0;
111
112 /* by default pluto logs out after every smartcard use */
113 bool pkcs11_keep_state = FALSE;
114
115 /* options read by optionsfrom */
116 options_t *options;
117
118 /*
119 * Global variables
120 */
121 chunk_t pkcs1;
122 chunk_t pkcs7;
123 chunk_t challengePassword;
124 chunk_t serialNumber;
125 chunk_t transID;
126 chunk_t fingerprint;
127 chunk_t encoding;
128 chunk_t pkcs10_encoding;
129 chunk_t issuerAndSubject;
130 chunk_t getCertInitial;
131 chunk_t scep_response;
132
133 linked_list_t *subjectAltNames;
134
135 identification_t *subject = NULL;
136 private_key_t *private_key = NULL;
137 public_key_t *public_key = NULL;
138 certificate_t *x509_signer = NULL;
139 certificate_t *x509_ca_enc = NULL;
140 certificate_t *x509_ca_sig = NULL;
141 certificate_t *pkcs10_req = NULL;
142
143 /* logging */
144 static bool log_to_stderr = TRUE;
145 static bool log_to_syslog = TRUE;
146 static level_t default_loglevel = 1;
147
148 /**
149 * logging function for scepclient
150 */
151 static void scepclient_dbg(debug_t group, level_t level, char *fmt, ...)
152 {
153 char buffer[8192];
154 char *current = buffer, *next;
155 va_list args;
156
157 if (level <= default_loglevel)
158 {
159 if (log_to_stderr)
160 {
161 va_start(args, fmt);
162 vfprintf(stderr, fmt, args);
163 va_end(args);
164 fprintf(stderr, "\n");
165 }
166 if (log_to_syslog)
167 {
168 /* write in memory buffer first */
169 va_start(args, fmt);
170 vsnprintf(buffer, sizeof(buffer), fmt, args);
171 va_end(args);
172
173 /* do a syslog with every line */
174 while (current)
175 {
176 next = strchr(current, '\n');
177 if (next)
178 {
179 *(next++) = '\0';
180 }
181 syslog(LOG_INFO, "%s\n", current);
182 current = next;
183 }
184 }
185 }
186 }
187
188 /**
189 * Initialize logging to stderr/syslog
190 */
191 static void init_log(const char *program)
192 {
193 dbg = scepclient_dbg;
194
195 if (log_to_stderr)
196 {
197 setbuf(stderr, NULL);
198 }
199 if (log_to_syslog)
200 {
201 openlog(program, LOG_CONS | LOG_NDELAY | LOG_PID, LOG_AUTHPRIV);
202 }
203 }
204
205 /**
206 * join two paths if filename is not absolute
207 */
208 static void join_paths(char *target, size_t target_size, char *parent,
209 char *filename)
210 {
211 if (*filename == '/' || *filename == '.')
212 {
213 snprintf(target, target_size, "%s", filename);
214 }
215 else
216 {
217 snprintf(target, target_size, "%s/%s", parent, filename);
218 }
219 }
220
221 /**
222 * add a suffix to a given filename, properly handling extensions like '.der'
223 */
224 static void add_path_suffix(char *target, size_t target_size, char *filename,
225 char *suffix_fmt, ...)
226 {
227 char suffix[PATH_MAX], *start, *dot;
228 va_list args;
229
230 va_start(args, suffix_fmt);
231 vsnprintf(suffix, sizeof(suffix), suffix_fmt, args);
232 va_end(args);
233
234 start = strrchr(filename, '/');
235 start = start ?: filename;
236 dot = strrchr(start, '.');
237
238 if (!dot || dot == start || dot[1] == '\0')
239 { /* no extension add suffix at the end */
240 snprintf(target, target_size, "%s%s", filename, suffix);
241 }
242 else
243 { /* add the suffix between the filename and the extension */
244 snprintf(target, target_size, "%.*s%s%s", (int)(dot - filename),
245 filename, suffix, dot);
246 }
247 }
248
249 /**
250 * @brief exit scepclient
251 *
252 * @param status 0 = OK, 1 = general discomfort
253 */
254 static void exit_scepclient(err_t message, ...)
255 {
256 int status = 0;
257
258 DESTROY_IF(subject);
259 DESTROY_IF(private_key);
260 DESTROY_IF(public_key);
261 DESTROY_IF(x509_signer);
262 DESTROY_IF(x509_ca_enc);
263 DESTROY_IF(x509_ca_sig);
264 DESTROY_IF(pkcs10_req);
265 subjectAltNames->destroy_offset(subjectAltNames,
266 offsetof(identification_t, destroy));
267 free(pkcs1.ptr);
268 free(pkcs7.ptr);
269 free(serialNumber.ptr);
270 free(transID.ptr);
271 free(fingerprint.ptr);
272 free(encoding.ptr);
273 free(pkcs10_encoding.ptr);
274 free(issuerAndSubject.ptr);
275 free(getCertInitial.ptr);
276 free(scep_response.ptr);
277 options->destroy(options);
278
279 /* print any error message to stderr */
280 if (message != NULL && *message != '\0')
281 {
282 va_list args;
283 char m[8192];
284
285 va_start(args, message);
286 vsnprintf(m, sizeof(m), message, args);
287 va_end(args);
288
289 fprintf(stderr, "error: %s\n", m);
290 status = -1;
291 }
292 library_deinit();
293 exit(status);
294 }
295
296 /**
297 * @brief prints the program version and exits
298 *
299 */
300 static void version(void)
301 {
302 printf("scepclient %s\n", scepclient_version);
303 exit_scepclient(NULL);
304 }
305
306 /**
307 * @brief prints the usage of the program to the stderr output
308 *
309 * If message is set, program is exitet with 1 (error)
310 * @param message message in case of an error
311 */
312 static void usage(const char *message)
313 {
314 fprintf(stderr,
315 "Usage: scepclient\n"
316 " --help (-h) show usage and exit\n"
317 " --version (-v) show version and exit\n"
318 " --quiet (-q) do not write log output to stderr\n"
319 " --in (-i) <type>[=<filename>] use <filename> of <type> for input\n"
320 " <type> = pkcs1 | pkcs10 | cert-self\n"
321 " cacert-enc | cacert-sig\n"
322 " - if no pkcs1 input is defined, an RSA\n"
323 " key will be generated\n"
324 " - if no pkcs10 input is defined, a\n"
325 " PKCS#10 request will be generated\n"
326 " - if no cert-self input is defined, a\n"
327 " self-signed certificate will be generated\n"
328 " - if no filename is given, default is used\n"
329 " --out (-o) <type>[=<filename>] write output of <type> to <filename>\n"
330 " multiple outputs are allowed\n"
331 " <type> = pkcs1 | pkcs10 | pkcs7 | cert-self |\n"
332 " cert | cacert\n"
333 " - type cacert defines filename prefix of\n"
334 " received CA certificate(s)\n"
335 " - if no filename is given, default is used\n"
336 " --optionsfrom (-+) <filename> reads additional options from given file\n"
337 " --force (-f) force existing file(s)\n"
338 "\n"
339 "Options for key generation (pkcs1):\n"
340 " --keylength (-k) <bits> key length for RSA key generation\n"
341 " (default: 2048 bits)\n"
342 "\n"
343 "Options for validity:\n"
344 " --days (-D) <days> validity in days\n"
345 " --startdate (-S) <YYMMDDHHMMSS>Z not valid before date\n"
346 " --enddate (-E) <YYMMDDHHMMSS>Z not valid after date\n"
347 "\n"
348 "Options for request generation (pkcs10):\n"
349 " --dn (-d) <dn> comma separated list of distinguished names\n"
350 " --subjectAltName (-s) <t>=<v> include subjectAltName in certificate request\n"
351 " <t> = email | dns | ip \n"
352 " --password (-p) <pw> challenge password\n"
353 " - use '%%prompt' as pw for a password prompt\n"
354 " --algorithm (-a) [<type>=]<algo> algorithm to be used for PKCS#7 encryption,\n"
355 " PKCS#7 digest or PKCS#10 signature\n"
356 " <type> = enc | dgst | sig\n"
357 " - if no type is given enc is assumed\n"
358 " <algo> = des (default) | 3des | aes128 |\n"
359 " aes192 | aes256 | camellia128 |\n"
360 " camellia192 | camellia256\n"
361 " <algo> = md5 (default) | sha1 | sha256 |\n"
362 " sha384 | sha512\n"
363 "\n"
364 "Options for CA certificate acquisition:\n"
365 " --caname (-c) <name> name of CA to fetch CA certificate(s)\n"
366 " (default: CAIdentifier)\n"
367 "Options for enrollment (cert):\n"
368 " --url (-u) <url> url of the SCEP server\n"
369 " --method (-m) post | get http request type\n"
370 " --interval (-t) <seconds> poll interval in seconds (default 20s)\n"
371 " --maxpolltime (-x) <seconds> max poll time in seconds when in manual mode\n"
372 " (default: unlimited)\n"
373 "\n"
374 "Debugging output:\n"
375 " --debug (-l) <level> changes the log level (-1..4, default: 1)\n"
376 );
377 exit_scepclient(message);
378 }
379
380 /**
381 * @brief main of scepclient
382 *
383 * @param argc number of arguments
384 * @param argv pointer to the argument values
385 */
386 int main(int argc, char **argv)
387 {
388 /* external values */
389 extern char * optarg;
390 extern int optind;
391
392 /* type of input and output files */
393 typedef enum {
394 PKCS1 = 0x01,
395 PKCS10 = 0x02,
396 PKCS7 = 0x04,
397 CERT_SELF = 0x08,
398 CERT = 0x10,
399 CACERT_ENC = 0x20,
400 CACERT_SIG = 0x40,
401 } scep_filetype_t;
402
403 /* filetype to read from, defaults to "generate a key" */
404 scep_filetype_t filetype_in = 0;
405
406 /* filetype to write to, no default here */
407 scep_filetype_t filetype_out = 0;
408
409 /* input files */
410 char *file_in_pkcs1 = DEFAULT_FILENAME_PKCS1;
411 char *file_in_pkcs10 = DEFAULT_FILENAME_PKCS10;
412 char *file_in_cert_self = DEFAULT_FILENAME_CERT_SELF;
413 char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
414 char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;
415
416 /* output files */
417 char *file_out_pkcs1 = DEFAULT_FILENAME_PKCS1;
418 char *file_out_pkcs10 = DEFAULT_FILENAME_PKCS10;
419 char *file_out_pkcs7 = DEFAULT_FILENAME_PKCS7;
420 char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
421 char *file_out_cert = DEFAULT_FILENAME_CERT;
422 char *file_out_ca_cert = DEFAULT_FILENAME_CACERT_ENC;
423
424 /* by default user certificate is requested */
425 bool request_ca_certificate = FALSE;
426
427 /* by default existing files are not overwritten */
428 bool force = FALSE;
429
430 /* length of RSA key in bits */
431 u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;
432
433 /* validity of self-signed certificate */
434 time_t validity = DEFAULT_CERT_VALIDITY;
435 time_t notBefore = 0;
436 time_t notAfter = 0;
437
438 /* distinguished name for requested certificate, ASCII format */
439 char *distinguishedName = NULL;
440
441 /* challenge password */
442 char challenge_password_buffer[MAX_PASSWORD_LENGTH];
443
444 /* symmetric encryption algorithm used by pkcs7, default is DES */
445 encryption_algorithm_t pkcs7_symmetric_cipher = ENCR_DES;
446 size_t pkcs7_key_size = 0;
447
448 /* digest algorithm used by pkcs7, default is MD5 */
449 hash_algorithm_t pkcs7_digest_alg = HASH_MD5;
450
451 /* signature algorithm used by pkcs10, default is MD5 */
452 hash_algorithm_t pkcs10_signature_alg = HASH_MD5;
453
454 /* URL of the SCEP-Server */
455 char *scep_url = NULL;
456
457 /* Name of CA to fetch CA certs for */
458 char *ca_name = "CAIdentifier";
459
460 /* http request method, default is GET */
461 bool http_get_request = TRUE;
462
463 /* poll interval time in manual mode in seconds */
464 u_int poll_interval = DEFAULT_POLL_INTERVAL;
465
466 /* maximum poll time */
467 u_int max_poll_time = 0;
468
469 err_t ugh = NULL;
470
471 /* initialize library */
472 if (!library_init(NULL))
473 {
474 library_deinit();
475 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
476 }
477 if (lib->integrity &&
478 !lib->integrity->check_file(lib->integrity, "scepclient", argv[0]))
479 {
480 fprintf(stderr, "integrity check of scepclient failed\n");
481 library_deinit();
482 exit(SS_RC_DAEMON_INTEGRITY);
483 }
484
485 /* initialize global variables */
486 pkcs1 = chunk_empty;
487 pkcs7 = chunk_empty;
488 serialNumber = chunk_empty;
489 transID = chunk_empty;
490 fingerprint = chunk_empty;
491 encoding = chunk_empty;
492 pkcs10_encoding = chunk_empty;
493 issuerAndSubject = chunk_empty;
494 challengePassword = chunk_empty;
495 getCertInitial = chunk_empty;
496 scep_response = chunk_empty;
497 subjectAltNames = linked_list_create();
498 options = options_create();
499
500 for (;;)
501 {
502 static const struct option long_opts[] = {
503 /* name, has_arg, flag, val */
504 { "help", no_argument, NULL, 'h' },
505 { "version", no_argument, NULL, 'v' },
506 { "optionsfrom", required_argument, NULL, '+' },
507 { "quiet", no_argument, NULL, 'q' },
508 { "debug", required_argument, NULL, 'l' },
509 { "in", required_argument, NULL, 'i' },
510 { "out", required_argument, NULL, 'o' },
511 { "force", no_argument, NULL, 'f' },
512 { "keylength", required_argument, NULL, 'k' },
513 { "dn", required_argument, NULL, 'd' },
514 { "days", required_argument, NULL, 'D' },
515 { "startdate", required_argument, NULL, 'S' },
516 { "enddate", required_argument, NULL, 'E' },
517 { "subjectAltName", required_argument, NULL, 's' },
518 { "password", required_argument, NULL, 'p' },
519 { "algorithm", required_argument, NULL, 'a' },
520 { "url", required_argument, NULL, 'u' },
521 { "caname", required_argument, NULL, 'c'},
522 { "method", required_argument, NULL, 'm' },
523 { "interval", required_argument, NULL, 't' },
524 { "maxpolltime", required_argument, NULL, 'x' },
525 { 0,0,0,0 }
526 };
527
528 /* parse next option */
529 int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:c:m:t:x:APRCMS", long_opts, NULL);
530
531 switch (c)
532 {
533 case EOF: /* end of flags */
534 break;
535
536 case 'h': /* --help */
537 usage(NULL);
538
539 case 'v': /* --version */
540 version();
541
542 case 'q': /* --quiet */
543 log_to_stderr = FALSE;
544 continue;
545
546 case 'l': /* --debug <level> */
547 default_loglevel = atoi(optarg);
548 continue;
549
550 case 'i': /* --in <type> [= <filename>] */
551 {
552 char *filename = strstr(optarg, "=");
553
554 if (filename)
555 {
556 /* replace '=' by '\0' */
557 *filename = '\0';
558 /* set pointer to start of filename */
559 filename++;
560 }
561 if (strcaseeq("pkcs1", optarg))
562 {
563 filetype_in |= PKCS1;
564 if (filename)
565 file_in_pkcs1 = filename;
566 }
567 else if (strcaseeq("pkcs10", optarg))
568 {
569 filetype_in |= PKCS10;
570 if (filename)
571 file_in_pkcs10 = filename;
572 }
573 else if (strcaseeq("cacert-enc", optarg))
574 {
575 filetype_in |= CACERT_ENC;
576 if (filename)
577 file_in_cacert_enc = filename;
578 }
579 else if (strcaseeq("cacert-sig", optarg))
580 {
581 filetype_in |= CACERT_SIG;
582 if (filename)
583 file_in_cacert_sig = filename;
584 }
585 else if (strcaseeq("cert-self", optarg))
586 {
587 filetype_in |= CERT_SELF;
588 if (filename)
589 file_in_cert_self = filename;
590 }
591 else
592 {
593 usage("invalid --in file type");
594 }
595 continue;
596 }
597
598 case 'o': /* --out <type> [= <filename>] */
599 {
600 char *filename = strstr(optarg, "=");
601
602 if (filename)
603 {
604 /* replace '=' by '\0' */
605 *filename = '\0';
606 /* set pointer to start of filename */
607 filename++;
608 }
609 if (strcaseeq("pkcs1", optarg))
610 {
611 filetype_out |= PKCS1;
612 if (filename)
613 file_out_pkcs1 = filename;
614 }
615 else if (strcaseeq("pkcs10", optarg))
616 {
617 filetype_out |= PKCS10;
618 if (filename)
619 file_out_pkcs10 = filename;
620 }
621 else if (strcaseeq("pkcs7", optarg))
622 {
623 filetype_out |= PKCS7;
624 if (filename)
625 file_out_pkcs7 = filename;
626 }
627 else if (strcaseeq("cert-self", optarg))
628 {
629 filetype_out |= CERT_SELF;
630 if (filename)
631 file_out_cert_self = filename;
632 }
633 else if (strcaseeq("cert", optarg))
634 {
635 filetype_out |= CERT;
636 if (filename)
637 file_out_cert = filename;
638 }
639 else if (strcaseeq("cacert", optarg))
640 {
641 request_ca_certificate = TRUE;
642 if (filename)
643 file_out_ca_cert = filename;
644 }
645 else
646 {
647 usage("invalid --out file type");
648 }
649 continue;
650 }
651
652 case 'f': /* --force */
653 force = TRUE;
654 continue;
655
656 case '+': /* --optionsfrom <filename> */
657 if (!options->from(options, optarg, &argc, &argv, optind))
658 {
659 exit_scepclient("optionsfrom failed");
660 }
661 continue;
662
663 case 'k': /* --keylength <length> */
664 {
665 div_t q;
666
667 rsa_keylength = atoi(optarg);
668 if (rsa_keylength == 0)
669 usage("invalid keylength");
670
671 /* check if key length is a multiple of 8 bits */
672 q = div(rsa_keylength, 2*BITS_PER_BYTE);
673 if (q.rem != 0)
674 {
675 exit_scepclient("keylength is not a multiple of %d bits!"
676 , 2*BITS_PER_BYTE);
677 }
678 continue;
679 }
680
681 case 'D': /* --days */
682 if (optarg == NULL || !isdigit(optarg[0]))
683 {
684 usage("missing number of days");
685 }
686 else
687 {
688 char *endptr;
689 long days = strtol(optarg, &endptr, 0);
690
691 if (*endptr != '\0' || endptr == optarg
692 || days <= 0)
693 usage("<days> must be a positive number");
694 validity = 24*3600*days;
695 }
696 continue;
697
698 case 'S': /* --startdate */
699 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
700 {
701 usage("date format must be YYMMDDHHMMSSZ");
702 }
703 else
704 {
705 chunk_t date = { optarg, 13 };
706 notBefore = asn1_to_time(&date, ASN1_UTCTIME);
707 }
708 continue;
709
710 case 'E': /* --enddate */
711 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
712 {
713 usage("date format must be YYMMDDHHMMSSZ");
714 }
715 else
716 {
717 chunk_t date = { optarg, 13 };
718 notAfter = asn1_to_time(&date, ASN1_UTCTIME);
719 }
720 continue;
721
722 case 'd': /* --dn */
723 if (distinguishedName)
724 {
725 usage("only one distinguished name allowed");
726 }
727 distinguishedName = optarg;
728 continue;
729
730 case 's': /* --subjectAltName */
731 {
732 char *value = strstr(optarg, "=");
733
734 if (value)
735 {
736 /* replace '=' by '\0' */
737 *value = '\0';
738 /* set pointer to start of value */
739 value++;
740 }
741
742 if (strcaseeq("email", optarg) ||
743 strcaseeq("dns", optarg) ||
744 strcaseeq("ip", optarg))
745 {
746 subjectAltNames->insert_last(subjectAltNames,
747 identification_create_from_string(value));
748 continue;
749 }
750 else
751 {
752 usage("invalid --subjectAltName type");
753 continue;
754 }
755 }
756
757 case 'p': /* --password */
758 if (challengePassword.len > 0)
759 {
760 usage("only one challenge password allowed");
761 }
762 if (strcaseeq("%prompt", optarg))
763 {
764 printf("Challenge password: ");
765 if (fgets(challenge_password_buffer,
766 sizeof(challenge_password_buffer) - 1, stdin))
767 {
768 challengePassword.ptr = challenge_password_buffer;
769 /* discard the terminating '\n' from the input */
770 challengePassword.len = strlen(challenge_password_buffer) - 1;
771 }
772 else
773 {
774 usage("challenge password could not be read");
775 }
776 }
777 else
778 {
779 challengePassword.ptr = optarg;
780 challengePassword.len = strlen(optarg);
781 }
782 continue;
783
784 case 'u': /* -- url */
785 if (scep_url)
786 {
787 usage("only one URL argument allowed");
788 }
789 scep_url = optarg;
790 continue;
791
792 case 'c': /* -- caname */
793 ca_name = optarg;
794 continue;
795
796 case 'm': /* --method */
797 if (strcaseeq("get", optarg))
798 {
799 http_get_request = TRUE;
800 }
801 else if (strcaseeq("post", optarg))
802 {
803 http_get_request = FALSE;
804 }
805 else
806 {
807 usage("invalid http request method specified");
808 }
809 continue;
810
811 case 't': /* --interval */
812 poll_interval = atoi(optarg);
813 if (poll_interval <= 0)
814 {
815 usage("invalid interval specified");
816 }
817 continue;
818
819 case 'x': /* --maxpolltime */
820 max_poll_time = atoi(optarg);
821 continue;
822
823 case 'a': /*--algorithm [<type>=]algo */
824 {
825 const proposal_token_t *token;
826 char *type = optarg;
827 char *algo = strstr(optarg, "=");
828
829 if (algo)
830 {
831 *algo = '\0';
832 algo++;
833 }
834 else
835 {
836 type = "enc";
837 algo = optarg;
838 }
839
840 if (strcaseeq("enc", type))
841 {
842 token = lib->proposal->get_token(lib->proposal, algo);
843 if (token == NULL || token->type != ENCRYPTION_ALGORITHM)
844 {
845 usage("invalid algorithm specified");
846 }
847 pkcs7_symmetric_cipher = token->algorithm;
848 pkcs7_key_size = token->keysize;
849 if (encryption_algorithm_to_oid(token->algorithm,
850 token->keysize) == OID_UNKNOWN)
851 {
852 usage("unsupported encryption algorithm specified");
853 }
854 }
855 else if (strcaseeq("dgst", type) ||
856 strcaseeq("sig", type))
857 {
858 hash_algorithm_t hash;
859
860 token = lib->proposal->get_token(lib->proposal, algo);
861 if (token == NULL || token->type != INTEGRITY_ALGORITHM)
862 {
863 usage("invalid algorithm specified");
864 }
865 hash = hasher_algorithm_from_integrity(token->algorithm,
866 NULL);
867 if (hash == OID_UNKNOWN)
868 {
869 usage("invalid algorithm specified");
870 }
871 if (strcaseeq("dgst", type))
872 {
873 pkcs7_digest_alg = hash;
874 }
875 else
876 {
877 pkcs10_signature_alg = hash;
878 }
879 }
880 else
881 {
882 usage("invalid --algorithm type");
883 }
884 continue;
885 }
886 default:
887 usage("unknown option");
888 }
889 /* break from loop */
890 break;
891 }
892
893 init_log("scepclient");
894
895 /* load plugins, further infrastructure may need it */
896 if (!lib->plugins->load(lib->plugins, NULL,
897 lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS)))
898 {
899 exit_scepclient("plugin loading failed");
900 }
901 DBG1(DBG_APP, " loaded plugins: %s",
902 lib->plugins->loaded_plugins(lib->plugins));
903
904 if ((filetype_out == 0) && (!request_ca_certificate))
905 {
906 usage("--out filetype required");
907 }
908 if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
909 {
910 usage("in CA certificate request, no other --in or --out option allowed");
911 }
912
913 /* check if url is given, if cert output defined */
914 if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
915 {
916 usage("URL of SCEP server required");
917 }
918
919 /* check for sanity of --in/--out */
920 if (!filetype_in && (filetype_in > filetype_out))
921 {
922 usage("cannot generate --out of given --in!");
923 }
924
925 /* get CA cert */
926 if (request_ca_certificate)
927 {
928 char ca_path[PATH_MAX];
929 pkcs7_t *pkcs7;
930
931 if (!scep_http_request(scep_url, chunk_create(ca_name, strlen(ca_name)),
932 SCEP_GET_CA_CERT, http_get_request, &scep_response))
933 {
934 exit_scepclient("did not receive a valid scep response");
935 }
936
937 join_paths(ca_path, sizeof(ca_path), CA_CERT_PATH, file_out_ca_cert);
938
939 pkcs7 = pkcs7_create_from_chunk(scep_response, 0);
940 if (!pkcs7 || !pkcs7->parse_signedData(pkcs7, NULL))
941 { /* no PKCS#7 encoded CA+RA certificates, assume simple CA cert */
942 DESTROY_IF(pkcs7);
943 if (!chunk_write(scep_response, ca_path, "ca cert", 0022, force))
944 {
945 exit_scepclient("could not write ca cert file '%s'", ca_path);
946 }
947 }
948 else
949 {
950 enumerator_t *enumerator;
951 certificate_t *cert;
952 int ra_certs = 0, ca_certs = 0;
953 int ra_index = 1, ca_index = 1;
954
955 enumerator = pkcs7->create_certificate_enumerator(pkcs7);
956 while (enumerator->enumerate(enumerator, &cert))
957 {
958 x509_t *x509 = (x509_t*)cert;
959 if (x509->get_flags(x509) & X509_CA)
960 {
961 ca_certs++;
962 }
963 else
964 {
965 ra_certs++;
966 }
967 }
968 enumerator->destroy(enumerator);
969
970 enumerator = pkcs7->create_certificate_enumerator(pkcs7);
971 while (enumerator->enumerate(enumerator, &cert))
972 {
973 x509_t *x509 = (x509_t*)cert;
974 bool ca_cert = x509->get_flags(x509) & X509_CA;
975 char cert_path[PATH_MAX], *path = ca_path;
976
977 if (ca_cert && ca_certs > 1)
978 {
979 add_path_suffix(cert_path, sizeof(cert_path), ca_path,
980 "-%.1d", ca_index++);
981 path = cert_path;
982 }
983 else if (!ca_cert)
984 { /* use CA name as base for RA certs */
985 if (ra_certs > 1)
986 {
987 add_path_suffix(cert_path, sizeof(cert_path), ca_path,
988 "-ra-%.1d", ra_index++);
989 }
990 else
991 {
992 add_path_suffix(cert_path, sizeof(cert_path), ca_path,
993 "-ra");
994 }
995 path = cert_path;
996 }
997
998 if (!cert->get_encoding(cert, CERT_ASN1_DER, &encoding) ||
999 !chunk_write(encoding, path,
1000 ca_cert ? "ca cert" : "ra cert", 0022, force))
1001 {
1002 exit_scepclient("could not write cert file '%s'", path);
1003 }
1004 chunk_free(&encoding);
1005 }
1006 enumerator->destroy(enumerator);
1007 pkcs7->destroy(pkcs7);
1008 }
1009 exit_scepclient(NULL); /* no further output required */
1010 }
1011
1012 /*
1013 * input of PKCS#1 file
1014 */
1015 if (filetype_in & PKCS1) /* load an RSA key pair from file */
1016 {
1017 char path[PATH_MAX];
1018
1019 join_paths(path, sizeof(path), PRIVATE_KEY_PATH, file_in_pkcs1);
1020
1021 private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
1022 BUILD_FROM_FILE, path, BUILD_END);
1023 }
1024 else /* generate an RSA key pair */
1025 {
1026 private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
1027 BUILD_KEY_SIZE, rsa_keylength,
1028 BUILD_END);
1029 }
1030 if (private_key == NULL)
1031 {
1032 exit_scepclient("no RSA private key available");
1033 }
1034 public_key = private_key->get_public_key(private_key);
1035
1036 /* check for minimum key length */
1037 if (private_key->get_keysize(private_key) < RSA_MIN_OCTETS / BITS_PER_BYTE)
1038 {
1039 exit_scepclient("length of RSA key has to be at least %d bits",
1040 RSA_MIN_OCTETS * BITS_PER_BYTE);
1041 }
1042
1043 /*
1044 * input of PKCS#10 file
1045 */
1046 if (filetype_in & PKCS10)
1047 {
1048 char path[PATH_MAX];
1049
1050 join_paths(path, sizeof(path), REQ_PATH, file_in_pkcs10);
1051
1052 pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
1053 CERT_PKCS10_REQUEST, BUILD_FROM_FILE,
1054 path, BUILD_END);
1055 if (!pkcs10_req)
1056 {
1057 exit_scepclient("could not read certificate request '%s'", path);
1058 }
1059 subject = pkcs10_req->get_subject(pkcs10_req);
1060 subject = subject->clone(subject);
1061 }
1062 else
1063 {
1064 if (distinguishedName == NULL)
1065 {
1066 char buf[BUF_LEN];
1067 int n = sprintf(buf, DEFAULT_DN);
1068
1069 /* set the common name to the hostname */
1070 if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
1071 {
1072 exit_scepclient("no hostname defined, use "
1073 "--dn <distinguished name> option");
1074 }
1075 distinguishedName = buf;
1076 }
1077
1078 DBG2(DBG_APP, "dn: '%s'", distinguishedName);
1079 subject = identification_create_from_string(distinguishedName);
1080 if (subject->get_type(subject) != ID_DER_ASN1_DN)
1081 {
1082 exit_scepclient("parsing of distinguished name failed");
1083 }
1084
1085 DBG2(DBG_APP, "building pkcs10 object:");
1086 pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
1087 CERT_PKCS10_REQUEST,
1088 BUILD_SIGNING_KEY, private_key,
1089 BUILD_SUBJECT, subject,
1090 BUILD_SUBJECT_ALTNAMES, subjectAltNames,
1091 BUILD_CHALLENGE_PWD, challengePassword,
1092 BUILD_DIGEST_ALG, pkcs10_signature_alg,
1093 BUILD_END);
1094 if (!pkcs10_req)
1095 {
1096 exit_scepclient("generating pkcs10 request failed");
1097 }
1098 }
1099 pkcs10_req->get_encoding(pkcs10_req, CERT_ASN1_DER, &pkcs10_encoding);
1100 fingerprint = scep_generate_pkcs10_fingerprint(pkcs10_encoding);
1101 DBG1(DBG_APP, " fingerprint: %s", fingerprint.ptr);
1102
1103 /*
1104 * output of PKCS#10 file
1105 */
1106 if (filetype_out & PKCS10)
1107 {
1108 char path[PATH_MAX];
1109
1110 join_paths(path, sizeof(path), REQ_PATH, file_out_pkcs10);
1111
1112 if (!chunk_write(pkcs10_encoding, path, "pkcs10", 0022, force))
1113 {
1114 exit_scepclient("could not write pkcs10 file '%s'", path);
1115 }
1116 filetype_out &= ~PKCS10; /* delete PKCS10 flag */
1117 }
1118
1119 if (!filetype_out)
1120 {
1121 exit_scepclient(NULL); /* no further output required */
1122 }
1123
1124 /*
1125 * output of PKCS#1 file
1126 */
1127 if (filetype_out & PKCS1)
1128 {
1129 char path[PATH_MAX];
1130
1131 join_paths(path, sizeof(path), PRIVATE_KEY_PATH, file_out_pkcs1);
1132
1133 DBG2(DBG_APP, "building pkcs1 object:");
1134 if (!private_key->get_encoding(private_key, PRIVKEY_ASN1_DER, &pkcs1) ||
1135 !chunk_write(pkcs1, path, "pkcs1", 0066, force))
1136 {
1137 exit_scepclient("could not write pkcs1 file '%s'", path);
1138 }
1139 filetype_out &= ~PKCS1; /* delete PKCS1 flag */
1140 }
1141
1142 if (!filetype_out)
1143 {
1144 exit_scepclient(NULL); /* no further output required */
1145 }
1146
1147 scep_generate_transaction_id(public_key, &transID, &serialNumber);
1148 DBG1(DBG_APP, " transaction ID: %.*s", (int)transID.len, transID.ptr);
1149
1150 /*
1151 * read or generate self-signed X.509 certificate
1152 */
1153 if (filetype_in & CERT_SELF)
1154 {
1155 char path[PATH_MAX];
1156
1157 join_paths(path, sizeof(path), HOST_CERT_PATH, file_in_cert_self);
1158
1159 x509_signer = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
1160 BUILD_FROM_FILE, path, BUILD_END);
1161 if (!x509_signer)
1162 {
1163 exit_scepclient("could not read certificate file '%s'", path);
1164 }
1165 }
1166 else
1167 {
1168 notBefore = notBefore ? notBefore : time(NULL);
1169 notAfter = notAfter ? notAfter : (notBefore + validity);
1170 x509_signer = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
1171 BUILD_SIGNING_KEY, private_key,
1172 BUILD_PUBLIC_KEY, public_key,
1173 BUILD_SUBJECT, subject,
1174 BUILD_NOT_BEFORE_TIME, notBefore,
1175 BUILD_NOT_AFTER_TIME, notAfter,
1176 BUILD_SERIAL, serialNumber,
1177 BUILD_SUBJECT_ALTNAMES, subjectAltNames,
1178 BUILD_END);
1179 if (!x509_signer)
1180 {
1181 exit_scepclient("generating certificate failed");
1182 }
1183 }
1184
1185 /*
1186 * output of self-signed X.509 certificate file
1187 */
1188 if (filetype_out & CERT_SELF)
1189 {
1190 char path[PATH_MAX];
1191
1192 join_paths(path, sizeof(path), HOST_CERT_PATH, file_out_cert_self);
1193
1194 if (!x509_signer->get_encoding(x509_signer, CERT_ASN1_DER, &encoding))
1195 {
1196 exit_scepclient("encoding certificate failed");
1197 }
1198 if (!chunk_write(encoding, path, "self-signed cert", 0022, force))
1199 {
1200 exit_scepclient("could not write self-signed cert file '%s'", path);
1201 }
1202 chunk_free(&encoding);
1203 filetype_out &= ~CERT_SELF; /* delete CERT_SELF flag */
1204 }
1205
1206 if (!filetype_out)
1207 {
1208 exit_scepclient(NULL); /* no further output required */
1209 }
1210
1211 /*
1212 * load ca encryption certificate
1213 */
1214 {
1215 char path[PATH_MAX];
1216
1217 join_paths(path, sizeof(path), CA_CERT_PATH, file_in_cacert_enc);
1218
1219 x509_ca_enc = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
1220 BUILD_FROM_FILE, path, BUILD_END);
1221 if (!x509_ca_enc)
1222 {
1223 exit_scepclient("could not load encryption cacert file '%s'", path);
1224 }
1225 }
1226
1227 /*
1228 * input of PKCS#7 file
1229 */
1230 if (filetype_in & PKCS7)
1231 {
1232 /* user wants to load a pkcs7 encrypted request
1233 * operation is not yet supported!
1234 * would require additional parsing of transaction-id
1235
1236 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
1237
1238 */
1239 }
1240 else
1241 {
1242 DBG2(DBG_APP, "building pkcs7 request");
1243 pkcs7 = scep_build_request(pkcs10_encoding,
1244 transID, SCEP_PKCSReq_MSG, x509_ca_enc,
1245 pkcs7_symmetric_cipher, pkcs7_key_size,
1246 x509_signer, pkcs7_digest_alg, private_key);
1247 if (!pkcs7.ptr)
1248 {
1249 exit_scepclient("failed to build pkcs7 request");
1250 }
1251 }
1252
1253 /*
1254 * output pkcs7 encrypted and signed certificate request
1255 */
1256 if (filetype_out & PKCS7)
1257 {
1258 char path[PATH_MAX];
1259
1260 join_paths(path, sizeof(path), REQ_PATH, file_out_pkcs7);
1261
1262 if (!chunk_write(pkcs7, path, "pkcs7 encrypted request", 0022, force))
1263 {
1264 exit_scepclient("could not write pkcs7 file '%s'", path);
1265 }
1266 filetype_out &= ~PKCS7; /* delete PKCS7 flag */
1267 }
1268
1269 if (!filetype_out)
1270 {
1271 exit_scepclient(NULL); /* no further output required */
1272 }
1273
1274 /*
1275 * output certificate fetch from SCEP server
1276 */
1277 if (filetype_out & CERT)
1278 {
1279 bool stored = FALSE;
1280 certificate_t *cert;
1281 enumerator_t *enumerator;
1282 char path[PATH_MAX];
1283 time_t poll_start = 0;
1284 pkcs7_t *data = NULL;
1285 scep_attributes_t attrs = empty_scep_attributes;
1286
1287 join_paths(path, sizeof(path), CA_CERT_PATH, file_in_cacert_sig);
1288
1289 x509_ca_sig = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
1290 BUILD_FROM_FILE, path, BUILD_END);
1291 if (!x509_ca_sig)
1292 {
1293 exit_scepclient("could not load signature cacert file '%s'", path);
1294 }
1295
1296 if (!scep_http_request(scep_url, pkcs7, SCEP_PKI_OPERATION,
1297 http_get_request, &scep_response))
1298 {
1299 exit_scepclient("did not receive a valid scep response");
1300 }
1301 ugh = scep_parse_response(scep_response, transID, &data, &attrs,
1302 x509_ca_sig);
1303 if (ugh != NULL)
1304 {
1305 exit_scepclient(ugh);
1306 }
1307
1308 /* in case of manual mode, we are going into a polling loop */
1309 if (attrs.pkiStatus == SCEP_PENDING)
1310 {
1311 identification_t *issuer = x509_ca_sig->get_subject(x509_ca_sig);
1312
1313 DBG1(DBG_APP, " scep request pending, polling every %d seconds",
1314 poll_interval);
1315 poll_start = time_monotonic(NULL);
1316 issuerAndSubject = asn1_wrap(ASN1_SEQUENCE, "cc",
1317 issuer->get_encoding(issuer),
1318 subject);
1319 }
1320 while (attrs.pkiStatus == SCEP_PENDING)
1321 {
1322 if (max_poll_time > 0 &&
1323 (time_monotonic(NULL) - poll_start >= max_poll_time))
1324 {
1325 exit_scepclient("maximum poll time reached: %d seconds"
1326 , max_poll_time);
1327 }
1328 DBG2(DBG_APP, "going to sleep for %d seconds", poll_interval);
1329 sleep(poll_interval);
1330 free(scep_response.ptr);
1331 data->destroy(data);
1332
1333 DBG2(DBG_APP, "fingerprint: %.*s",
1334 (int)fingerprint.len, fingerprint.ptr);
1335 DBG2(DBG_APP, "transaction ID: %.*s",
1336 (int)transID.len, transID.ptr);
1337
1338 chunk_free(&getCertInitial);
1339 getCertInitial = scep_build_request(issuerAndSubject,
1340 transID, SCEP_GetCertInitial_MSG, x509_ca_enc,
1341 pkcs7_symmetric_cipher, pkcs7_key_size,
1342 x509_signer, pkcs7_digest_alg, private_key);
1343 if (!getCertInitial.ptr)
1344 {
1345 exit_scepclient("failed to build scep request");
1346 }
1347 if (!scep_http_request(scep_url, getCertInitial, SCEP_PKI_OPERATION,
1348 http_get_request, &scep_response))
1349 {
1350 exit_scepclient("did not receive a valid scep response");
1351 }
1352 ugh = scep_parse_response(scep_response, transID, &data, &attrs,
1353 x509_ca_sig);
1354 if (ugh != NULL)
1355 {
1356 exit_scepclient(ugh);
1357 }
1358 }
1359
1360 if (attrs.pkiStatus != SCEP_SUCCESS)
1361 {
1362 data->destroy(data);
1363 exit_scepclient("reply status is not 'SUCCESS'");
1364 }
1365
1366 if (!data->parse_envelopedData(data, serialNumber, private_key))
1367 {
1368 data->destroy(data);
1369 exit_scepclient("could not decrypt envelopedData");
1370 }
1371 if (!data->parse_signedData(data, NULL))
1372 {
1373 data->destroy(data);
1374 exit_scepclient("error parsing the scep response");
1375 }
1376
1377 /* store the end entity certificate */
1378 join_paths(path, sizeof(path), HOST_CERT_PATH, file_out_cert);
1379
1380 enumerator = data->create_certificate_enumerator(data);
1381 while (enumerator->enumerate(enumerator, &cert))
1382 {
1383 x509_t *x509 = (x509_t*)cert;
1384
1385 if (!(x509->get_flags(x509) & X509_CA))
1386 {
1387 if (stored)
1388 {
1389 exit_scepclient("multiple certs received, only first stored");
1390 }
1391 if (!cert->get_encoding(cert, CERT_ASN1_DER, &encoding) ||
1392 !chunk_write(encoding, path, "requested cert", 0022, force))
1393 {
1394 exit_scepclient("could not write cert file '%s'", path);
1395 }
1396 chunk_free(&encoding);
1397 stored = TRUE;
1398 }
1399 }
1400 enumerator->destroy(enumerator);
1401 data->destroy(data);
1402 filetype_out &= ~CERT; /* delete CERT flag */
1403 }
1404
1405 exit_scepclient(NULL);
1406 return -1; /* should never be reached */
1407 }
1408
1409