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