]> git.ipfire.org Git - thirdparty/strongswan.git/blob - src/scepclient/scepclient.c
Allow support for CA-certificate retrieval in scepclient
[thirdparty/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 * Log loaded plugins
280 */
281 static void print_plugins()
282 {
283 char buf[BUF_LEN];
284 plugin_t *plugin;
285 int len = 0;
286 enumerator_t *enumerator;
287
288 enumerator = lib->plugins->create_plugin_enumerator(lib->plugins);
289 while (len < BUF_LEN && enumerator->enumerate(enumerator, &plugin, NULL))
290 {
291 len += snprintf(&buf[len], BUF_LEN-len, "%s ", plugin->get_name(plugin));
292 }
293 enumerator->destroy(enumerator);
294 DBG1(DBG_LIB, " loaded plugins: %s", buf);
295 }
296
297 /**
298 * @brief main of scepclient
299 *
300 * @param argc number of arguments
301 * @param argv pointer to the argument values
302 */
303 int main(int argc, char **argv)
304 {
305 /* external values */
306 extern char * optarg;
307 extern int optind;
308
309 /* type of input and output files */
310 typedef enum {
311 PKCS1 = 0x01,
312 PKCS10 = 0x02,
313 PKCS7 = 0x04,
314 CERT_SELF = 0x08,
315 CERT = 0x10,
316 CACERT_ENC = 0x20,
317 CACERT_SIG = 0x40
318 } scep_filetype_t;
319
320 /* filetype to read from, defaults to "generate a key" */
321 scep_filetype_t filetype_in = 0;
322
323 /* filetype to write to, no default here */
324 scep_filetype_t filetype_out = 0;
325
326 /* input files */
327 char *file_in_pkcs1 = DEFAULT_FILENAME_PKCS1;
328 char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
329 char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;
330
331 /* output files */
332 char *file_out_pkcs1 = DEFAULT_FILENAME_PKCS1;
333 char *file_out_pkcs10 = DEFAULT_FILENAME_PKCS10;
334 char *file_out_pkcs7 = DEFAULT_FILENAME_PKCS7;
335 char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
336 char *file_out_cert = DEFAULT_FILENAME_CERT;
337 char *file_out_ca_cert = DEFAULT_FILENAME_CACERT_ENC;
338
339 /* by default user certificate is requested */
340 bool request_ca_certificate = FALSE;
341
342 /* by default existing files are not overwritten */
343 bool force = FALSE;
344
345 /* length of RSA key in bits */
346 u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;
347
348 /* validity of self-signed certificate */
349 time_t validity = DEFAULT_CERT_VALIDITY;
350 time_t notBefore = 0;
351 time_t notAfter = 0;
352
353 /* distinguished name for requested certificate, ASCII format */
354 char *distinguishedName = NULL;
355
356 /* challenge password */
357 char challenge_password_buffer[MAX_PASSWORD_LENGTH];
358
359 /* symmetric encryption algorithm used by pkcs7, default is 3DES */
360 int pkcs7_symmetric_cipher = OID_3DES_EDE_CBC;
361
362 /* digest algorithm used by pkcs7, default is SHA-1 */
363 int pkcs7_digest_alg = OID_SHA1;
364
365 /* signature algorithm used by pkcs10, default is SHA-1 */
366 hash_algorithm_t pkcs10_signature_alg = HASH_SHA1;
367
368 /* URL of the SCEP-Server */
369 char *scep_url = NULL;
370
371 /* http request method, default is GET */
372 bool http_get_request = TRUE;
373
374 /* poll interval time in manual mode in seconds */
375 u_int poll_interval = DEFAULT_POLL_INTERVAL;
376
377 /* maximum poll time */
378 u_int max_poll_time = 0;
379
380 err_t ugh = NULL;
381
382 /* initialize library */
383 if (!library_init(NULL))
384 {
385 library_deinit();
386 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
387 }
388 if (lib->integrity &&
389 !lib->integrity->check_file(lib->integrity, "scepclient", argv[0]))
390 {
391 fprintf(stderr, "integrity check of scepclient failed\n");
392 library_deinit();
393 exit(SS_RC_DAEMON_INTEGRITY);
394 }
395
396 /* initialize global variables */
397 pkcs1 = chunk_empty;
398 pkcs7 = chunk_empty;
399 serialNumber = chunk_empty;
400 transID = chunk_empty;
401 fingerprint = chunk_empty;
402 encoding = chunk_empty;
403 pkcs10_encoding = chunk_empty;
404 issuerAndSubject = chunk_empty;
405 challengePassword = chunk_empty;
406 getCertInitial = chunk_empty;
407 scep_response = chunk_empty;
408 subjectAltNames = linked_list_create();
409 options = options_create();
410 log_to_stderr = TRUE;
411
412 for (;;)
413 {
414 static const struct option long_opts[] = {
415 /* name, has_arg, flag, val */
416 { "help", no_argument, NULL, 'h' },
417 { "version", no_argument, NULL, 'v' },
418 { "optionsfrom", required_argument, NULL, '+' },
419 { "quiet", no_argument, NULL, 'q' },
420 { "in", required_argument, NULL, 'i' },
421 { "out", required_argument, NULL, 'o' },
422 { "force", no_argument, NULL, 'f' },
423 { "keylength", required_argument, NULL, 'k' },
424 { "dn", required_argument, NULL, 'd' },
425 { "days", required_argument, NULL, 'D' },
426 { "startdate", required_argument, NULL, 'S' },
427 { "enddate", required_argument, NULL, 'E' },
428 { "subjectAltName", required_argument, NULL, 's' },
429 { "password", required_argument, NULL, 'p' },
430 { "algorithm", required_argument, NULL, 'a' },
431 { "url", required_argument, NULL, 'u' },
432 { "method", required_argument, NULL, 'm' },
433 { "interval", required_argument, NULL, 't' },
434 { "maxpolltime", required_argument, NULL, 'x' },
435 #ifdef DEBUG
436 { "debug-all", no_argument, NULL, 'A' },
437 { "debug-parsing", no_argument, NULL, 'P'},
438 { "debug-raw", no_argument, NULL, 'R'},
439 { "debug-control", no_argument, NULL, 'C'},
440 { "debug-controlmore", no_argument, NULL, 'M'},
441 { "debug-private", no_argument, NULL, 'X'},
442 #endif
443 { 0,0,0,0 }
444 };
445
446 /* parse next option */
447 int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:m:t:x:APRCMS", long_opts, NULL);
448
449 switch (c)
450 {
451 case EOF: /* end of flags */
452 break;
453
454 case 'h': /* --help */
455 usage(NULL);
456
457 case 'v': /* --version */
458 version();
459
460 case 'q': /* --quiet */
461 log_to_stderr = FALSE;
462 continue;
463
464 case 'i': /* --in <type> [= <filename>] */
465 {
466 char *filename = strstr(optarg, "=");
467
468 if (filename)
469 {
470 /* replace '=' by '\0' */
471 *filename = '\0';
472 /* set pointer to start of filename */
473 filename++;
474 }
475 if (strcaseeq("pkcs1", optarg))
476 {
477 filetype_in |= PKCS1;
478 if (filename)
479 file_in_pkcs1 = filename;
480 }
481 else if (strcaseeq("cacert-enc", optarg))
482 {
483 filetype_in |= CACERT_ENC;
484 if (filename)
485 file_in_cacert_enc = filename;
486 }
487 else if (strcaseeq("cacert-sig", optarg))
488 {
489 filetype_in |= CACERT_SIG;
490 if (filename)
491 file_in_cacert_sig = filename;
492 }
493 else
494 {
495 usage("invalid --in file type");
496 }
497 continue;
498 }
499
500 case 'o': /* --out <type> [= <filename>] */
501 {
502 char *filename = strstr(optarg, "=");
503
504 if (filename)
505 {
506 /* replace '=' by '\0' */
507 *filename = '\0';
508 /* set pointer to start of filename */
509 filename++;
510 }
511 if (strcaseeq("pkcs1", optarg))
512 {
513 filetype_out |= PKCS1;
514 if (filename)
515 file_out_pkcs1 = filename;
516 }
517 else if (strcaseeq("pkcs10", optarg))
518 {
519 filetype_out |= PKCS10;
520 if (filename)
521 file_out_pkcs10 = filename;
522 }
523 else if (strcaseeq("pkcs7", optarg))
524 {
525 filetype_out |= PKCS7;
526 if (filename)
527 file_out_pkcs7 = filename;
528 }
529 else if (strcaseeq("cert-self", optarg))
530 {
531 filetype_out |= CERT_SELF;
532 if (filename)
533 file_out_cert_self = filename;
534 }
535 else if (strcaseeq("cert", optarg))
536 {
537 filetype_out |= CERT;
538 if (filename)
539 file_out_cert = filename;
540 }
541 else if (strcaseeq("cacert", optarg))
542 {
543 request_ca_certificate = TRUE;
544 if (filename)
545 file_out_ca_cert = filename;
546 }
547 else
548 {
549 usage("invalid --out file type");
550 }
551 continue;
552 }
553
554 case 'f': /* --force */
555 force = TRUE;
556 continue;
557
558 case '+': /* --optionsfrom <filename> */
559 if (!options->from(options, optarg, &argc, &argv, optind))
560 {
561 exit_scepclient("optionsfrom failed");
562 }
563 continue;
564
565 case 'k': /* --keylength <length> */
566 {
567 div_t q;
568
569 rsa_keylength = atoi(optarg);
570 if (rsa_keylength == 0)
571 usage("invalid keylength");
572
573 /* check if key length is a multiple of 8 bits */
574 q = div(rsa_keylength, 2*BITS_PER_BYTE);
575 if (q.rem != 0)
576 {
577 exit_scepclient("keylength is not a multiple of %d bits!"
578 , 2*BITS_PER_BYTE);
579 }
580 continue;
581 }
582
583 case 'D': /* --days */
584 if (optarg == NULL || !isdigit(optarg[0]))
585 usage("missing number of days");
586 {
587 char *endptr;
588 long days = strtol(optarg, &endptr, 0);
589
590 if (*endptr != '\0' || endptr == optarg
591 || days <= 0)
592 usage("<days> must be a positive number");
593 validity = 24*3600*days;
594 }
595 continue;
596
597 case 'S': /* --startdate */
598 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
599 usage("date format must be YYMMDDHHMMSSZ");
600 {
601 chunk_t date = { optarg, 13 };
602 notBefore = asn1_to_time(&date, ASN1_UTCTIME);
603 }
604 continue;
605
606 case 'E': /* --enddate */
607 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
608 usage("date format must be YYMMDDHHMMSSZ");
609 {
610 chunk_t date = { optarg, 13 };
611 notAfter = asn1_to_time(&date, ASN1_UTCTIME);
612 }
613 continue;
614
615 case 'd': /* --dn */
616 if (distinguishedName)
617 usage("only one distinguished name allowed");
618 distinguishedName = optarg;
619 continue;
620
621 case 's': /* --subjectAltName */
622 {
623 char *value = strstr(optarg, "=");
624
625 if (value)
626 {
627 /* replace '=' by '\0' */
628 *value = '\0';
629 /* set pointer to start of value */
630 value++;
631 }
632
633 if (strcaseeq("email", optarg) ||
634 strcaseeq("dns", optarg) ||
635 strcaseeq("ip", optarg))
636 {
637 subjectAltNames->insert_last(subjectAltNames,
638 identification_create_from_string(value));
639 continue;
640 }
641 else
642 {
643 usage("invalid --subjectAltName type");
644 continue;
645 }
646 }
647
648 case 'p': /* --password */
649 if (challengePassword.len > 0)
650 {
651 usage("only one challenge password allowed");
652 }
653 if (strcaseeq("%prompt", optarg))
654 {
655 printf("Challenge password: ");
656 if (fgets(challenge_password_buffer, sizeof(challenge_password_buffer)-1, stdin))
657 {
658 challengePassword.ptr = challenge_password_buffer;
659 /* discard the terminating '\n' from the input */
660 challengePassword.len = strlen(challenge_password_buffer) - 1;
661 }
662 else
663 {
664 usage("challenge password could not be read");
665 }
666 }
667 else
668 {
669 challengePassword.ptr = optarg;
670 challengePassword.len = strlen(optarg);
671 }
672 continue;
673
674 case 'u': /* -- url */
675 if (scep_url)
676 {
677 usage("only one URL argument allowed");
678 }
679 scep_url = optarg;
680 continue;
681
682 case 'm': /* --method */
683 if (strcaseeq("get", optarg))
684 {
685 http_get_request = TRUE;
686 }
687 else if (strcaseeq("post", optarg))
688 {
689 http_get_request = FALSE;
690 }
691 else
692 {
693 usage("invalid http request method specified");
694 }
695 continue;
696
697 case 't': /* --interval */
698 poll_interval = atoi(optarg);
699 if (poll_interval <= 0)
700 {
701 usage("invalid interval specified");
702 }
703 continue;
704
705 case 'x': /* --maxpolltime */
706 max_poll_time = atoi(optarg);
707 if (max_poll_time < 0)
708 {
709 usage("invalid maxpolltime specified");
710 }
711 continue;
712
713 case 'a': /*--algorithm */
714 {
715 const proposal_token_t *token;
716
717 token = proposal_get_token(optarg, strlen(optarg));
718 if (token == NULL || token->type != ENCRYPTION_ALGORITHM)
719 {
720 usage("invalid algorithm specified");
721 }
722 pkcs7_symmetric_cipher = encryption_algorithm_to_oid(
723 token->algorithm, token->keysize);
724 if (pkcs7_symmetric_cipher == OID_UNKNOWN)
725 {
726 usage("unsupported encryption algorithm specified");
727 }
728 continue;
729 }
730 #ifdef DEBUG
731 case 'A': /* --debug-all */
732 base_debugging |= DBG_ALL;
733 continue;
734 case 'P': /* debug parsing */
735 base_debugging |= DBG_PARSING;
736 continue;
737 case 'R': /* debug raw */
738 base_debugging |= DBG_RAW;
739 continue;
740 case 'C': /* debug control */
741 base_debugging |= DBG_CONTROL;
742 continue;
743 case 'M': /* debug control more */
744 base_debugging |= DBG_CONTROLMORE;
745 continue;
746 case 'X': /* debug private */
747 base_debugging |= DBG_PRIVATE;
748 continue;
749 #endif
750 default:
751 usage("unknown option");
752 }
753 /* break from loop */
754 break;
755 }
756 cur_debugging = base_debugging;
757
758 init_log("scepclient");
759
760 /* load plugins, further infrastructure may need it */
761 if (!lib->plugins->load(lib->plugins, NULL,
762 lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS)))
763 {
764 exit_scepclient("plugin loading failed");
765 }
766 print_plugins();
767
768 if ((filetype_out == 0) && (!request_ca_certificate))
769 {
770 usage ("--out filetype required");
771 }
772 if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
773 {
774 usage("in CA certificate request, no other --in or --out option allowed");
775 }
776
777 /* check if url is given, if cert output defined */
778 if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
779 {
780 usage("URL of SCEP server required");
781 }
782
783 /* check for sanity of --in/--out */
784 if (!filetype_in && (filetype_in > filetype_out))
785 {
786 usage("cannot generate --out of given --in!");
787 }
788
789 /* get CA cert */
790 if (request_ca_certificate)
791 {
792 char *path = concatenate_paths(CA_CERT_PATH, file_out_ca_cert);
793
794 if (!scep_http_request(scep_url, chunk_empty, SCEP_GET_CA_CERT,
795 http_get_request, &scep_response))
796 {
797 exit_scepclient("did not receive a valid scep response");
798 }
799
800 if (!chunk_write(scep_response, path, "ca cert", 0022, force))
801 {
802 exit_scepclient("could not write ca cert file '%s'", path);
803 }
804 exit_scepclient(NULL); /* no further output required */
805 }
806
807 /*
808 * input of PKCS#1 file
809 */
810 if (filetype_in & PKCS1) /* load an RSA key pair from file */
811 {
812 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_in_pkcs1);
813
814 private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
815 BUILD_FROM_FILE, path, BUILD_END);
816 }
817 else /* generate an RSA key pair */
818 {
819 private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
820 BUILD_KEY_SIZE, rsa_keylength,
821 BUILD_END);
822 }
823 if (private_key == NULL)
824 {
825 exit_scepclient("no RSA private key available");
826 }
827 public_key = private_key->get_public_key(private_key);
828
829 /* check for minimum key length */
830 if (private_key->get_keysize(private_key) < RSA_MIN_OCTETS / BITS_PER_BYTE)
831 {
832 exit_scepclient("length of RSA key has to be at least %d bits"
833 ,RSA_MIN_OCTETS * BITS_PER_BYTE);
834 }
835
836 /*
837 * input of PKCS#10 file
838 */
839 if (filetype_in & PKCS10)
840 {
841 /* user wants to load a pkcs10 request
842 * operation is not yet supported
843 * would require a PKCS#10 parsing function
844
845 pkcs10 = pkcs10_read_from_file(file_in_pkcs10);
846
847 */
848 }
849 else
850 {
851 if (distinguishedName == NULL)
852 {
853 char buf[BUF_LEN];
854 int n = sprintf(buf, DEFAULT_DN);
855
856 /* set the common name to the hostname */
857 if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
858 {
859 exit_scepclient("no hostname defined, use "
860 "--dn <distinguished name> option");
861 }
862 distinguishedName = buf;
863 }
864
865 DBG(DBG_CONTROL,
866 DBG_log("dn: '%s'", distinguishedName);
867 )
868 subject = identification_create_from_string(distinguishedName);
869 if (subject->get_type(subject) != ID_DER_ASN1_DN)
870 {
871 exit_scepclient("parsing of distinguished name failed");
872 }
873
874 DBG(DBG_CONTROL,
875 DBG_log("building pkcs10 object:")
876 )
877 pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
878 CERT_PKCS10_REQUEST,
879 BUILD_SIGNING_KEY, private_key,
880 BUILD_SUBJECT, subject,
881 BUILD_SUBJECT_ALTNAMES, subjectAltNames,
882 BUILD_CHALLENGE_PWD, challengePassword,
883 BUILD_DIGEST_ALG, pkcs10_signature_alg,
884 BUILD_END);
885 if (!pkcs10_req)
886 {
887 exit_scepclient("generating pkcs10 request failed");
888 }
889 pkcs10_req->get_encoding(pkcs10_req, CERT_ASN1_DER, &pkcs10_encoding);
890 fingerprint = scep_generate_pkcs10_fingerprint(pkcs10_encoding);
891 plog(" fingerprint: %s", fingerprint.ptr);
892 }
893
894 /*
895 * output of PKCS#10 file
896 */
897 if (filetype_out & PKCS10)
898 {
899 char *path = concatenate_paths(REQ_PATH, file_out_pkcs10);
900
901 if (!chunk_write(pkcs10_encoding, path, "pkcs10", 0022, force))
902 {
903 exit_scepclient("could not write pkcs10 file '%s'", path);
904 }
905 filetype_out &= ~PKCS10; /* delete PKCS10 flag */
906 }
907
908 if (!filetype_out)
909 {
910 exit_scepclient(NULL); /* no further output required */
911 }
912
913 /*
914 * output of PKCS#1 file
915 */
916 if (filetype_out & PKCS1)
917 {
918 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_out_pkcs1);
919
920 DBG(DBG_CONTROL,
921 DBG_log("building pkcs1 object:")
922 )
923 if (!private_key->get_encoding(private_key, PRIVKEY_ASN1_DER, &pkcs1) ||
924 !chunk_write(pkcs1, path, "pkcs1", 0066, force))
925 {
926 exit_scepclient("could not write pkcs1 file '%s'", path);
927 }
928 filetype_out &= ~PKCS1; /* delete PKCS1 flag */
929 }
930
931 if (!filetype_out)
932 {
933 exit_scepclient(NULL); /* no further output required */
934 }
935
936 scep_generate_transaction_id(public_key, &transID, &serialNumber);
937 plog(" transaction ID: %.*s", (int)transID.len, transID.ptr);
938
939 notBefore = notBefore ? notBefore : time(NULL);
940 notAfter = notAfter ? notAfter : (notBefore + validity);
941
942 /* generate a self-signed X.509 certificate */
943 x509_signer = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
944 BUILD_SIGNING_KEY, private_key,
945 BUILD_PUBLIC_KEY, public_key,
946 BUILD_SUBJECT, subject,
947 BUILD_NOT_BEFORE_TIME, notBefore,
948 BUILD_NOT_AFTER_TIME, notAfter,
949 BUILD_SERIAL, serialNumber,
950 BUILD_SUBJECT_ALTNAMES, subjectAltNames,
951 BUILD_END);
952 if (!x509_signer)
953 {
954 exit_scepclient("generating certificate failed");
955 }
956
957 /*
958 * output of self-signed X.509 certificate file
959 */
960 if (filetype_out & CERT_SELF)
961 {
962 char *path = concatenate_paths(HOST_CERT_PATH, file_out_cert_self);
963
964 if (!x509_signer->get_encoding(x509_signer, CERT_ASN1_DER, &encoding))
965 {
966 exit_scepclient("encoding certificate failed");
967 }
968 if (!chunk_write(encoding, path, "self-signed cert", 0022, force))
969 {
970 exit_scepclient("could not write self-signed cert file '%s'", path);
971 }
972 chunk_free(&encoding);
973 filetype_out &= ~CERT_SELF; /* delete CERT_SELF flag */
974 }
975
976 if (!filetype_out)
977 {
978 exit_scepclient(NULL); /* no further output required */
979 }
980
981 /*
982 * load ca encryption certificate
983 */
984 {
985 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_enc);
986
987 x509_ca_enc = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
988 BUILD_FROM_FILE, path, BUILD_END);
989 if (!x509_ca_enc)
990 {
991 exit_scepclient("could not load encryption cacert file '%s'", path);
992 }
993 }
994
995 /*
996 * input of PKCS#7 file
997 */
998 if (filetype_in & PKCS7)
999 {
1000 /* user wants to load a pkcs7 encrypted request
1001 * operation is not yet supported!
1002 * would require additional parsing of transaction-id
1003
1004 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
1005
1006 */
1007 }
1008 else
1009 {
1010 DBG(DBG_CONTROL,
1011 DBG_log("building pkcs7 request")
1012 )
1013 pkcs7 = scep_build_request(pkcs10_encoding,
1014 transID, SCEP_PKCSReq_MSG,
1015 x509_ca_enc, pkcs7_symmetric_cipher,
1016 x509_signer, pkcs7_digest_alg, private_key);
1017 }
1018
1019 /*
1020 * output pkcs7 encrypted and signed certificate request
1021 */
1022 if (filetype_out & PKCS7)
1023 {
1024 char *path = concatenate_paths(REQ_PATH, file_out_pkcs7);
1025
1026 if (!chunk_write(pkcs7, path, "pkcs7 encrypted request", 0022, force))
1027 exit_scepclient("could not write pkcs7 file '%s'", path);
1028 ;
1029 filetype_out &= ~PKCS7; /* delete PKCS7 flag */
1030 }
1031
1032 if (!filetype_out)
1033 {
1034 exit_scepclient(NULL); /* no further output required */
1035 }
1036
1037 /*
1038 * output certificate fetch from SCEP server
1039 */
1040 if (filetype_out & CERT)
1041 {
1042 bool stored = FALSE;
1043 certificate_t *cert;
1044 enumerator_t *enumerator;
1045 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_sig);
1046 time_t poll_start = 0;
1047
1048 linked_list_t *certs = linked_list_create();
1049 chunk_t envelopedData = chunk_empty;
1050 chunk_t certData = chunk_empty;
1051 contentInfo_t data = empty_contentInfo;
1052 scep_attributes_t attrs = empty_scep_attributes;
1053
1054 x509_ca_sig = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
1055 BUILD_FROM_FILE, path, BUILD_END);
1056 if (!x509_ca_sig)
1057 {
1058 exit_scepclient("could not load signature cacert file '%s'", path);
1059 }
1060
1061 if (!scep_http_request(scep_url, pkcs7, SCEP_PKI_OPERATION,
1062 http_get_request, &scep_response))
1063 {
1064 exit_scepclient("did not receive a valid scep response");
1065 }
1066 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1067 , x509_ca_sig);
1068 if (ugh != NULL)
1069 {
1070 exit_scepclient(ugh);
1071 }
1072
1073 /* in case of manual mode, we are going into a polling loop */
1074 if (attrs.pkiStatus == SCEP_PENDING)
1075 {
1076 identification_t *issuer = x509_ca_sig->get_subject(x509_ca_sig);
1077
1078 plog(" scep request pending, polling every %d seconds"
1079 , poll_interval);
1080 poll_start = time_monotonic(NULL);
1081 issuerAndSubject = asn1_wrap(ASN1_SEQUENCE, "cc",
1082 issuer->get_encoding(issuer),
1083 subject);
1084 }
1085 while (attrs.pkiStatus == SCEP_PENDING)
1086 {
1087 if (max_poll_time > 0
1088 && (time_monotonic(NULL) - poll_start >= max_poll_time))
1089 {
1090 exit_scepclient("maximum poll time reached: %d seconds"
1091 , max_poll_time);
1092 }
1093 DBG(DBG_CONTROL,
1094 DBG_log("going to sleep for %d seconds", poll_interval)
1095 )
1096 sleep(poll_interval);
1097 free(scep_response.ptr);
1098
1099 DBG(DBG_CONTROL,
1100 DBG_log("fingerprint: %.*s", (int)fingerprint.len, fingerprint.ptr);
1101 DBG_log("transaction ID: %.*s", (int)transID.len, transID.ptr)
1102 )
1103
1104 chunk_free(&getCertInitial);
1105 getCertInitial = scep_build_request(issuerAndSubject
1106 , transID, SCEP_GetCertInitial_MSG
1107 , x509_ca_enc, pkcs7_symmetric_cipher
1108 , x509_signer, pkcs7_digest_alg, private_key);
1109
1110 if (!scep_http_request(scep_url, getCertInitial, SCEP_PKI_OPERATION,
1111 http_get_request, &scep_response))
1112 {
1113 exit_scepclient("did not receive a valid scep response");
1114 }
1115 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1116 , x509_ca_sig);
1117 if (ugh != NULL)
1118 {
1119 exit_scepclient(ugh);
1120 }
1121 }
1122
1123 if (attrs.pkiStatus != SCEP_SUCCESS)
1124 {
1125 exit_scepclient("reply status is not 'SUCCESS'");
1126 }
1127
1128 envelopedData = data.content;
1129
1130 if (data.type != OID_PKCS7_DATA
1131 || !asn1_parse_simple_object(&envelopedData, ASN1_OCTET_STRING, 0, "data"))
1132 {
1133 exit_scepclient("contentInfo is not of type 'data'");
1134 }
1135 if (!pkcs7_parse_envelopedData(envelopedData, &certData
1136 , serialNumber, private_key))
1137 {
1138 exit_scepclient("could not decrypt envelopedData");
1139 }
1140 if (!pkcs7_parse_signedData(certData, NULL, certs, NULL, NULL))
1141 {
1142 exit_scepclient("error parsing the scep response");
1143 }
1144 chunk_free(&certData);
1145
1146 /* store the end entity certificate */
1147 path = concatenate_paths(HOST_CERT_PATH, file_out_cert);
1148
1149 enumerator = certs->create_enumerator(certs);
1150 while (enumerator->enumerate(enumerator, &cert))
1151 {
1152 x509_t *x509 = (x509_t*)cert;
1153
1154 if (!(x509->get_flags(x509) & X509_CA))
1155 {
1156 if (stored)
1157 {
1158 exit_scepclient("multiple certs received, only first stored");
1159 }
1160 if (!cert->get_encoding(cert, CERT_ASN1_DER, &encoding) ||
1161 !chunk_write(encoding, path, "requested cert", 0022, force))
1162 {
1163 exit_scepclient("could not write cert file '%s'", path);
1164 }
1165 chunk_free(&encoding);
1166 stored = TRUE;
1167 }
1168 }
1169 certs->destroy_offset(certs, offsetof(certificate_t, destroy));
1170 filetype_out &= ~CERT; /* delete CERT flag */
1171 }
1172
1173 exit_scepclient(NULL);
1174 return -1; /* should never be reached */
1175 }
1176
1177