Removed len argument from proposal_get_token()
[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 <debug.h>
30 #include <asn1/asn1.h>
31 #include <asn1/oid.h>
32 #include <utils/optionsfrom.h>
33 #include <utils/enumerator.h>
34 #include <utils/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 enrollment (cert):\n"
365 " --url (-u) <url> url of the SCEP server\n"
366 " --method (-m) post | get http request type\n"
367 " --interval (-t) <seconds> poll interval in seconds (default 20s)\n"
368 " --maxpolltime (-x) <seconds> max poll time in seconds when in manual mode\n"
369 " (default: unlimited)\n"
370 "\n"
371 "Debugging output:\n"
372 " --debug (-l) <level> changes the log level (-1..4, default: 1)\n"
373 );
374 exit_scepclient(message);
375 }
376
377 /**
378 * @brief main of scepclient
379 *
380 * @param argc number of arguments
381 * @param argv pointer to the argument values
382 */
383 int main(int argc, char **argv)
384 {
385 /* external values */
386 extern char * optarg;
387 extern int optind;
388
389 /* type of input and output files */
390 typedef enum {
391 PKCS1 = 0x01,
392 PKCS10 = 0x02,
393 PKCS7 = 0x04,
394 CERT_SELF = 0x08,
395 CERT = 0x10,
396 CACERT_ENC = 0x20,
397 CACERT_SIG = 0x40,
398 } scep_filetype_t;
399
400 /* filetype to read from, defaults to "generate a key" */
401 scep_filetype_t filetype_in = 0;
402
403 /* filetype to write to, no default here */
404 scep_filetype_t filetype_out = 0;
405
406 /* input files */
407 char *file_in_pkcs1 = DEFAULT_FILENAME_PKCS1;
408 char *file_in_pkcs10 = DEFAULT_FILENAME_PKCS10;
409 char *file_in_cert_self = DEFAULT_FILENAME_CERT_SELF;
410 char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
411 char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;
412
413 /* output files */
414 char *file_out_pkcs1 = DEFAULT_FILENAME_PKCS1;
415 char *file_out_pkcs10 = DEFAULT_FILENAME_PKCS10;
416 char *file_out_pkcs7 = DEFAULT_FILENAME_PKCS7;
417 char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
418 char *file_out_cert = DEFAULT_FILENAME_CERT;
419 char *file_out_ca_cert = DEFAULT_FILENAME_CACERT_ENC;
420
421 /* by default user certificate is requested */
422 bool request_ca_certificate = FALSE;
423
424 /* by default existing files are not overwritten */
425 bool force = FALSE;
426
427 /* length of RSA key in bits */
428 u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;
429
430 /* validity of self-signed certificate */
431 time_t validity = DEFAULT_CERT_VALIDITY;
432 time_t notBefore = 0;
433 time_t notAfter = 0;
434
435 /* distinguished name for requested certificate, ASCII format */
436 char *distinguishedName = NULL;
437
438 /* challenge password */
439 char challenge_password_buffer[MAX_PASSWORD_LENGTH];
440
441 /* symmetric encryption algorithm used by pkcs7, default is DES */
442 encryption_algorithm_t pkcs7_symmetric_cipher = ENCR_DES;
443 size_t pkcs7_key_size = 0;
444
445 /* digest algorithm used by pkcs7, default is MD5 */
446 hash_algorithm_t pkcs7_digest_alg = HASH_MD5;
447
448 /* signature algorithm used by pkcs10, default is MD5 */
449 hash_algorithm_t pkcs10_signature_alg = HASH_MD5;
450
451 /* URL of the SCEP-Server */
452 char *scep_url = NULL;
453
454 /* http request method, default is GET */
455 bool http_get_request = TRUE;
456
457 /* poll interval time in manual mode in seconds */
458 u_int poll_interval = DEFAULT_POLL_INTERVAL;
459
460 /* maximum poll time */
461 u_int max_poll_time = 0;
462
463 err_t ugh = NULL;
464
465 /* initialize library */
466 if (!library_init(NULL))
467 {
468 library_deinit();
469 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
470 }
471 if (lib->integrity &&
472 !lib->integrity->check_file(lib->integrity, "scepclient", argv[0]))
473 {
474 fprintf(stderr, "integrity check of scepclient failed\n");
475 library_deinit();
476 exit(SS_RC_DAEMON_INTEGRITY);
477 }
478
479 /* initialize global variables */
480 pkcs1 = chunk_empty;
481 pkcs7 = chunk_empty;
482 serialNumber = chunk_empty;
483 transID = chunk_empty;
484 fingerprint = chunk_empty;
485 encoding = chunk_empty;
486 pkcs10_encoding = chunk_empty;
487 issuerAndSubject = chunk_empty;
488 challengePassword = chunk_empty;
489 getCertInitial = chunk_empty;
490 scep_response = chunk_empty;
491 subjectAltNames = linked_list_create();
492 options = options_create();
493
494 for (;;)
495 {
496 static const struct option long_opts[] = {
497 /* name, has_arg, flag, val */
498 { "help", no_argument, NULL, 'h' },
499 { "version", no_argument, NULL, 'v' },
500 { "optionsfrom", required_argument, NULL, '+' },
501 { "quiet", no_argument, NULL, 'q' },
502 { "debug", required_argument, NULL, 'l' },
503 { "in", required_argument, NULL, 'i' },
504 { "out", required_argument, NULL, 'o' },
505 { "force", no_argument, NULL, 'f' },
506 { "keylength", required_argument, NULL, 'k' },
507 { "dn", required_argument, NULL, 'd' },
508 { "days", required_argument, NULL, 'D' },
509 { "startdate", required_argument, NULL, 'S' },
510 { "enddate", required_argument, NULL, 'E' },
511 { "subjectAltName", required_argument, NULL, 's' },
512 { "password", required_argument, NULL, 'p' },
513 { "algorithm", required_argument, NULL, 'a' },
514 { "url", required_argument, NULL, 'u' },
515 { "method", required_argument, NULL, 'm' },
516 { "interval", required_argument, NULL, 't' },
517 { "maxpolltime", required_argument, NULL, 'x' },
518 { 0,0,0,0 }
519 };
520
521 /* parse next option */
522 int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:m:t:x:APRCMS", long_opts, NULL);
523
524 switch (c)
525 {
526 case EOF: /* end of flags */
527 break;
528
529 case 'h': /* --help */
530 usage(NULL);
531
532 case 'v': /* --version */
533 version();
534
535 case 'q': /* --quiet */
536 log_to_stderr = FALSE;
537 continue;
538
539 case 'l': /* --debug <level> */
540 default_loglevel = atoi(optarg);
541 continue;
542
543 case 'i': /* --in <type> [= <filename>] */
544 {
545 char *filename = strstr(optarg, "=");
546
547 if (filename)
548 {
549 /* replace '=' by '\0' */
550 *filename = '\0';
551 /* set pointer to start of filename */
552 filename++;
553 }
554 if (strcaseeq("pkcs1", optarg))
555 {
556 filetype_in |= PKCS1;
557 if (filename)
558 file_in_pkcs1 = filename;
559 }
560 else if (strcaseeq("pkcs10", optarg))
561 {
562 filetype_in |= PKCS10;
563 if (filename)
564 file_in_pkcs10 = filename;
565 }
566 else if (strcaseeq("cacert-enc", optarg))
567 {
568 filetype_in |= CACERT_ENC;
569 if (filename)
570 file_in_cacert_enc = filename;
571 }
572 else if (strcaseeq("cacert-sig", optarg))
573 {
574 filetype_in |= CACERT_SIG;
575 if (filename)
576 file_in_cacert_sig = filename;
577 }
578 else if (strcaseeq("cert-self", optarg))
579 {
580 filetype_in |= CERT_SELF;
581 if (filename)
582 file_in_cert_self = filename;
583 }
584 else
585 {
586 usage("invalid --in file type");
587 }
588 continue;
589 }
590
591 case 'o': /* --out <type> [= <filename>] */
592 {
593 char *filename = strstr(optarg, "=");
594
595 if (filename)
596 {
597 /* replace '=' by '\0' */
598 *filename = '\0';
599 /* set pointer to start of filename */
600 filename++;
601 }
602 if (strcaseeq("pkcs1", optarg))
603 {
604 filetype_out |= PKCS1;
605 if (filename)
606 file_out_pkcs1 = filename;
607 }
608 else if (strcaseeq("pkcs10", optarg))
609 {
610 filetype_out |= PKCS10;
611 if (filename)
612 file_out_pkcs10 = filename;
613 }
614 else if (strcaseeq("pkcs7", optarg))
615 {
616 filetype_out |= PKCS7;
617 if (filename)
618 file_out_pkcs7 = filename;
619 }
620 else if (strcaseeq("cert-self", optarg))
621 {
622 filetype_out |= CERT_SELF;
623 if (filename)
624 file_out_cert_self = filename;
625 }
626 else if (strcaseeq("cert", optarg))
627 {
628 filetype_out |= CERT;
629 if (filename)
630 file_out_cert = filename;
631 }
632 else if (strcaseeq("cacert", optarg))
633 {
634 request_ca_certificate = TRUE;
635 if (filename)
636 file_out_ca_cert = filename;
637 }
638 else
639 {
640 usage("invalid --out file type");
641 }
642 continue;
643 }
644
645 case 'f': /* --force */
646 force = TRUE;
647 continue;
648
649 case '+': /* --optionsfrom <filename> */
650 if (!options->from(options, optarg, &argc, &argv, optind))
651 {
652 exit_scepclient("optionsfrom failed");
653 }
654 continue;
655
656 case 'k': /* --keylength <length> */
657 {
658 div_t q;
659
660 rsa_keylength = atoi(optarg);
661 if (rsa_keylength == 0)
662 usage("invalid keylength");
663
664 /* check if key length is a multiple of 8 bits */
665 q = div(rsa_keylength, 2*BITS_PER_BYTE);
666 if (q.rem != 0)
667 {
668 exit_scepclient("keylength is not a multiple of %d bits!"
669 , 2*BITS_PER_BYTE);
670 }
671 continue;
672 }
673
674 case 'D': /* --days */
675 if (optarg == NULL || !isdigit(optarg[0]))
676 {
677 usage("missing number of days");
678 }
679 else
680 {
681 char *endptr;
682 long days = strtol(optarg, &endptr, 0);
683
684 if (*endptr != '\0' || endptr == optarg
685 || days <= 0)
686 usage("<days> must be a positive number");
687 validity = 24*3600*days;
688 }
689 continue;
690
691 case 'S': /* --startdate */
692 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
693 {
694 usage("date format must be YYMMDDHHMMSSZ");
695 }
696 else
697 {
698 chunk_t date = { optarg, 13 };
699 notBefore = asn1_to_time(&date, ASN1_UTCTIME);
700 }
701 continue;
702
703 case 'E': /* --enddate */
704 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
705 {
706 usage("date format must be YYMMDDHHMMSSZ");
707 }
708 else
709 {
710 chunk_t date = { optarg, 13 };
711 notAfter = asn1_to_time(&date, ASN1_UTCTIME);
712 }
713 continue;
714
715 case 'd': /* --dn */
716 if (distinguishedName)
717 {
718 usage("only one distinguished name allowed");
719 }
720 distinguishedName = optarg;
721 continue;
722
723 case 's': /* --subjectAltName */
724 {
725 char *value = strstr(optarg, "=");
726
727 if (value)
728 {
729 /* replace '=' by '\0' */
730 *value = '\0';
731 /* set pointer to start of value */
732 value++;
733 }
734
735 if (strcaseeq("email", optarg) ||
736 strcaseeq("dns", optarg) ||
737 strcaseeq("ip", optarg))
738 {
739 subjectAltNames->insert_last(subjectAltNames,
740 identification_create_from_string(value));
741 continue;
742 }
743 else
744 {
745 usage("invalid --subjectAltName type");
746 continue;
747 }
748 }
749
750 case 'p': /* --password */
751 if (challengePassword.len > 0)
752 {
753 usage("only one challenge password allowed");
754 }
755 if (strcaseeq("%prompt", optarg))
756 {
757 printf("Challenge password: ");
758 if (fgets(challenge_password_buffer,
759 sizeof(challenge_password_buffer) - 1, stdin))
760 {
761 challengePassword.ptr = challenge_password_buffer;
762 /* discard the terminating '\n' from the input */
763 challengePassword.len = strlen(challenge_password_buffer) - 1;
764 }
765 else
766 {
767 usage("challenge password could not be read");
768 }
769 }
770 else
771 {
772 challengePassword.ptr = optarg;
773 challengePassword.len = strlen(optarg);
774 }
775 continue;
776
777 case 'u': /* -- url */
778 if (scep_url)
779 {
780 usage("only one URL argument allowed");
781 }
782 scep_url = optarg;
783 continue;
784
785 case 'm': /* --method */
786 if (strcaseeq("get", optarg))
787 {
788 http_get_request = TRUE;
789 }
790 else if (strcaseeq("post", optarg))
791 {
792 http_get_request = FALSE;
793 }
794 else
795 {
796 usage("invalid http request method specified");
797 }
798 continue;
799
800 case 't': /* --interval */
801 poll_interval = atoi(optarg);
802 if (poll_interval <= 0)
803 {
804 usage("invalid interval specified");
805 }
806 continue;
807
808 case 'x': /* --maxpolltime */
809 max_poll_time = atoi(optarg);
810 continue;
811
812 case 'a': /*--algorithm [<type>=]algo */
813 {
814 const proposal_token_t *token;
815 char *type = optarg;
816 char *algo = strstr(optarg, "=");
817
818 if (algo)
819 {
820 *algo = '\0';
821 algo++;
822 }
823 else
824 {
825 type = "enc";
826 algo = optarg;
827 }
828
829 if (strcaseeq("enc", type))
830 {
831 token = proposal_get_token(algo);
832 if (token == NULL || token->type != ENCRYPTION_ALGORITHM)
833 {
834 usage("invalid algorithm specified");
835 }
836 pkcs7_symmetric_cipher = token->algorithm;
837 pkcs7_key_size = token->keysize;
838 if (encryption_algorithm_to_oid(token->algorithm,
839 token->keysize) == OID_UNKNOWN)
840 {
841 usage("unsupported encryption algorithm specified");
842 }
843 }
844 else if (strcaseeq("dgst", type) ||
845 strcaseeq("sig", type))
846 {
847 hash_algorithm_t hash;
848
849 token = proposal_get_token(algo);
850 if (token == NULL || token->type != INTEGRITY_ALGORITHM)
851 {
852 usage("invalid algorithm specified");
853 }
854 hash = hasher_algorithm_from_integrity(token->algorithm,
855 NULL);
856 if (hash == OID_UNKNOWN)
857 {
858 usage("invalid algorithm specified");
859 }
860 if (strcaseeq("dgst", type))
861 {
862 pkcs7_digest_alg = hash;
863 }
864 else
865 {
866 pkcs10_signature_alg = hash;
867 }
868 }
869 else
870 {
871 usage("invalid --algorithm type");
872 }
873 continue;
874 }
875 default:
876 usage("unknown option");
877 }
878 /* break from loop */
879 break;
880 }
881
882 init_log("scepclient");
883
884 /* load plugins, further infrastructure may need it */
885 if (!lib->plugins->load(lib->plugins, NULL,
886 lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS)))
887 {
888 exit_scepclient("plugin loading failed");
889 }
890 DBG1(DBG_APP, " loaded plugins: %s",
891 lib->plugins->loaded_plugins(lib->plugins));
892
893 if ((filetype_out == 0) && (!request_ca_certificate))
894 {
895 usage("--out filetype required");
896 }
897 if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
898 {
899 usage("in CA certificate request, no other --in or --out option allowed");
900 }
901
902 /* check if url is given, if cert output defined */
903 if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
904 {
905 usage("URL of SCEP server required");
906 }
907
908 /* check for sanity of --in/--out */
909 if (!filetype_in && (filetype_in > filetype_out))
910 {
911 usage("cannot generate --out of given --in!");
912 }
913
914 /* get CA cert */
915 if (request_ca_certificate)
916 {
917 char ca_path[PATH_MAX];
918 pkcs7_t *pkcs7;
919
920 if (!scep_http_request(scep_url, chunk_empty, SCEP_GET_CA_CERT,
921 http_get_request, &scep_response))
922 {
923 exit_scepclient("did not receive a valid scep response");
924 }
925
926 join_paths(ca_path, sizeof(ca_path), CA_CERT_PATH, file_out_ca_cert);
927
928 pkcs7 = pkcs7_create_from_chunk(scep_response, 0);
929 if (!pkcs7 || !pkcs7->parse_signedData(pkcs7, NULL))
930 { /* no PKCS#7 encoded CA+RA certificates, assume simple CA cert */
931 DESTROY_IF(pkcs7);
932 if (!chunk_write(scep_response, ca_path, "ca cert", 0022, force))
933 {
934 exit_scepclient("could not write ca cert file '%s'", ca_path);
935 }
936 }
937 else
938 {
939 enumerator_t *enumerator;
940 certificate_t *cert;
941 int ra_certs = 0, ca_certs = 0;
942 int ra_index = 1, ca_index = 1;
943
944 enumerator = pkcs7->create_certificate_enumerator(pkcs7);
945 while (enumerator->enumerate(enumerator, &cert))
946 {
947 x509_t *x509 = (x509_t*)cert;
948 if (x509->get_flags(x509) & X509_CA)
949 {
950 ca_certs++;
951 }
952 else
953 {
954 ra_certs++;
955 }
956 }
957 enumerator->destroy(enumerator);
958
959 enumerator = pkcs7->create_certificate_enumerator(pkcs7);
960 while (enumerator->enumerate(enumerator, &cert))
961 {
962 x509_t *x509 = (x509_t*)cert;
963 bool ca_cert = x509->get_flags(x509) & X509_CA;
964 char cert_path[PATH_MAX], *path = ca_path;
965
966 if (ca_cert && ca_certs > 1)
967 {
968 add_path_suffix(cert_path, sizeof(cert_path), ca_path,
969 "-%.1d", ca_index++);
970 path = cert_path;
971 }
972 else if (!ca_cert)
973 { /* use CA name as base for RA certs */
974 if (ra_certs > 1)
975 {
976 add_path_suffix(cert_path, sizeof(cert_path), ca_path,
977 "-ra-%.1d", ra_index++);
978 }
979 else
980 {
981 add_path_suffix(cert_path, sizeof(cert_path), ca_path,
982 "-ra");
983 }
984 path = cert_path;
985 }
986
987 if (!cert->get_encoding(cert, CERT_ASN1_DER, &encoding) ||
988 !chunk_write(encoding, path,
989 ca_cert ? "ca cert" : "ra cert", 0022, force))
990 {
991 exit_scepclient("could not write cert file '%s'", path);
992 }
993 chunk_free(&encoding);
994 }
995 enumerator->destroy(enumerator);
996 pkcs7->destroy(pkcs7);
997 }
998 exit_scepclient(NULL); /* no further output required */
999 }
1000
1001 /*
1002 * input of PKCS#1 file
1003 */
1004 if (filetype_in & PKCS1) /* load an RSA key pair from file */
1005 {
1006 char path[PATH_MAX];
1007
1008 join_paths(path, sizeof(path), PRIVATE_KEY_PATH, file_in_pkcs1);
1009
1010 private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
1011 BUILD_FROM_FILE, path, BUILD_END);
1012 }
1013 else /* generate an RSA key pair */
1014 {
1015 private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
1016 BUILD_KEY_SIZE, rsa_keylength,
1017 BUILD_END);
1018 }
1019 if (private_key == NULL)
1020 {
1021 exit_scepclient("no RSA private key available");
1022 }
1023 public_key = private_key->get_public_key(private_key);
1024
1025 /* check for minimum key length */
1026 if (private_key->get_keysize(private_key) < RSA_MIN_OCTETS / BITS_PER_BYTE)
1027 {
1028 exit_scepclient("length of RSA key has to be at least %d bits",
1029 RSA_MIN_OCTETS * BITS_PER_BYTE);
1030 }
1031
1032 /*
1033 * input of PKCS#10 file
1034 */
1035 if (filetype_in & PKCS10)
1036 {
1037 char path[PATH_MAX];
1038
1039 join_paths(path, sizeof(path), REQ_PATH, file_in_pkcs10);
1040
1041 pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
1042 CERT_PKCS10_REQUEST, BUILD_FROM_FILE,
1043 path, BUILD_END);
1044 if (!pkcs10_req)
1045 {
1046 exit_scepclient("could not read certificate request '%s'", path);
1047 }
1048 subject = pkcs10_req->get_subject(pkcs10_req);
1049 subject = subject->clone(subject);
1050 }
1051 else
1052 {
1053 if (distinguishedName == NULL)
1054 {
1055 char buf[BUF_LEN];
1056 int n = sprintf(buf, DEFAULT_DN);
1057
1058 /* set the common name to the hostname */
1059 if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
1060 {
1061 exit_scepclient("no hostname defined, use "
1062 "--dn <distinguished name> option");
1063 }
1064 distinguishedName = buf;
1065 }
1066
1067 DBG2(DBG_APP, "dn: '%s'", distinguishedName);
1068 subject = identification_create_from_string(distinguishedName);
1069 if (subject->get_type(subject) != ID_DER_ASN1_DN)
1070 {
1071 exit_scepclient("parsing of distinguished name failed");
1072 }
1073
1074 DBG2(DBG_APP, "building pkcs10 object:");
1075 pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
1076 CERT_PKCS10_REQUEST,
1077 BUILD_SIGNING_KEY, private_key,
1078 BUILD_SUBJECT, subject,
1079 BUILD_SUBJECT_ALTNAMES, subjectAltNames,
1080 BUILD_CHALLENGE_PWD, challengePassword,
1081 BUILD_DIGEST_ALG, pkcs10_signature_alg,
1082 BUILD_END);
1083 if (!pkcs10_req)
1084 {
1085 exit_scepclient("generating pkcs10 request failed");
1086 }
1087 }
1088 pkcs10_req->get_encoding(pkcs10_req, CERT_ASN1_DER, &pkcs10_encoding);
1089 fingerprint = scep_generate_pkcs10_fingerprint(pkcs10_encoding);
1090 DBG1(DBG_APP, " fingerprint: %s", fingerprint.ptr);
1091
1092 /*
1093 * output of PKCS#10 file
1094 */
1095 if (filetype_out & PKCS10)
1096 {
1097 char path[PATH_MAX];
1098
1099 join_paths(path, sizeof(path), REQ_PATH, file_out_pkcs10);
1100
1101 if (!chunk_write(pkcs10_encoding, path, "pkcs10", 0022, force))
1102 {
1103 exit_scepclient("could not write pkcs10 file '%s'", path);
1104 }
1105 filetype_out &= ~PKCS10; /* delete PKCS10 flag */
1106 }
1107
1108 if (!filetype_out)
1109 {
1110 exit_scepclient(NULL); /* no further output required */
1111 }
1112
1113 /*
1114 * output of PKCS#1 file
1115 */
1116 if (filetype_out & PKCS1)
1117 {
1118 char path[PATH_MAX];
1119
1120 join_paths(path, sizeof(path), PRIVATE_KEY_PATH, file_out_pkcs1);
1121
1122 DBG2(DBG_APP, "building pkcs1 object:");
1123 if (!private_key->get_encoding(private_key, PRIVKEY_ASN1_DER, &pkcs1) ||
1124 !chunk_write(pkcs1, path, "pkcs1", 0066, force))
1125 {
1126 exit_scepclient("could not write pkcs1 file '%s'", path);
1127 }
1128 filetype_out &= ~PKCS1; /* delete PKCS1 flag */
1129 }
1130
1131 if (!filetype_out)
1132 {
1133 exit_scepclient(NULL); /* no further output required */
1134 }
1135
1136 scep_generate_transaction_id(public_key, &transID, &serialNumber);
1137 DBG1(DBG_APP, " transaction ID: %.*s", (int)transID.len, transID.ptr);
1138
1139 /*
1140 * read or generate self-signed X.509 certificate
1141 */
1142 if (filetype_in & CERT_SELF)
1143 {
1144 char path[PATH_MAX];
1145
1146 join_paths(path, sizeof(path), HOST_CERT_PATH, file_in_cert_self);
1147
1148 x509_signer = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
1149 BUILD_FROM_FILE, path, BUILD_END);
1150 if (!x509_signer)
1151 {
1152 exit_scepclient("could not read certificate file '%s'", path);
1153 }
1154 }
1155 else
1156 {
1157 notBefore = notBefore ? notBefore : time(NULL);
1158 notAfter = notAfter ? notAfter : (notBefore + validity);
1159 x509_signer = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
1160 BUILD_SIGNING_KEY, private_key,
1161 BUILD_PUBLIC_KEY, public_key,
1162 BUILD_SUBJECT, subject,
1163 BUILD_NOT_BEFORE_TIME, notBefore,
1164 BUILD_NOT_AFTER_TIME, notAfter,
1165 BUILD_SERIAL, serialNumber,
1166 BUILD_SUBJECT_ALTNAMES, subjectAltNames,
1167 BUILD_END);
1168 if (!x509_signer)
1169 {
1170 exit_scepclient("generating certificate failed");
1171 }
1172 }
1173
1174 /*
1175 * output of self-signed X.509 certificate file
1176 */
1177 if (filetype_out & CERT_SELF)
1178 {
1179 char path[PATH_MAX];
1180
1181 join_paths(path, sizeof(path), HOST_CERT_PATH, file_out_cert_self);
1182
1183 if (!x509_signer->get_encoding(x509_signer, CERT_ASN1_DER, &encoding))
1184 {
1185 exit_scepclient("encoding certificate failed");
1186 }
1187 if (!chunk_write(encoding, path, "self-signed cert", 0022, force))
1188 {
1189 exit_scepclient("could not write self-signed cert file '%s'", path);
1190 }
1191 chunk_free(&encoding);
1192 filetype_out &= ~CERT_SELF; /* delete CERT_SELF flag */
1193 }
1194
1195 if (!filetype_out)
1196 {
1197 exit_scepclient(NULL); /* no further output required */
1198 }
1199
1200 /*
1201 * load ca encryption certificate
1202 */
1203 {
1204 char path[PATH_MAX];
1205
1206 join_paths(path, sizeof(path), CA_CERT_PATH, file_in_cacert_enc);
1207
1208 x509_ca_enc = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
1209 BUILD_FROM_FILE, path, BUILD_END);
1210 if (!x509_ca_enc)
1211 {
1212 exit_scepclient("could not load encryption cacert file '%s'", path);
1213 }
1214 }
1215
1216 /*
1217 * input of PKCS#7 file
1218 */
1219 if (filetype_in & PKCS7)
1220 {
1221 /* user wants to load a pkcs7 encrypted request
1222 * operation is not yet supported!
1223 * would require additional parsing of transaction-id
1224
1225 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
1226
1227 */
1228 }
1229 else
1230 {
1231 DBG2(DBG_APP, "building pkcs7 request");
1232 pkcs7 = scep_build_request(pkcs10_encoding,
1233 transID, SCEP_PKCSReq_MSG, x509_ca_enc,
1234 pkcs7_symmetric_cipher, pkcs7_key_size,
1235 x509_signer, pkcs7_digest_alg, private_key);
1236 if (!pkcs7.ptr)
1237 {
1238 exit_scepclient("failed to build pkcs7 request");
1239 }
1240 }
1241
1242 /*
1243 * output pkcs7 encrypted and signed certificate request
1244 */
1245 if (filetype_out & PKCS7)
1246 {
1247 char path[PATH_MAX];
1248
1249 join_paths(path, sizeof(path), REQ_PATH, file_out_pkcs7);
1250
1251 if (!chunk_write(pkcs7, path, "pkcs7 encrypted request", 0022, force))
1252 {
1253 exit_scepclient("could not write pkcs7 file '%s'", path);
1254 }
1255 filetype_out &= ~PKCS7; /* delete PKCS7 flag */
1256 }
1257
1258 if (!filetype_out)
1259 {
1260 exit_scepclient(NULL); /* no further output required */
1261 }
1262
1263 /*
1264 * output certificate fetch from SCEP server
1265 */
1266 if (filetype_out & CERT)
1267 {
1268 bool stored = FALSE;
1269 certificate_t *cert;
1270 enumerator_t *enumerator;
1271 char path[PATH_MAX];
1272 time_t poll_start = 0;
1273 pkcs7_t *data = NULL;
1274 scep_attributes_t attrs = empty_scep_attributes;
1275
1276 join_paths(path, sizeof(path), CA_CERT_PATH, file_in_cacert_sig);
1277
1278 x509_ca_sig = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
1279 BUILD_FROM_FILE, path, BUILD_END);
1280 if (!x509_ca_sig)
1281 {
1282 exit_scepclient("could not load signature cacert file '%s'", path);
1283 }
1284
1285 if (!scep_http_request(scep_url, pkcs7, SCEP_PKI_OPERATION,
1286 http_get_request, &scep_response))
1287 {
1288 exit_scepclient("did not receive a valid scep response");
1289 }
1290 ugh = scep_parse_response(scep_response, transID, &data, &attrs,
1291 x509_ca_sig);
1292 if (ugh != NULL)
1293 {
1294 exit_scepclient(ugh);
1295 }
1296
1297 /* in case of manual mode, we are going into a polling loop */
1298 if (attrs.pkiStatus == SCEP_PENDING)
1299 {
1300 identification_t *issuer = x509_ca_sig->get_subject(x509_ca_sig);
1301
1302 DBG1(DBG_APP, " scep request pending, polling every %d seconds",
1303 poll_interval);
1304 poll_start = time_monotonic(NULL);
1305 issuerAndSubject = asn1_wrap(ASN1_SEQUENCE, "cc",
1306 issuer->get_encoding(issuer),
1307 subject);
1308 }
1309 while (attrs.pkiStatus == SCEP_PENDING)
1310 {
1311 if (max_poll_time > 0 &&
1312 (time_monotonic(NULL) - poll_start >= max_poll_time))
1313 {
1314 exit_scepclient("maximum poll time reached: %d seconds"
1315 , max_poll_time);
1316 }
1317 DBG2(DBG_APP, "going to sleep for %d seconds", poll_interval);
1318 sleep(poll_interval);
1319 free(scep_response.ptr);
1320 data->destroy(data);
1321
1322 DBG2(DBG_APP, "fingerprint: %.*s",
1323 (int)fingerprint.len, fingerprint.ptr);
1324 DBG2(DBG_APP, "transaction ID: %.*s",
1325 (int)transID.len, transID.ptr);
1326
1327 chunk_free(&getCertInitial);
1328 getCertInitial = scep_build_request(issuerAndSubject,
1329 transID, SCEP_GetCertInitial_MSG, x509_ca_enc,
1330 pkcs7_symmetric_cipher, pkcs7_key_size,
1331 x509_signer, pkcs7_digest_alg, private_key);
1332 if (!getCertInitial.ptr)
1333 {
1334 exit_scepclient("failed to build scep request");
1335 }
1336 if (!scep_http_request(scep_url, getCertInitial, SCEP_PKI_OPERATION,
1337 http_get_request, &scep_response))
1338 {
1339 exit_scepclient("did not receive a valid scep response");
1340 }
1341 ugh = scep_parse_response(scep_response, transID, &data, &attrs,
1342 x509_ca_sig);
1343 if (ugh != NULL)
1344 {
1345 exit_scepclient(ugh);
1346 }
1347 }
1348
1349 if (attrs.pkiStatus != SCEP_SUCCESS)
1350 {
1351 data->destroy(data);
1352 exit_scepclient("reply status is not 'SUCCESS'");
1353 }
1354
1355 if (!data->parse_envelopedData(data, serialNumber, private_key))
1356 {
1357 data->destroy(data);
1358 exit_scepclient("could not decrypt envelopedData");
1359 }
1360 if (!data->parse_signedData(data, NULL))
1361 {
1362 data->destroy(data);
1363 exit_scepclient("error parsing the scep response");
1364 }
1365
1366 /* store the end entity certificate */
1367 join_paths(path, sizeof(path), HOST_CERT_PATH, file_out_cert);
1368
1369 enumerator = data->create_certificate_enumerator(data);
1370 while (enumerator->enumerate(enumerator, &cert))
1371 {
1372 x509_t *x509 = (x509_t*)cert;
1373
1374 if (!(x509->get_flags(x509) & X509_CA))
1375 {
1376 if (stored)
1377 {
1378 exit_scepclient("multiple certs received, only first stored");
1379 }
1380 if (!cert->get_encoding(cert, CERT_ASN1_DER, &encoding) ||
1381 !chunk_write(encoding, path, "requested cert", 0022, force))
1382 {
1383 exit_scepclient("could not write cert file '%s'", path);
1384 }
1385 chunk_free(&encoding);
1386 stored = TRUE;
1387 }
1388 }
1389 enumerator->destroy(enumerator);
1390 data->destroy(data);
1391 filetype_out &= ~CERT; /* delete CERT flag */
1392 }
1393
1394 exit_scepclient(NULL);
1395 return -1; /* should never be reached */
1396 }
1397
1398