0b54eeee313cc1975503ab8312a2faef7c52f338
[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 #include <plugins/plugin.h>
54
55 #include "../pluto/constants.h"
56 #include "../pluto/defs.h"
57 #include "../pluto/log.h"
58 #include "../pluto/certs.h"
59 #include "../pluto/pkcs7.h"
60
61 #include "scep.h"
62
63 /*
64 * definition of some defaults
65 */
66
67 /* default name of DER-encoded PKCS#1 private key file */
68 #define DEFAULT_FILENAME_PKCS1 "myKey.der"
69
70 /* default name of DER-encoded PKCS#10 certificate request file */
71 #define DEFAULT_FILENAME_PKCS10 "myReq.der"
72
73 /* default name of DER-encoded PKCS#7 file */
74 #define DEFAULT_FILENAME_PKCS7 "pkcs7.der"
75
76 /* default name of DER-encoded self-signed X.509 certificate file */
77 #define DEFAULT_FILENAME_CERT_SELF "selfCert.der"
78
79 /* default name of DER-encoded X.509 certificate file */
80 #define DEFAULT_FILENAME_CERT "myCert.der"
81
82 /* default name of DER-encoded CA cert file used for key encipherment */
83 #define DEFAULT_FILENAME_CACERT_ENC "caCert.der"
84
85 /* default name of the der encoded CA cert file used for signature verification */
86 #define DEFAULT_FILENAME_CACERT_SIG "caCert.der"
87
88 /* default prefix of the der encoded CA certificates received from the SCEP server */
89 #define DEFAULT_FILENAME_PREFIX_CACERT "caCert.der"
90
91 /* default certificate validity */
92 #define DEFAULT_CERT_VALIDITY 5 * 3600 * 24 * 365 /* seconds */
93
94 /* default polling time interval in SCEP manual mode */
95 #define DEFAULT_POLL_INTERVAL 20 /* seconds */
96
97 /* default key length for self-generated RSA keys */
98 #define DEFAULT_RSA_KEY_LENGTH 2048 /* bits */
99
100 /* default distinguished name */
101 #define DEFAULT_DN "C=CH, O=Linux strongSwan, CN="
102
103 /* challenge password buffer size */
104 #define MAX_PASSWORD_LENGTH 256
105
106 /* Max length of filename for tempfile */
107 #define MAX_TEMP_FILENAME_LENGTH 256
108
109
110 /* current scepclient version */
111 static const char *scepclient_version = "1.0";
112
113 /* by default the CRL policy is lenient */
114 bool strict_crl_policy = FALSE;
115
116 /* by default pluto does not check crls dynamically */
117 long crl_check_interval = 0;
118
119 /* by default pluto logs out after every smartcard use */
120 bool pkcs11_keep_state = FALSE;
121
122 /* options read by optionsfrom */
123 options_t *options;
124
125 /*
126 * Global variables
127 */
128
129 chunk_t pkcs1;
130 chunk_t pkcs7;
131 chunk_t challengePassword;
132 chunk_t serialNumber;
133 chunk_t transID;
134 chunk_t fingerprint;
135 chunk_t encoding;
136 chunk_t pkcs10_encoding;
137 chunk_t issuerAndSubject;
138 chunk_t getCertInitial;
139 chunk_t scep_response;
140
141 linked_list_t *subjectAltNames;
142
143 identification_t *subject = NULL;
144 private_key_t *private_key = NULL;
145 public_key_t *public_key = NULL;
146 certificate_t *x509_signer = NULL;
147 certificate_t *x509_ca_enc = NULL;
148 certificate_t *x509_ca_sig = NULL;
149 certificate_t *pkcs10_req = NULL;
150
151 /**
152 * @brief exit scepclient
153 *
154 * @param status 0 = OK, 1 = general discomfort
155 */
156 static void
157 exit_scepclient(err_t message, ...)
158 {
159 int status = 0;
160
161 DESTROY_IF(subject);
162 DESTROY_IF(private_key);
163 DESTROY_IF(public_key);
164 DESTROY_IF(x509_signer);
165 DESTROY_IF(x509_ca_enc);
166 DESTROY_IF(x509_ca_sig);
167 DESTROY_IF(pkcs10_req);
168 subjectAltNames->destroy_offset(subjectAltNames,
169 offsetof(identification_t, destroy));
170 free(pkcs1.ptr);
171 free(pkcs7.ptr);
172 free(serialNumber.ptr);
173 free(transID.ptr);
174 free(fingerprint.ptr);
175 free(encoding.ptr);
176 free(pkcs10_encoding.ptr);
177 free(issuerAndSubject.ptr);
178 free(getCertInitial.ptr);
179 free(scep_response.ptr);
180 options->destroy(options);
181
182 /* print any error message to stderr */
183 if (message != NULL && *message != '\0')
184 {
185 va_list args;
186 char m[LOG_WIDTH]; /* longer messages will be truncated */
187
188 va_start(args, message);
189 vsnprintf(m, sizeof(m), message, args);
190 va_end(args);
191
192 fprintf(stderr, "error: %s\n", m);
193 status = -1;
194 }
195 library_deinit();
196 close_log();
197 exit(status);
198 }
199
200 /**
201 * @brief prints the program version and exits
202 *
203 */
204 static void
205 version(void)
206 {
207 printf("scepclient %s\n", scepclient_version);
208 exit_scepclient(NULL);
209 }
210
211 /**
212 * @brief prints the usage of the program to the stderr output
213 *
214 * If message is set, program is exitet with 1 (error)
215 * @param message message in case of an error
216 */
217 static void
218 usage(const char *message)
219 {
220 fprintf(stderr,
221 "Usage: scepclient\n"
222 " --help (-h) show usage and exit\n"
223 " --version (-v) show version and exit\n"
224 " --quiet (-q) do not write log output to stderr\n"
225 " --in (-i) <type>[=<filename>] use <filename> of <type> for input \n"
226 " <type> = pkcs1 | cacert-enc | cacert-sig\n"
227 " - if no pkcs1 input is defined, a \n"
228 " RSA key will be generated\n"
229 " - if no filename is given, default is used\n"
230 " --out (-o) <type>[=<filename>] write output of <type> to <filename>\n"
231 " multiple outputs are allowed\n"
232 " <type> = pkcs1 | pkcs10 | pkcs7 | cert-self | cert | cacert\n"
233 " - type cacert defines filename prefix of\n"
234 " received CA certificate(s)\n"
235 " - if no filename is given, default is used\n"
236 " --optionsfrom (-+) <filename> reads additional options from given file\n"
237 " --force (-f) force existing file(s)\n"
238 "\n"
239 "Options for key generation (pkcs1):\n"
240 " --keylength (-k) <bits> key length for RSA key generation\n"
241 "(default: 2048 bits)\n"
242 "\n"
243 "Options for validity:\n"
244 " --days (-D) <days> validity in days\n"
245 " --startdate (-S) <YYMMDDHHMMSS>Z not valid before date\n"
246 " --enddate (-E) <YYMMDDHHMMSS>Z not valid after date\n"
247 "\n"
248 "Options for request generation (pkcs10):\n"
249 " --dn (-d) <dn> comma separated list of distinguished names\n"
250 " --subjectAltName (-s) <t>=<v> include subjectAltName in certificate request\n"
251 " <t> = email | dns | ip \n"
252 " --password (-p) <pw> challenge password\n"
253 " - if pw is '%%prompt', password gets prompted for\n"
254 " --algorithm (-a) <algo> use specified algorithm for PKCS#7 encryption\n"
255 " <algo> = des | 3des (default) | aes128| aes192 | \n"
256 " aes256 | camellia128 | camellia192 | camellia256\n"
257 "\n"
258 "Options for enrollment (cert):\n"
259 " --url (-u) <url> url of the SCEP server\n"
260 " --method (-m) post | get http request type\n"
261 " --interval (-t) <seconds> manual mode poll interval in seconds (default 20s)\n"
262 " --maxpolltime (-x) <seconds> max poll time in seconds when in manual mode\n"
263 " (default: unlimited)\n"
264 #ifdef DEBUG
265 "\n"
266 "Debugging output:\n"
267 " --debug-all (-A) show everything except private\n"
268 " --debug-parsing (-P) show parsing relevant stuff\n"
269 " --debug-raw (-R) show raw hex dumps\n"
270 " --debug-control (-C) show control flow output\n"
271 " --debug-controlmore (-M) show more control flow\n"
272 " --debug-private (-X) show sensitive data (private keys, etc.)\n"
273 #endif
274 );
275 exit_scepclient(message);
276 }
277
278 /**
279 * @brief main of scepclient
280 *
281 * @param argc number of arguments
282 * @param argv pointer to the argument values
283 */
284 int main(int argc, char **argv)
285 {
286 /* external values */
287 extern char * optarg;
288 extern int optind;
289
290 /* type of input and output files */
291 typedef enum {
292 PKCS1 = 0x01,
293 PKCS10 = 0x02,
294 PKCS7 = 0x04,
295 CERT_SELF = 0x08,
296 CERT = 0x10,
297 CACERT_ENC = 0x20,
298 CACERT_SIG = 0x40
299 } scep_filetype_t;
300
301 /* filetype to read from, defaults to "generate a key" */
302 scep_filetype_t filetype_in = 0;
303
304 /* filetype to write to, no default here */
305 scep_filetype_t filetype_out = 0;
306
307 /* input files */
308 char *file_in_pkcs1 = DEFAULT_FILENAME_PKCS1;
309 char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
310 char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;
311
312 /* output files */
313 char *file_out_pkcs1 = DEFAULT_FILENAME_PKCS1;
314 char *file_out_pkcs10 = DEFAULT_FILENAME_PKCS10;
315 char *file_out_pkcs7 = DEFAULT_FILENAME_PKCS7;
316 char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
317 char *file_out_cert = DEFAULT_FILENAME_CERT;
318 char *file_out_ca_cert = DEFAULT_FILENAME_CACERT_ENC;
319
320 /* by default user certificate is requested */
321 bool request_ca_certificate = FALSE;
322
323 /* by default existing files are not overwritten */
324 bool force = FALSE;
325
326 /* length of RSA key in bits */
327 u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;
328
329 /* validity of self-signed certificate */
330 time_t validity = DEFAULT_CERT_VALIDITY;
331 time_t notBefore = 0;
332 time_t notAfter = 0;
333
334 /* distinguished name for requested certificate, ASCII format */
335 char *distinguishedName = NULL;
336
337 /* challenge password */
338 char challenge_password_buffer[MAX_PASSWORD_LENGTH];
339
340 /* symmetric encryption algorithm used by pkcs7, default is 3DES */
341 int pkcs7_symmetric_cipher = OID_3DES_EDE_CBC;
342
343 /* digest algorithm used by pkcs7, default is SHA-1 */
344 int pkcs7_digest_alg = OID_SHA1;
345
346 /* signature algorithm used by pkcs10, default is SHA-1 */
347 hash_algorithm_t pkcs10_signature_alg = HASH_SHA1;
348
349 /* URL of the SCEP-Server */
350 char *scep_url = NULL;
351
352 /* http request method, default is GET */
353 bool http_get_request = TRUE;
354
355 /* poll interval time in manual mode in seconds */
356 u_int poll_interval = DEFAULT_POLL_INTERVAL;
357
358 /* maximum poll time */
359 u_int max_poll_time = 0;
360
361 err_t ugh = NULL;
362
363 /* initialize library */
364 if (!library_init(NULL))
365 {
366 library_deinit();
367 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
368 }
369 if (lib->integrity &&
370 !lib->integrity->check_file(lib->integrity, "scepclient", argv[0]))
371 {
372 fprintf(stderr, "integrity check of scepclient failed\n");
373 library_deinit();
374 exit(SS_RC_DAEMON_INTEGRITY);
375 }
376
377 /* initialize global variables */
378 pkcs1 = chunk_empty;
379 pkcs7 = chunk_empty;
380 serialNumber = chunk_empty;
381 transID = chunk_empty;
382 fingerprint = chunk_empty;
383 encoding = chunk_empty;
384 pkcs10_encoding = chunk_empty;
385 issuerAndSubject = chunk_empty;
386 challengePassword = chunk_empty;
387 getCertInitial = chunk_empty;
388 scep_response = chunk_empty;
389 subjectAltNames = linked_list_create();
390 options = options_create();
391 log_to_stderr = TRUE;
392
393 for (;;)
394 {
395 static const struct option long_opts[] = {
396 /* name, has_arg, flag, val */
397 { "help", no_argument, NULL, 'h' },
398 { "version", no_argument, NULL, 'v' },
399 { "optionsfrom", required_argument, NULL, '+' },
400 { "quiet", no_argument, NULL, 'q' },
401 { "in", required_argument, NULL, 'i' },
402 { "out", required_argument, NULL, 'o' },
403 { "force", no_argument, NULL, 'f' },
404 { "keylength", required_argument, NULL, 'k' },
405 { "dn", required_argument, NULL, 'd' },
406 { "days", required_argument, NULL, 'D' },
407 { "startdate", required_argument, NULL, 'S' },
408 { "enddate", required_argument, NULL, 'E' },
409 { "subjectAltName", required_argument, NULL, 's' },
410 { "password", required_argument, NULL, 'p' },
411 { "algorithm", required_argument, NULL, 'a' },
412 { "url", required_argument, NULL, 'u' },
413 { "method", required_argument, NULL, 'm' },
414 { "interval", required_argument, NULL, 't' },
415 { "maxpolltime", required_argument, NULL, 'x' },
416 #ifdef DEBUG
417 { "debug-all", no_argument, NULL, 'A' },
418 { "debug-parsing", no_argument, NULL, 'P'},
419 { "debug-raw", no_argument, NULL, 'R'},
420 { "debug-control", no_argument, NULL, 'C'},
421 { "debug-controlmore", no_argument, NULL, 'M'},
422 { "debug-private", no_argument, NULL, 'X'},
423 #endif
424 { 0,0,0,0 }
425 };
426
427 /* parse next option */
428 int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:m:t:x:APRCMS", long_opts, NULL);
429
430 switch (c)
431 {
432 case EOF: /* end of flags */
433 break;
434
435 case 'h': /* --help */
436 usage(NULL);
437
438 case 'v': /* --version */
439 version();
440
441 case 'q': /* --quiet */
442 log_to_stderr = FALSE;
443 continue;
444
445 case 'i': /* --in <type> [= <filename>] */
446 {
447 char *filename = strstr(optarg, "=");
448
449 if (filename)
450 {
451 /* replace '=' by '\0' */
452 *filename = '\0';
453 /* set pointer to start of filename */
454 filename++;
455 }
456 if (strcaseeq("pkcs1", optarg))
457 {
458 filetype_in |= PKCS1;
459 if (filename)
460 file_in_pkcs1 = filename;
461 }
462 else if (strcaseeq("cacert-enc", optarg))
463 {
464 filetype_in |= CACERT_ENC;
465 if (filename)
466 file_in_cacert_enc = filename;
467 }
468 else if (strcaseeq("cacert-sig", optarg))
469 {
470 filetype_in |= CACERT_SIG;
471 if (filename)
472 file_in_cacert_sig = filename;
473 }
474 else
475 {
476 usage("invalid --in file type");
477 }
478 continue;
479 }
480
481 case 'o': /* --out <type> [= <filename>] */
482 {
483 char *filename = strstr(optarg, "=");
484
485 if (filename)
486 {
487 /* replace '=' by '\0' */
488 *filename = '\0';
489 /* set pointer to start of filename */
490 filename++;
491 }
492 if (strcaseeq("pkcs1", optarg))
493 {
494 filetype_out |= PKCS1;
495 if (filename)
496 file_out_pkcs1 = filename;
497 }
498 else if (strcaseeq("pkcs10", optarg))
499 {
500 filetype_out |= PKCS10;
501 if (filename)
502 file_out_pkcs10 = filename;
503 }
504 else if (strcaseeq("pkcs7", optarg))
505 {
506 filetype_out |= PKCS7;
507 if (filename)
508 file_out_pkcs7 = filename;
509 }
510 else if (strcaseeq("cert-self", optarg))
511 {
512 filetype_out |= CERT_SELF;
513 if (filename)
514 file_out_cert_self = filename;
515 }
516 else if (strcaseeq("cert", optarg))
517 {
518 filetype_out |= CERT;
519 if (filename)
520 file_out_cert = filename;
521 }
522 else if (strcaseeq("cacert", optarg))
523 {
524 request_ca_certificate = TRUE;
525 if (filename)
526 file_out_ca_cert = filename;
527 }
528 else
529 {
530 usage("invalid --out file type");
531 }
532 continue;
533 }
534
535 case 'f': /* --force */
536 force = TRUE;
537 continue;
538
539 case '+': /* --optionsfrom <filename> */
540 if (!options->from(options, optarg, &argc, &argv, optind))
541 {
542 exit_scepclient("optionsfrom failed");
543 }
544 continue;
545
546 case 'k': /* --keylength <length> */
547 {
548 div_t q;
549
550 rsa_keylength = atoi(optarg);
551 if (rsa_keylength == 0)
552 usage("invalid keylength");
553
554 /* check if key length is a multiple of 8 bits */
555 q = div(rsa_keylength, 2*BITS_PER_BYTE);
556 if (q.rem != 0)
557 {
558 exit_scepclient("keylength is not a multiple of %d bits!"
559 , 2*BITS_PER_BYTE);
560 }
561 continue;
562 }
563
564 case 'D': /* --days */
565 if (optarg == NULL || !isdigit(optarg[0]))
566 usage("missing number of days");
567 {
568 char *endptr;
569 long days = strtol(optarg, &endptr, 0);
570
571 if (*endptr != '\0' || endptr == optarg
572 || days <= 0)
573 usage("<days> must be a positive number");
574 validity = 24*3600*days;
575 }
576 continue;
577
578 case 'S': /* --startdate */
579 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
580 usage("date format must be YYMMDDHHMMSSZ");
581 {
582 chunk_t date = { optarg, 13 };
583 notBefore = asn1_to_time(&date, ASN1_UTCTIME);
584 }
585 continue;
586
587 case 'E': /* --enddate */
588 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
589 usage("date format must be YYMMDDHHMMSSZ");
590 {
591 chunk_t date = { optarg, 13 };
592 notAfter = asn1_to_time(&date, ASN1_UTCTIME);
593 }
594 continue;
595
596 case 'd': /* --dn */
597 if (distinguishedName)
598 usage("only one distinguished name allowed");
599 distinguishedName = optarg;
600 continue;
601
602 case 's': /* --subjectAltName */
603 {
604 char *value = strstr(optarg, "=");
605
606 if (value)
607 {
608 /* replace '=' by '\0' */
609 *value = '\0';
610 /* set pointer to start of value */
611 value++;
612 }
613
614 if (strcaseeq("email", optarg) ||
615 strcaseeq("dns", optarg) ||
616 strcaseeq("ip", optarg))
617 {
618 subjectAltNames->insert_last(subjectAltNames,
619 identification_create_from_string(value));
620 continue;
621 }
622 else
623 {
624 usage("invalid --subjectAltName type");
625 continue;
626 }
627 }
628
629 case 'p': /* --password */
630 if (challengePassword.len > 0)
631 {
632 usage("only one challenge password allowed");
633 }
634 if (strcaseeq("%prompt", optarg))
635 {
636 printf("Challenge password: ");
637 if (fgets(challenge_password_buffer, sizeof(challenge_password_buffer)-1, stdin))
638 {
639 challengePassword.ptr = challenge_password_buffer;
640 /* discard the terminating '\n' from the input */
641 challengePassword.len = strlen(challenge_password_buffer) - 1;
642 }
643 else
644 {
645 usage("challenge password could not be read");
646 }
647 }
648 else
649 {
650 challengePassword.ptr = optarg;
651 challengePassword.len = strlen(optarg);
652 }
653 continue;
654
655 case 'u': /* -- url */
656 if (scep_url)
657 {
658 usage("only one URL argument allowed");
659 }
660 scep_url = optarg;
661 continue;
662
663 case 'm': /* --method */
664 if (strcaseeq("get", optarg))
665 {
666 http_get_request = TRUE;
667 }
668 else if (strcaseeq("post", optarg))
669 {
670 http_get_request = FALSE;
671 }
672 else
673 {
674 usage("invalid http request method specified");
675 }
676 continue;
677
678 case 't': /* --interval */
679 poll_interval = atoi(optarg);
680 if (poll_interval <= 0)
681 {
682 usage("invalid interval specified");
683 }
684 continue;
685
686 case 'x': /* --maxpolltime */
687 max_poll_time = atoi(optarg);
688 continue;
689
690 case 'a': /*--algorithm */
691 {
692 const proposal_token_t *token;
693
694 token = proposal_get_token(optarg, strlen(optarg));
695 if (token == NULL || token->type != ENCRYPTION_ALGORITHM)
696 {
697 usage("invalid algorithm specified");
698 }
699 pkcs7_symmetric_cipher = encryption_algorithm_to_oid(
700 token->algorithm, token->keysize);
701 if (pkcs7_symmetric_cipher == OID_UNKNOWN)
702 {
703 usage("unsupported encryption algorithm specified");
704 }
705 continue;
706 }
707 #ifdef DEBUG
708 case 'A': /* --debug-all */
709 base_debugging |= DBG_ALL;
710 continue;
711 case 'P': /* debug parsing */
712 base_debugging |= DBG_PARSING;
713 continue;
714 case 'R': /* debug raw */
715 base_debugging |= DBG_RAW;
716 continue;
717 case 'C': /* debug control */
718 base_debugging |= DBG_CONTROL;
719 continue;
720 case 'M': /* debug control more */
721 base_debugging |= DBG_CONTROLMORE;
722 continue;
723 case 'X': /* debug private */
724 base_debugging |= DBG_PRIVATE;
725 continue;
726 #endif
727 default:
728 usage("unknown option");
729 }
730 /* break from loop */
731 break;
732 }
733 cur_debugging = base_debugging;
734
735 init_log("scepclient");
736
737 /* load plugins, further infrastructure may need it */
738 if (!lib->plugins->load(lib->plugins, NULL,
739 lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS)))
740 {
741 exit_scepclient("plugin loading failed");
742 }
743 DBG1(DBG_LIB, " loaded plugins: %s",
744 lib->plugins->loaded_plugins(lib->plugins));
745
746 if ((filetype_out == 0) && (!request_ca_certificate))
747 {
748 usage ("--out filetype required");
749 }
750 if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
751 {
752 usage("in CA certificate request, no other --in or --out option allowed");
753 }
754
755 /* check if url is given, if cert output defined */
756 if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
757 {
758 usage("URL of SCEP server required");
759 }
760
761 /* check for sanity of --in/--out */
762 if (!filetype_in && (filetype_in > filetype_out))
763 {
764 usage("cannot generate --out of given --in!");
765 }
766
767 /* get CA cert */
768 if (request_ca_certificate)
769 {
770 char *path = concatenate_paths(CA_CERT_PATH, file_out_ca_cert);
771
772 if (!scep_http_request(scep_url, chunk_empty, SCEP_GET_CA_CERT,
773 http_get_request, &scep_response))
774 {
775 exit_scepclient("did not receive a valid scep response");
776 }
777
778 if (!chunk_write(scep_response, path, "ca cert", 0022, force))
779 {
780 exit_scepclient("could not write ca cert file '%s'", path);
781 }
782 exit_scepclient(NULL); /* no further output required */
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