fixed typo
[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];
283 plugin_t *plugin;
284 int len = 0;
285 enumerator_t *enumerator;
286
287 enumerator = lib->plugins->create_plugin_enumerator(lib->plugins);
288 while (len < BUF_LEN && enumerator->enumerate(enumerator, &plugin))
289 {
290 len += snprintf(&buf[len], BUF_LEN-len, "%s ", plugin->get_name(plugin));
291 }
292 enumerator->destroy(enumerator);
293 DBG1(DBG_LIB, " loaded plugins: %s", buf);
294 }
295
296 /**
297 * @brief main of scepclient
298 *
299 * @param argc number of arguments
300 * @param argv pointer to the argument values
301 */
302 int main(int argc, char **argv)
303 {
304 /* external values */
305 extern char * optarg;
306 extern int optind;
307
308 /* type of input and output files */
309 typedef enum {
310 PKCS1 = 0x01,
311 PKCS10 = 0x02,
312 PKCS7 = 0x04,
313 CERT_SELF = 0x08,
314 CERT = 0x10,
315 CACERT_ENC = 0x20,
316 CACERT_SIG = 0x40
317 } scep_filetype_t;
318
319 /* filetype to read from, defaults to "generate a key" */
320 scep_filetype_t filetype_in = 0;
321
322 /* filetype to write to, no default here */
323 scep_filetype_t filetype_out = 0;
324
325 /* input files */
326 char *file_in_pkcs1 = DEFAULT_FILENAME_PKCS1;
327 char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
328 char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;
329
330 /* output files */
331 char *file_out_pkcs1 = DEFAULT_FILENAME_PKCS1;
332 char *file_out_pkcs10 = DEFAULT_FILENAME_PKCS10;
333 char *file_out_pkcs7 = DEFAULT_FILENAME_PKCS7;
334 char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
335 char *file_out_cert = DEFAULT_FILENAME_CERT;
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 }
543 else
544 {
545 usage("invalid --out file type");
546 }
547 continue;
548 }
549
550 case 'f': /* --force */
551 force = TRUE;
552 continue;
553
554 case '+': /* --optionsfrom <filename> */
555 if (!options->from(options, optarg, &argc, &argv, optind))
556 {
557 exit_scepclient("optionsfrom failed");
558 }
559 continue;
560
561 case 'k': /* --keylength <length> */
562 {
563 div_t q;
564
565 rsa_keylength = atoi(optarg);
566 if (rsa_keylength == 0)
567 usage("invalid keylength");
568
569 /* check if key length is a multiple of 8 bits */
570 q = div(rsa_keylength, 2*BITS_PER_BYTE);
571 if (q.rem != 0)
572 {
573 exit_scepclient("keylength is not a multiple of %d bits!"
574 , 2*BITS_PER_BYTE);
575 }
576 continue;
577 }
578
579 case 'D': /* --days */
580 if (optarg == NULL || !isdigit(optarg[0]))
581 usage("missing number of days");
582 {
583 char *endptr;
584 long days = strtol(optarg, &endptr, 0);
585
586 if (*endptr != '\0' || endptr == optarg
587 || days <= 0)
588 usage("<days> must be a positive number");
589 validity = 24*3600*days;
590 }
591 continue;
592
593 case 'S': /* --startdate */
594 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
595 usage("date format must be YYMMDDHHMMSSZ");
596 {
597 chunk_t date = { optarg, 13 };
598 notBefore = asn1_to_time(&date, ASN1_UTCTIME);
599 }
600 continue;
601
602 case 'E': /* --enddate */
603 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
604 usage("date format must be YYMMDDHHMMSSZ");
605 {
606 chunk_t date = { optarg, 13 };
607 notAfter = asn1_to_time(&date, ASN1_UTCTIME);
608 }
609 continue;
610
611 case 'd': /* --dn */
612 if (distinguishedName)
613 usage("only one distinguished name allowed");
614 distinguishedName = optarg;
615 continue;
616
617 case 's': /* --subjectAltName */
618 {
619 char *value = strstr(optarg, "=");
620
621 if (value)
622 {
623 /* replace '=' by '\0' */
624 *value = '\0';
625 /* set pointer to start of value */
626 value++;
627 }
628
629 if (strcaseeq("email", optarg) ||
630 strcaseeq("dns", optarg) ||
631 strcaseeq("ip", optarg))
632 {
633 subjectAltNames->insert_last(subjectAltNames,
634 identification_create_from_string(value));
635 continue;
636 }
637 else
638 {
639 usage("invalid --subjectAltName type");
640 continue;
641 }
642 }
643
644 case 'p': /* --password */
645 if (challengePassword.len > 0)
646 {
647 usage("only one challenge password allowed");
648 }
649 if (strcaseeq("%prompt", optarg))
650 {
651 printf("Challenge password: ");
652 if (fgets(challenge_password_buffer, sizeof(challenge_password_buffer)-1, stdin))
653 {
654 challengePassword.ptr = challenge_password_buffer;
655 /* discard the terminating '\n' from the input */
656 challengePassword.len = strlen(challenge_password_buffer) - 1;
657 }
658 else
659 {
660 usage("challenge password could not be read");
661 }
662 }
663 else
664 {
665 challengePassword.ptr = optarg;
666 challengePassword.len = strlen(optarg);
667 }
668 continue;
669
670 case 'u': /* -- url */
671 if (scep_url)
672 {
673 usage("only one URL argument allowed");
674 }
675 scep_url = optarg;
676 continue;
677
678 case 'm': /* --method */
679 if (strcaseeq("get", optarg))
680 {
681 http_get_request = TRUE;
682 }
683 else if (strcaseeq("post", optarg))
684 {
685 http_get_request = FALSE;
686 }
687 else
688 {
689 usage("invalid http request method specified");
690 }
691 continue;
692
693 case 't': /* --interval */
694 poll_interval = atoi(optarg);
695 if (poll_interval <= 0)
696 {
697 usage("invalid interval specified");
698 }
699 continue;
700
701 case 'x': /* --maxpolltime */
702 max_poll_time = atoi(optarg);
703 if (max_poll_time < 0)
704 {
705 usage("invalid maxpolltime specified");
706 }
707 continue;
708
709 case 'a': /*--algorithm */
710 {
711 const proposal_token_t *token;
712
713 token = proposal_get_token(optarg, strlen(optarg));
714 if (token == NULL || token->type != ENCRYPTION_ALGORITHM)
715 {
716 usage("invalid algorithm specified");
717 }
718 pkcs7_symmetric_cipher = encryption_algorithm_to_oid(
719 token->algorithm, token->keysize);
720 if (pkcs7_symmetric_cipher == OID_UNKNOWN)
721 {
722 usage("unsupported encryption algorithm specified");
723 }
724 continue;
725 }
726 #ifdef DEBUG
727 case 'A': /* --debug-all */
728 base_debugging |= DBG_ALL;
729 continue;
730 case 'P': /* debug parsing */
731 base_debugging |= DBG_PARSING;
732 continue;
733 case 'R': /* debug raw */
734 base_debugging |= DBG_RAW;
735 continue;
736 case 'C': /* debug control */
737 base_debugging |= DBG_CONTROL;
738 continue;
739 case 'M': /* debug control more */
740 base_debugging |= DBG_CONTROLMORE;
741 continue;
742 case 'X': /* debug private */
743 base_debugging |= DBG_PRIVATE;
744 continue;
745 #endif
746 default:
747 usage("unknown option");
748 }
749 /* break from loop */
750 break;
751 }
752 cur_debugging = base_debugging;
753
754 init_log("scepclient");
755
756 /* load plugins, further infrastructure may need it */
757 if (!lib->plugins->load(lib->plugins, NULL,
758 lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS)))
759 {
760 exit_scepclient("plugin loading failed");
761 }
762 print_plugins();
763
764 if ((filetype_out == 0) && (!request_ca_certificate))
765 {
766 usage ("--out filetype required");
767 }
768 if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
769 {
770 usage("in CA certificate request, no other --in or --out option allowed");
771 }
772
773 /* check if url is given, if cert output defined */
774 if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
775 {
776 usage("URL of SCEP server required");
777 }
778
779 /* check for sanity of --in/--out */
780 if (!filetype_in && (filetype_in > filetype_out))
781 {
782 usage("cannot generate --out of given --in!");
783 }
784
785 /*
786 * input of PKCS#1 file
787 */
788 if (filetype_in & PKCS1) /* load an RSA key pair from file */
789 {
790 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_in_pkcs1);
791
792 private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
793 BUILD_FROM_FILE, path, BUILD_END);
794 }
795 else /* generate an RSA key pair */
796 {
797 private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
798 BUILD_KEY_SIZE, rsa_keylength,
799 BUILD_END);
800 }
801 if (private_key == NULL)
802 {
803 exit_scepclient("no RSA private key available");
804 }
805 public_key = private_key->get_public_key(private_key);
806
807 /* check for minimum key length */
808 if (private_key->get_keysize(private_key) < RSA_MIN_OCTETS / BITS_PER_BYTE)
809 {
810 exit_scepclient("length of RSA key has to be at least %d bits"
811 ,RSA_MIN_OCTETS * BITS_PER_BYTE);
812 }
813
814 /*
815 * input of PKCS#10 file
816 */
817 if (filetype_in & PKCS10)
818 {
819 /* user wants to load a pkcs10 request
820 * operation is not yet supported
821 * would require a PKCS#10 parsing function
822
823 pkcs10 = pkcs10_read_from_file(file_in_pkcs10);
824
825 */
826 }
827 else
828 {
829 if (distinguishedName == NULL)
830 {
831 char buf[BUF_LEN];
832 int n = sprintf(buf, DEFAULT_DN);
833
834 /* set the common name to the hostname */
835 if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
836 {
837 exit_scepclient("no hostname defined, use "
838 "--dn <distinguished name> option");
839 }
840 distinguishedName = buf;
841 }
842
843 DBG(DBG_CONTROL,
844 DBG_log("dn: '%s'", distinguishedName);
845 )
846 subject = identification_create_from_string(distinguishedName);
847 if (subject->get_type(subject) != ID_DER_ASN1_DN)
848 {
849 exit_scepclient("parsing of distinguished name failed");
850 }
851
852 DBG(DBG_CONTROL,
853 DBG_log("building pkcs10 object:")
854 )
855 pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
856 CERT_PKCS10_REQUEST,
857 BUILD_SIGNING_KEY, private_key,
858 BUILD_SUBJECT, subject,
859 BUILD_SUBJECT_ALTNAMES, subjectAltNames,
860 BUILD_CHALLENGE_PWD, challengePassword,
861 BUILD_DIGEST_ALG, pkcs10_signature_alg,
862 BUILD_END);
863 if (!pkcs10_req)
864 {
865 exit_scepclient("generating pkcs10 request failed");
866 }
867 pkcs10_req->get_encoding(pkcs10_req, CERT_ASN1_DER, &pkcs10_encoding);
868 fingerprint = scep_generate_pkcs10_fingerprint(pkcs10_encoding);
869 plog(" fingerprint: %s", fingerprint.ptr);
870 }
871
872 /*
873 * output of PKCS#10 file
874 */
875 if (filetype_out & PKCS10)
876 {
877 char *path = concatenate_paths(REQ_PATH, file_out_pkcs10);
878
879 if (!chunk_write(pkcs10_encoding, path, "pkcs10", 0022, force))
880 {
881 exit_scepclient("could not write pkcs10 file '%s'", path);
882 }
883 filetype_out &= ~PKCS10; /* delete PKCS10 flag */
884 }
885
886 if (!filetype_out)
887 {
888 exit_scepclient(NULL); /* no further output required */
889 }
890
891 /*
892 * output of PKCS#1 file
893 */
894 if (filetype_out & PKCS1)
895 {
896 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_out_pkcs1);
897
898 DBG(DBG_CONTROL,
899 DBG_log("building pkcs1 object:")
900 )
901 if (!private_key->get_encoding(private_key, PRIVKEY_ASN1_DER, &pkcs1) ||
902 !chunk_write(pkcs1, path, "pkcs1", 0066, force))
903 {
904 exit_scepclient("could not write pkcs1 file '%s'", path);
905 }
906 filetype_out &= ~PKCS1; /* delete PKCS1 flag */
907 }
908
909 if (!filetype_out)
910 {
911 exit_scepclient(NULL); /* no further output required */
912 }
913
914 scep_generate_transaction_id(public_key, &transID, &serialNumber);
915 plog(" transaction ID: %.*s", (int)transID.len, transID.ptr);
916
917 notBefore = notBefore ? notBefore : time(NULL);
918 notAfter = notAfter ? notAfter : (notBefore + validity);
919
920 /* generate a self-signed X.509 certificate */
921 x509_signer = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
922 BUILD_SIGNING_KEY, private_key,
923 BUILD_PUBLIC_KEY, public_key,
924 BUILD_SUBJECT, subject,
925 BUILD_NOT_BEFORE_TIME, notBefore,
926 BUILD_NOT_AFTER_TIME, notAfter,
927 BUILD_SERIAL, serialNumber,
928 BUILD_SUBJECT_ALTNAMES, subjectAltNames,
929 BUILD_END);
930 if (!x509_signer)
931 {
932 exit_scepclient("generating certificate failed");
933 }
934
935 /*
936 * output of self-signed X.509 certificate file
937 */
938 if (filetype_out & CERT_SELF)
939 {
940 char *path = concatenate_paths(HOST_CERT_PATH, file_out_cert_self);
941
942 if (!x509_signer->get_encoding(x509_signer, CERT_ASN1_DER, &encoding))
943 {
944 exit_scepclient("encoding certificate failed");
945 }
946 if (!chunk_write(encoding, path, "self-signed cert", 0022, force))
947 {
948 exit_scepclient("could not write self-signed cert file '%s'", path);
949 }
950 chunk_free(&encoding);
951 filetype_out &= ~CERT_SELF; /* delete CERT_SELF flag */
952 }
953
954 if (!filetype_out)
955 {
956 exit_scepclient(NULL); /* no further output required */
957 }
958
959 /*
960 * load ca encryption certificate
961 */
962 {
963 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_enc);
964
965 x509_ca_enc = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
966 BUILD_FROM_FILE, path, BUILD_END);
967 if (!x509_ca_enc)
968 {
969 exit_scepclient("could not load encryption cacert file '%s'", path);
970 }
971 }
972
973 /*
974 * input of PKCS#7 file
975 */
976 if (filetype_in & PKCS7)
977 {
978 /* user wants to load a pkcs7 encrypted request
979 * operation is not yet supported!
980 * would require additional parsing of transaction-id
981
982 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
983
984 */
985 }
986 else
987 {
988 DBG(DBG_CONTROL,
989 DBG_log("building pkcs7 request")
990 )
991 pkcs7 = scep_build_request(pkcs10_encoding,
992 transID, SCEP_PKCSReq_MSG,
993 x509_ca_enc, pkcs7_symmetric_cipher,
994 x509_signer, pkcs7_digest_alg, private_key);
995 }
996
997 /*
998 * output pkcs7 encrypted and signed certificate request
999 */
1000 if (filetype_out & PKCS7)
1001 {
1002 char *path = concatenate_paths(REQ_PATH, file_out_pkcs7);
1003
1004 if (!chunk_write(pkcs7, path, "pkcs7 encrypted request", 0022, force))
1005 exit_scepclient("could not write pkcs7 file '%s'", path);
1006 ;
1007 filetype_out &= ~PKCS7; /* delete PKCS7 flag */
1008 }
1009
1010 if (!filetype_out)
1011 {
1012 exit_scepclient(NULL); /* no further output required */
1013 }
1014
1015 /*
1016 * output certificate fetch from SCEP server
1017 */
1018 if (filetype_out & CERT)
1019 {
1020 bool stored = FALSE;
1021 certificate_t *cert;
1022 enumerator_t *enumerator;
1023 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_sig);
1024 time_t poll_start = 0;
1025
1026 linked_list_t *certs = linked_list_create();
1027 chunk_t envelopedData = chunk_empty;
1028 chunk_t certData = chunk_empty;
1029 contentInfo_t data = empty_contentInfo;
1030 scep_attributes_t attrs = empty_scep_attributes;
1031
1032 x509_ca_sig = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
1033 BUILD_FROM_FILE, path, BUILD_END);
1034 if (!x509_ca_sig)
1035 {
1036 exit_scepclient("could not load signature cacert file '%s'", path);
1037 }
1038
1039 if (!scep_http_request(scep_url, pkcs7, SCEP_PKI_OPERATION,
1040 http_get_request, &scep_response))
1041 {
1042 exit_scepclient("did not receive a valid scep response");
1043 }
1044 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1045 , x509_ca_sig);
1046 if (ugh != NULL)
1047 {
1048 exit_scepclient(ugh);
1049 }
1050
1051 /* in case of manual mode, we are going into a polling loop */
1052 if (attrs.pkiStatus == SCEP_PENDING)
1053 {
1054 identification_t *issuer = x509_ca_sig->get_subject(x509_ca_sig);
1055
1056 plog(" scep request pending, polling every %d seconds"
1057 , poll_interval);
1058 poll_start = time_monotonic(NULL);
1059 issuerAndSubject = asn1_wrap(ASN1_SEQUENCE, "cc",
1060 issuer->get_encoding(issuer),
1061 subject);
1062 }
1063 while (attrs.pkiStatus == SCEP_PENDING)
1064 {
1065 if (max_poll_time > 0
1066 && (time_monotonic(NULL) - poll_start >= max_poll_time))
1067 {
1068 exit_scepclient("maximum poll time reached: %d seconds"
1069 , max_poll_time);
1070 }
1071 DBG(DBG_CONTROL,
1072 DBG_log("going to sleep for %d seconds", poll_interval)
1073 )
1074 sleep(poll_interval);
1075 free(scep_response.ptr);
1076
1077 DBG(DBG_CONTROL,
1078 DBG_log("fingerprint: %.*s", (int)fingerprint.len, fingerprint.ptr);
1079 DBG_log("transaction ID: %.*s", (int)transID.len, transID.ptr)
1080 )
1081
1082 chunk_free(&getCertInitial);
1083 getCertInitial = scep_build_request(issuerAndSubject
1084 , transID, SCEP_GetCertInitial_MSG
1085 , x509_ca_enc, pkcs7_symmetric_cipher
1086 , x509_signer, pkcs7_digest_alg, private_key);
1087
1088 if (!scep_http_request(scep_url, getCertInitial, SCEP_PKI_OPERATION,
1089 http_get_request, &scep_response))
1090 {
1091 exit_scepclient("did not receive a valid scep response");
1092 }
1093 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1094 , x509_ca_sig);
1095 if (ugh != NULL)
1096 {
1097 exit_scepclient(ugh);
1098 }
1099 }
1100
1101 if (attrs.pkiStatus != SCEP_SUCCESS)
1102 {
1103 exit_scepclient("reply status is not 'SUCCESS'");
1104 }
1105
1106 envelopedData = data.content;
1107
1108 if (data.type != OID_PKCS7_DATA
1109 || !asn1_parse_simple_object(&envelopedData, ASN1_OCTET_STRING, 0, "data"))
1110 {
1111 exit_scepclient("contentInfo is not of type 'data'");
1112 }
1113 if (!pkcs7_parse_envelopedData(envelopedData, &certData
1114 , serialNumber, private_key))
1115 {
1116 exit_scepclient("could not decrypt envelopedData");
1117 }
1118 if (!pkcs7_parse_signedData(certData, NULL, certs, NULL, NULL))
1119 {
1120 exit_scepclient("error parsing the scep response");
1121 }
1122 chunk_free(&certData);
1123
1124 /* store the end entity certificate */
1125 path = concatenate_paths(HOST_CERT_PATH, file_out_cert);
1126
1127 enumerator = certs->create_enumerator(certs);
1128 while (enumerator->enumerate(enumerator, &cert))
1129 {
1130 x509_t *x509 = (x509_t*)cert;
1131
1132 if (!(x509->get_flags(x509) & X509_CA))
1133 {
1134 if (stored)
1135 {
1136 exit_scepclient("multiple certs received, only first stored");
1137 }
1138 if (!cert->get_encoding(cert, CERT_ASN1_DER, &encoding) ||
1139 !chunk_write(encoding, path, "requested cert", 0022, force))
1140 {
1141 exit_scepclient("could not write cert file '%s'", path);
1142 }
1143 chunk_free(&encoding);
1144 stored = TRUE;
1145 }
1146 }
1147 certs->destroy_offset(certs, offsetof(certificate_t, destroy));
1148 filetype_out &= ~CERT; /* delete CERT flag */
1149 }
1150
1151 exit_scepclient(NULL);
1152 return -1; /* should never be reached */
1153 }
1154
1155