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