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