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