2 * Copyright (C) 2012 Tobias Brunner
3 * Copyright (C) 2005 Jan Hutter, Martin Willi
4 * Hochschule fuer Technik Rapperswil
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
29 #include <utils/debug.h>
30 #include <asn1/asn1.h>
32 #include <utils/optionsfrom.h>
33 #include <collections/enumerator.h>
34 #include <collections/linked_list.h>
35 #include <crypto/hashers/hasher.h>
36 #include <crypto/crypters/crypter.h>
37 #include <crypto/proposal/proposal_keywords.h>
38 #include <credentials/keys/private_key.h>
39 #include <credentials/keys/public_key.h>
40 #include <credentials/certificates/certificate.h>
41 #include <credentials/certificates/x509.h>
42 #include <credentials/certificates/pkcs10.h>
43 #include <credentials/sets/mem_cred.h>
44 #include <plugins/plugin.h>
49 * definition of some defaults
53 #define REQ_PATH IPSEC_CONFDIR "/ipsec.d/reqs"
54 #define HOST_CERT_PATH IPSEC_CONFDIR "/ipsec.d/certs"
55 #define CA_CERT_PATH IPSEC_CONFDIR "/ipsec.d/cacerts"
56 #define PRIVATE_KEY_PATH IPSEC_CONFDIR "/ipsec.d/private"
58 /* default name of DER-encoded PKCS#1 private key file */
59 #define DEFAULT_FILENAME_PKCS1 "myKey.der"
61 /* default name of DER-encoded PKCS#10 certificate request file */
62 #define DEFAULT_FILENAME_PKCS10 "myReq.der"
64 /* default name of DER-encoded PKCS#7 file */
65 #define DEFAULT_FILENAME_PKCS7 "pkcs7.der"
67 /* default name of DER-encoded self-signed X.509 certificate file */
68 #define DEFAULT_FILENAME_CERT_SELF "selfCert.der"
70 /* default name of DER-encoded X.509 certificate file */
71 #define DEFAULT_FILENAME_CERT "myCert.der"
73 /* default name of DER-encoded CA cert file used for key encipherment */
74 #define DEFAULT_FILENAME_CACERT_ENC "caCert.der"
76 /* default name of the der encoded CA cert file used for signature verification */
77 #define DEFAULT_FILENAME_CACERT_SIG "caCert.der"
79 /* default prefix of the der encoded CA certificates received from the SCEP server */
80 #define DEFAULT_FILENAME_PREFIX_CACERT "caCert.der"
82 /* default certificate validity */
83 #define DEFAULT_CERT_VALIDITY 5 * 3600 * 24 * 365 /* seconds */
85 /* default polling time interval in SCEP manual mode */
86 #define DEFAULT_POLL_INTERVAL 20 /* seconds */
88 /* default key length for self-generated RSA keys */
89 #define DEFAULT_RSA_KEY_LENGTH 2048 /* bits */
91 /* default distinguished name */
92 #define DEFAULT_DN "C=CH, O=Linux strongSwan, CN="
94 /* minimum RSA key size */
95 #define RSA_MIN_OCTETS (512 / BITS_PER_BYTE)
97 /* challenge password buffer size */
98 #define MAX_PASSWORD_LENGTH 256
100 /* Max length of filename for tempfile */
101 #define MAX_TEMP_FILENAME_LENGTH 256
104 /* current scepclient version */
105 static const char *scepclient_version
= "1.0";
107 /* by default the CRL policy is lenient */
108 bool strict_crl_policy
= FALSE
;
110 /* by default pluto does not check crls dynamically */
111 long crl_check_interval
= 0;
113 /* by default pluto logs out after every smartcard use */
114 bool pkcs11_keep_state
= FALSE
;
116 /* options read by optionsfrom */
124 chunk_t challengePassword
;
125 chunk_t serialNumber
;
129 chunk_t pkcs10_encoding
;
130 chunk_t issuerAndSubject
;
131 chunk_t getCertInitial
;
132 chunk_t scep_response
;
134 linked_list_t
*subjectAltNames
;
136 identification_t
*subject
= NULL
;
137 private_key_t
*private_key
= NULL
;
138 public_key_t
*public_key
= NULL
;
139 certificate_t
*x509_signer
= NULL
;
140 certificate_t
*x509_ca_enc
= NULL
;
141 certificate_t
*x509_ca_sig
= NULL
;
142 certificate_t
*pkcs10_req
= NULL
;
144 mem_cred_t
*creds
= NULL
;
147 static bool log_to_stderr
= TRUE
;
148 static bool log_to_syslog
= TRUE
;
149 static level_t default_loglevel
= 1;
152 * logging function for scepclient
154 static void scepclient_dbg(debug_t group
, level_t level
, char *fmt
, ...)
157 char *current
= buffer
, *next
;
160 if (level
<= default_loglevel
)
165 vfprintf(stderr
, fmt
, args
);
167 fprintf(stderr
, "\n");
171 /* write in memory buffer first */
173 vsnprintf(buffer
, sizeof(buffer
), fmt
, args
);
176 /* do a syslog with every line */
179 next
= strchr(current
, '\n');
184 syslog(LOG_INFO
, "%s\n", current
);
192 * Initialize logging to stderr/syslog
194 static void init_log(const char *program
)
196 dbg
= scepclient_dbg
;
200 setbuf(stderr
, NULL
);
204 openlog(program
, LOG_CONS
| LOG_NDELAY
| LOG_PID
, LOG_AUTHPRIV
);
209 * join two paths if filename is not absolute
211 static void join_paths(char *target
, size_t target_size
, char *parent
,
214 if (*filename
== '/' || *filename
== '.')
216 snprintf(target
, target_size
, "%s", filename
);
220 snprintf(target
, target_size
, "%s/%s", parent
, filename
);
225 * add a suffix to a given filename, properly handling extensions like '.der'
227 static void add_path_suffix(char *target
, size_t target_size
, char *filename
,
228 char *suffix_fmt
, ...)
230 char suffix
[PATH_MAX
], *start
, *dot
;
233 va_start(args
, suffix_fmt
);
234 vsnprintf(suffix
, sizeof(suffix
), suffix_fmt
, args
);
237 start
= strrchr(filename
, '/');
238 start
= start
?: filename
;
239 dot
= strrchr(start
, '.');
241 if (!dot
|| dot
== start
|| dot
[1] == '\0')
242 { /* no extension add suffix at the end */
243 snprintf(target
, target_size
, "%s%s", filename
, suffix
);
246 { /* add the suffix between the filename and the extension */
247 snprintf(target
, target_size
, "%.*s%s%s", (int)(dot
- filename
),
248 filename
, suffix
, dot
);
253 * @brief exit scepclient
255 * @param status 0 = OK, 1 = general discomfort
257 static void exit_scepclient(err_t message
, ...)
263 lib
->credmgr
->remove_set(lib
->credmgr
, &creds
->set
);
264 creds
->destroy(creds
);
268 DESTROY_IF(private_key
);
269 DESTROY_IF(public_key
);
270 DESTROY_IF(x509_signer
);
271 DESTROY_IF(x509_ca_enc
);
272 DESTROY_IF(x509_ca_sig
);
273 DESTROY_IF(pkcs10_req
);
274 subjectAltNames
->destroy_offset(subjectAltNames
,
275 offsetof(identification_t
, destroy
));
278 free(serialNumber
.ptr
);
280 free(fingerprint
.ptr
);
282 free(pkcs10_encoding
.ptr
);
283 free(issuerAndSubject
.ptr
);
284 free(getCertInitial
.ptr
);
285 free(scep_response
.ptr
);
286 options
->destroy(options
);
288 /* print any error message to stderr */
289 if (message
!= NULL
&& *message
!= '\0')
294 va_start(args
, message
);
295 vsnprintf(m
, sizeof(m
), message
, args
);
298 fprintf(stderr
, "error: %s\n", m
);
306 * @brief prints the program version and exits
309 static void version(void)
311 printf("scepclient %s\n", scepclient_version
);
312 exit_scepclient(NULL
);
316 * @brief prints the usage of the program to the stderr output
318 * If message is set, program is exitet with 1 (error)
319 * @param message message in case of an error
321 static void usage(const char *message
)
324 "Usage: scepclient\n"
325 " --help (-h) show usage and exit\n"
326 " --version (-v) show version and exit\n"
327 " --quiet (-q) do not write log output to stderr\n"
328 " --in (-i) <type>[=<filename>] use <filename> of <type> for input\n"
329 " <type> = pkcs1 | pkcs10 | cert-self\n"
330 " cacert-enc | cacert-sig\n"
331 " - if no pkcs1 input is defined, an RSA\n"
332 " key will be generated\n"
333 " - if no pkcs10 input is defined, a\n"
334 " PKCS#10 request will be generated\n"
335 " - if no cert-self input is defined, a\n"
336 " self-signed certificate will be generated\n"
337 " - if no filename is given, default is used\n"
338 " --out (-o) <type>[=<filename>] write output of <type> to <filename>\n"
339 " multiple outputs are allowed\n"
340 " <type> = pkcs1 | pkcs10 | pkcs7 | cert-self |\n"
342 " - type cacert defines filename prefix of\n"
343 " received CA certificate(s)\n"
344 " - if no filename is given, default is used\n"
345 " --optionsfrom (-+) <filename> reads additional options from given file\n"
346 " --force (-f) force existing file(s)\n"
348 "Options for key generation (pkcs1):\n"
349 " --keylength (-k) <bits> key length for RSA key generation\n"
350 " (default: 2048 bits)\n"
352 "Options for validity:\n"
353 " --days (-D) <days> validity in days\n"
354 " --startdate (-S) <YYMMDDHHMMSS>Z not valid before date\n"
355 " --enddate (-E) <YYMMDDHHMMSS>Z not valid after date\n"
357 "Options for request generation (pkcs10):\n"
358 " --dn (-d) <dn> comma separated list of distinguished names\n"
359 " --subjectAltName (-s) <t>=<v> include subjectAltName in certificate request\n"
360 " <t> = email | dns | ip \n"
361 " --password (-p) <pw> challenge password\n"
362 " - use '%%prompt' as pw for a password prompt\n"
363 " --algorithm (-a) [<type>=]<algo> algorithm to be used for PKCS#7 encryption,\n"
364 " PKCS#7 digest or PKCS#10 signature\n"
365 " <type> = enc | dgst | sig\n"
366 " - if no type is given enc is assumed\n"
367 " <algo> = des (default) | 3des | aes128 |\n"
368 " aes192 | aes256 | camellia128 |\n"
369 " camellia192 | camellia256\n"
370 " <algo> = md5 (default) | sha1 | sha256 |\n"
373 "Options for CA certificate acquisition:\n"
374 " --caname (-c) <name> name of CA to fetch CA certificate(s)\n"
375 " (default: CAIdentifier)\n"
376 "Options for enrollment (cert):\n"
377 " --url (-u) <url> url of the SCEP server\n"
378 " --method (-m) post | get http request type\n"
379 " --interval (-t) <seconds> poll interval in seconds (default 20s)\n"
380 " --maxpolltime (-x) <seconds> max poll time in seconds when in manual mode\n"
381 " (default: unlimited)\n"
383 "Debugging output:\n"
384 " --debug (-l) <level> changes the log level (-1..4, default: 1)\n"
386 exit_scepclient(message
);
390 * @brief main of scepclient
392 * @param argc number of arguments
393 * @param argv pointer to the argument values
395 int main(int argc
, char **argv
)
397 /* external values */
398 extern char * optarg
;
401 /* type of input and output files */
412 /* filetype to read from, defaults to "generate a key" */
413 scep_filetype_t filetype_in
= 0;
415 /* filetype to write to, no default here */
416 scep_filetype_t filetype_out
= 0;
419 char *file_in_pkcs1
= DEFAULT_FILENAME_PKCS1
;
420 char *file_in_pkcs10
= DEFAULT_FILENAME_PKCS10
;
421 char *file_in_cert_self
= DEFAULT_FILENAME_CERT_SELF
;
422 char *file_in_cacert_enc
= DEFAULT_FILENAME_CACERT_ENC
;
423 char *file_in_cacert_sig
= DEFAULT_FILENAME_CACERT_SIG
;
426 char *file_out_pkcs1
= DEFAULT_FILENAME_PKCS1
;
427 char *file_out_pkcs10
= DEFAULT_FILENAME_PKCS10
;
428 char *file_out_pkcs7
= DEFAULT_FILENAME_PKCS7
;
429 char *file_out_cert_self
= DEFAULT_FILENAME_CERT_SELF
;
430 char *file_out_cert
= DEFAULT_FILENAME_CERT
;
431 char *file_out_ca_cert
= DEFAULT_FILENAME_CACERT_ENC
;
433 /* by default user certificate is requested */
434 bool request_ca_certificate
= FALSE
;
436 /* by default existing files are not overwritten */
439 /* length of RSA key in bits */
440 u_int rsa_keylength
= DEFAULT_RSA_KEY_LENGTH
;
442 /* validity of self-signed certificate */
443 time_t validity
= DEFAULT_CERT_VALIDITY
;
444 time_t notBefore
= 0;
447 /* distinguished name for requested certificate, ASCII format */
448 char *distinguishedName
= NULL
;
450 /* challenge password */
451 char challenge_password_buffer
[MAX_PASSWORD_LENGTH
];
453 /* symmetric encryption algorithm used by pkcs7, default is DES */
454 encryption_algorithm_t pkcs7_symmetric_cipher
= ENCR_DES
;
455 size_t pkcs7_key_size
= 0;
457 /* digest algorithm used by pkcs7, default is MD5 */
458 hash_algorithm_t pkcs7_digest_alg
= HASH_MD5
;
460 /* signature algorithm used by pkcs10, default is MD5 */
461 hash_algorithm_t pkcs10_signature_alg
= HASH_MD5
;
463 /* URL of the SCEP-Server */
464 char *scep_url
= NULL
;
466 /* Name of CA to fetch CA certs for */
467 char *ca_name
= "CAIdentifier";
469 /* http request method, default is GET */
470 bool http_get_request
= TRUE
;
472 /* poll interval time in manual mode in seconds */
473 u_int poll_interval
= DEFAULT_POLL_INTERVAL
;
475 /* maximum poll time */
476 u_int max_poll_time
= 0;
480 /* initialize library */
481 if (!library_init(NULL
))
484 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY
);
486 if (lib
->integrity
&&
487 !lib
->integrity
->check_file(lib
->integrity
, "scepclient", argv
[0]))
489 fprintf(stderr
, "integrity check of scepclient failed\n");
491 exit(SS_RC_DAEMON_INTEGRITY
);
494 /* initialize global variables */
497 serialNumber
= chunk_empty
;
498 transID
= chunk_empty
;
499 fingerprint
= chunk_empty
;
500 encoding
= chunk_empty
;
501 pkcs10_encoding
= chunk_empty
;
502 issuerAndSubject
= chunk_empty
;
503 challengePassword
= chunk_empty
;
504 getCertInitial
= chunk_empty
;
505 scep_response
= chunk_empty
;
506 subjectAltNames
= linked_list_create();
507 options
= options_create();
511 static const struct option long_opts
[] = {
512 /* name, has_arg, flag, val */
513 { "help", no_argument
, NULL
, 'h' },
514 { "version", no_argument
, NULL
, 'v' },
515 { "optionsfrom", required_argument
, NULL
, '+' },
516 { "quiet", no_argument
, NULL
, 'q' },
517 { "debug", required_argument
, NULL
, 'l' },
518 { "in", required_argument
, NULL
, 'i' },
519 { "out", required_argument
, NULL
, 'o' },
520 { "force", no_argument
, NULL
, 'f' },
521 { "keylength", required_argument
, NULL
, 'k' },
522 { "dn", required_argument
, NULL
, 'd' },
523 { "days", required_argument
, NULL
, 'D' },
524 { "startdate", required_argument
, NULL
, 'S' },
525 { "enddate", required_argument
, NULL
, 'E' },
526 { "subjectAltName", required_argument
, NULL
, 's' },
527 { "password", required_argument
, NULL
, 'p' },
528 { "algorithm", required_argument
, NULL
, 'a' },
529 { "url", required_argument
, NULL
, 'u' },
530 { "caname", required_argument
, NULL
, 'c'},
531 { "method", required_argument
, NULL
, 'm' },
532 { "interval", required_argument
, NULL
, 't' },
533 { "maxpolltime", required_argument
, NULL
, 'x' },
537 /* parse next option */
538 int c
= getopt_long(argc
, argv
, "hv+:qi:o:fk:d:s:p:a:u:c:m:t:x:APRCMS", long_opts
, NULL
);
542 case EOF
: /* end of flags */
545 case 'h': /* --help */
548 case 'v': /* --version */
551 case 'q': /* --quiet */
552 log_to_stderr
= FALSE
;
555 case 'l': /* --debug <level> */
556 default_loglevel
= atoi(optarg
);
559 case 'i': /* --in <type> [= <filename>] */
561 char *filename
= strstr(optarg
, "=");
565 /* replace '=' by '\0' */
567 /* set pointer to start of filename */
570 if (strcaseeq("pkcs1", optarg
))
572 filetype_in
|= PKCS1
;
574 file_in_pkcs1
= filename
;
576 else if (strcaseeq("pkcs10", optarg
))
578 filetype_in
|= PKCS10
;
580 file_in_pkcs10
= filename
;
582 else if (strcaseeq("cacert-enc", optarg
))
584 filetype_in
|= CACERT_ENC
;
586 file_in_cacert_enc
= filename
;
588 else if (strcaseeq("cacert-sig", optarg
))
590 filetype_in
|= CACERT_SIG
;
592 file_in_cacert_sig
= filename
;
594 else if (strcaseeq("cert-self", optarg
))
596 filetype_in
|= CERT_SELF
;
598 file_in_cert_self
= filename
;
602 usage("invalid --in file type");
607 case 'o': /* --out <type> [= <filename>] */
609 char *filename
= strstr(optarg
, "=");
613 /* replace '=' by '\0' */
615 /* set pointer to start of filename */
618 if (strcaseeq("pkcs1", optarg
))
620 filetype_out
|= PKCS1
;
622 file_out_pkcs1
= filename
;
624 else if (strcaseeq("pkcs10", optarg
))
626 filetype_out
|= PKCS10
;
628 file_out_pkcs10
= filename
;
630 else if (strcaseeq("pkcs7", optarg
))
632 filetype_out
|= PKCS7
;
634 file_out_pkcs7
= filename
;
636 else if (strcaseeq("cert-self", optarg
))
638 filetype_out
|= CERT_SELF
;
640 file_out_cert_self
= filename
;
642 else if (strcaseeq("cert", optarg
))
644 filetype_out
|= CERT
;
646 file_out_cert
= filename
;
648 else if (strcaseeq("cacert", optarg
))
650 request_ca_certificate
= TRUE
;
652 file_out_ca_cert
= filename
;
656 usage("invalid --out file type");
661 case 'f': /* --force */
665 case '+': /* --optionsfrom <filename> */
666 if (!options
->from(options
, optarg
, &argc
, &argv
, optind
))
668 exit_scepclient("optionsfrom failed");
672 case 'k': /* --keylength <length> */
676 rsa_keylength
= atoi(optarg
);
677 if (rsa_keylength
== 0)
678 usage("invalid keylength");
680 /* check if key length is a multiple of 8 bits */
681 q
= div(rsa_keylength
, 2*BITS_PER_BYTE
);
684 exit_scepclient("keylength is not a multiple of %d bits!"
690 case 'D': /* --days */
691 if (optarg
== NULL
|| !isdigit(optarg
[0]))
693 usage("missing number of days");
698 long days
= strtol(optarg
, &endptr
, 0);
700 if (*endptr
!= '\0' || endptr
== optarg
702 usage("<days> must be a positive number");
703 validity
= 24*3600*days
;
707 case 'S': /* --startdate */
708 if (optarg
== NULL
|| strlen(optarg
) != 13 || optarg
[12] != 'Z')
710 usage("date format must be YYMMDDHHMMSSZ");
714 chunk_t date
= { optarg
, 13 };
715 notBefore
= asn1_to_time(&date
, ASN1_UTCTIME
);
719 case 'E': /* --enddate */
720 if (optarg
== NULL
|| strlen(optarg
) != 13 || optarg
[12] != 'Z')
722 usage("date format must be YYMMDDHHMMSSZ");
726 chunk_t date
= { optarg
, 13 };
727 notAfter
= asn1_to_time(&date
, ASN1_UTCTIME
);
732 if (distinguishedName
)
734 usage("only one distinguished name allowed");
736 distinguishedName
= optarg
;
739 case 's': /* --subjectAltName */
741 char *value
= strstr(optarg
, "=");
745 /* replace '=' by '\0' */
747 /* set pointer to start of value */
751 if (strcaseeq("email", optarg
) ||
752 strcaseeq("dns", optarg
) ||
753 strcaseeq("ip", optarg
))
755 subjectAltNames
->insert_last(subjectAltNames
,
756 identification_create_from_string(value
));
761 usage("invalid --subjectAltName type");
766 case 'p': /* --password */
767 if (challengePassword
.len
> 0)
769 usage("only one challenge password allowed");
771 if (strcaseeq("%prompt", optarg
))
773 printf("Challenge password: ");
774 if (fgets(challenge_password_buffer
,
775 sizeof(challenge_password_buffer
) - 1, stdin
))
777 challengePassword
.ptr
= challenge_password_buffer
;
778 /* discard the terminating '\n' from the input */
779 challengePassword
.len
= strlen(challenge_password_buffer
) - 1;
783 usage("challenge password could not be read");
788 challengePassword
.ptr
= optarg
;
789 challengePassword
.len
= strlen(optarg
);
793 case 'u': /* -- url */
796 usage("only one URL argument allowed");
801 case 'c': /* -- caname */
805 case 'm': /* --method */
806 if (strcaseeq("get", optarg
))
808 http_get_request
= TRUE
;
810 else if (strcaseeq("post", optarg
))
812 http_get_request
= FALSE
;
816 usage("invalid http request method specified");
820 case 't': /* --interval */
821 poll_interval
= atoi(optarg
);
822 if (poll_interval
<= 0)
824 usage("invalid interval specified");
828 case 'x': /* --maxpolltime */
829 max_poll_time
= atoi(optarg
);
832 case 'a': /*--algorithm [<type>=]algo */
834 const proposal_token_t
*token
;
836 char *algo
= strstr(optarg
, "=");
849 if (strcaseeq("enc", type
))
851 token
= lib
->proposal
->get_token(lib
->proposal
, algo
);
852 if (token
== NULL
|| token
->type
!= ENCRYPTION_ALGORITHM
)
854 usage("invalid algorithm specified");
856 pkcs7_symmetric_cipher
= token
->algorithm
;
857 pkcs7_key_size
= token
->keysize
;
858 if (encryption_algorithm_to_oid(token
->algorithm
,
859 token
->keysize
) == OID_UNKNOWN
)
861 usage("unsupported encryption algorithm specified");
864 else if (strcaseeq("dgst", type
) ||
865 strcaseeq("sig", type
))
867 hash_algorithm_t hash
;
869 token
= lib
->proposal
->get_token(lib
->proposal
, algo
);
870 if (token
== NULL
|| token
->type
!= INTEGRITY_ALGORITHM
)
872 usage("invalid algorithm specified");
874 hash
= hasher_algorithm_from_integrity(token
->algorithm
,
876 if (hash
== OID_UNKNOWN
)
878 usage("invalid algorithm specified");
880 if (strcaseeq("dgst", type
))
882 pkcs7_digest_alg
= hash
;
886 pkcs10_signature_alg
= hash
;
891 usage("invalid --algorithm type");
896 usage("unknown option");
898 /* break from loop */
902 init_log("scepclient");
904 /* load plugins, further infrastructure may need it */
905 if (!lib
->plugins
->load(lib
->plugins
, NULL
,
906 lib
->settings
->get_str(lib
->settings
, "scepclient.load", PLUGINS
)))
908 exit_scepclient("plugin loading failed");
910 DBG1(DBG_APP
, " loaded plugins: %s",
911 lib
->plugins
->loaded_plugins(lib
->plugins
));
913 if ((filetype_out
== 0) && (!request_ca_certificate
))
915 usage("--out filetype required");
917 if (request_ca_certificate
&& (filetype_out
> 0 || filetype_in
> 0))
919 usage("in CA certificate request, no other --in or --out option allowed");
922 /* check if url is given, if cert output defined */
923 if (((filetype_out
& CERT
) || request_ca_certificate
) && !scep_url
)
925 usage("URL of SCEP server required");
928 /* check for sanity of --in/--out */
929 if (!filetype_in
&& (filetype_in
> filetype_out
))
931 usage("cannot generate --out of given --in!");
935 if (request_ca_certificate
)
937 char ca_path
[PATH_MAX
];
938 container_t
*container
;
941 if (!scep_http_request(scep_url
, chunk_create(ca_name
, strlen(ca_name
)),
942 SCEP_GET_CA_CERT
, http_get_request
, &scep_response
))
944 exit_scepclient("did not receive a valid scep response");
947 join_paths(ca_path
, sizeof(ca_path
), CA_CERT_PATH
, file_out_ca_cert
);
949 pkcs7
= lib
->creds
->create(lib
->creds
, CRED_CONTAINER
, CONTAINER_PKCS7
,
950 BUILD_BLOB_ASN1_DER
, scep_response
, BUILD_END
);
953 { /* no PKCS#7 encoded CA+RA certificates, assume simple CA cert */
955 DBG1(DBG_APP
, "unable to parse PKCS#7, assuming plain CA cert");
956 if (!chunk_write(scep_response
, ca_path
, "ca cert", 0022, force
))
958 exit_scepclient("could not write ca cert file '%s'", ca_path
);
963 enumerator_t
*enumerator
;
965 int ra_certs
= 0, ca_certs
= 0;
966 int ra_index
= 1, ca_index
= 1;
968 enumerator
= pkcs7
->create_cert_enumerator(pkcs7
);
969 while (enumerator
->enumerate(enumerator
, &cert
))
971 x509_t
*x509
= (x509_t
*)cert
;
972 if (x509
->get_flags(x509
) & X509_CA
)
981 enumerator
->destroy(enumerator
);
983 enumerator
= pkcs7
->create_cert_enumerator(pkcs7
);
984 while (enumerator
->enumerate(enumerator
, &cert
))
986 x509_t
*x509
= (x509_t
*)cert
;
987 bool ca_cert
= x509
->get_flags(x509
) & X509_CA
;
988 char cert_path
[PATH_MAX
], *path
= ca_path
;
990 if (ca_cert
&& ca_certs
> 1)
992 add_path_suffix(cert_path
, sizeof(cert_path
), ca_path
,
993 "-%.1d", ca_index
++);
997 { /* use CA name as base for RA certs */
1000 add_path_suffix(cert_path
, sizeof(cert_path
), ca_path
,
1001 "-ra-%.1d", ra_index
++);
1005 add_path_suffix(cert_path
, sizeof(cert_path
), ca_path
,
1011 if (!cert
->get_encoding(cert
, CERT_ASN1_DER
, &encoding
) ||
1012 !chunk_write(encoding
, path
,
1013 ca_cert
? "ca cert" : "ra cert", 0022, force
))
1015 exit_scepclient("could not write cert file '%s'", path
);
1017 chunk_free(&encoding
);
1019 enumerator
->destroy(enumerator
);
1020 container
= &pkcs7
->container
;
1021 container
->destroy(container
);
1023 exit_scepclient(NULL
); /* no further output required */
1026 creds
= mem_cred_create();
1027 lib
->credmgr
->add_set(lib
->credmgr
, &creds
->set
);
1030 * input of PKCS#1 file
1032 if (filetype_in
& PKCS1
) /* load an RSA key pair from file */
1034 char path
[PATH_MAX
];
1036 join_paths(path
, sizeof(path
), PRIVATE_KEY_PATH
, file_in_pkcs1
);
1038 private_key
= lib
->creds
->create(lib
->creds
, CRED_PRIVATE_KEY
, KEY_RSA
,
1039 BUILD_FROM_FILE
, path
, BUILD_END
);
1041 else /* generate an RSA key pair */
1043 private_key
= lib
->creds
->create(lib
->creds
, CRED_PRIVATE_KEY
, KEY_RSA
,
1044 BUILD_KEY_SIZE
, rsa_keylength
,
1047 if (private_key
== NULL
)
1049 exit_scepclient("no RSA private key available");
1051 creds
->add_key(creds
, private_key
->get_ref(private_key
));
1052 public_key
= private_key
->get_public_key(private_key
);
1054 /* check for minimum key length */
1055 if (private_key
->get_keysize(private_key
) < RSA_MIN_OCTETS
/ BITS_PER_BYTE
)
1057 exit_scepclient("length of RSA key has to be at least %d bits",
1058 RSA_MIN_OCTETS
* BITS_PER_BYTE
);
1062 * input of PKCS#10 file
1064 if (filetype_in
& PKCS10
)
1066 char path
[PATH_MAX
];
1068 join_paths(path
, sizeof(path
), REQ_PATH
, file_in_pkcs10
);
1070 pkcs10_req
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
,
1071 CERT_PKCS10_REQUEST
, BUILD_FROM_FILE
,
1075 exit_scepclient("could not read certificate request '%s'", path
);
1077 subject
= pkcs10_req
->get_subject(pkcs10_req
);
1078 subject
= subject
->clone(subject
);
1082 if (distinguishedName
== NULL
)
1085 int n
= sprintf(buf
, DEFAULT_DN
);
1087 /* set the common name to the hostname */
1088 if (gethostname(buf
+ n
, BUF_LEN
- n
) || strlen(buf
) == n
)
1090 exit_scepclient("no hostname defined, use "
1091 "--dn <distinguished name> option");
1093 distinguishedName
= buf
;
1096 DBG2(DBG_APP
, "dn: '%s'", distinguishedName
);
1097 subject
= identification_create_from_string(distinguishedName
);
1098 if (subject
->get_type(subject
) != ID_DER_ASN1_DN
)
1100 exit_scepclient("parsing of distinguished name failed");
1103 DBG2(DBG_APP
, "building pkcs10 object:");
1104 pkcs10_req
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
,
1105 CERT_PKCS10_REQUEST
,
1106 BUILD_SIGNING_KEY
, private_key
,
1107 BUILD_SUBJECT
, subject
,
1108 BUILD_SUBJECT_ALTNAMES
, subjectAltNames
,
1109 BUILD_CHALLENGE_PWD
, challengePassword
,
1110 BUILD_DIGEST_ALG
, pkcs10_signature_alg
,
1114 exit_scepclient("generating pkcs10 request failed");
1117 pkcs10_req
->get_encoding(pkcs10_req
, CERT_ASN1_DER
, &pkcs10_encoding
);
1118 fingerprint
= scep_generate_pkcs10_fingerprint(pkcs10_encoding
);
1119 DBG1(DBG_APP
, " fingerprint: %s", fingerprint
.ptr
);
1122 * output of PKCS#10 file
1124 if (filetype_out
& PKCS10
)
1126 char path
[PATH_MAX
];
1128 join_paths(path
, sizeof(path
), REQ_PATH
, file_out_pkcs10
);
1130 if (!chunk_write(pkcs10_encoding
, path
, "pkcs10", 0022, force
))
1132 exit_scepclient("could not write pkcs10 file '%s'", path
);
1134 filetype_out
&= ~PKCS10
; /* delete PKCS10 flag */
1139 exit_scepclient(NULL
); /* no further output required */
1143 * output of PKCS#1 file
1145 if (filetype_out
& PKCS1
)
1147 char path
[PATH_MAX
];
1149 join_paths(path
, sizeof(path
), PRIVATE_KEY_PATH
, file_out_pkcs1
);
1151 DBG2(DBG_APP
, "building pkcs1 object:");
1152 if (!private_key
->get_encoding(private_key
, PRIVKEY_ASN1_DER
, &pkcs1
) ||
1153 !chunk_write(pkcs1
, path
, "pkcs1", 0066, force
))
1155 exit_scepclient("could not write pkcs1 file '%s'", path
);
1157 filetype_out
&= ~PKCS1
; /* delete PKCS1 flag */
1162 exit_scepclient(NULL
); /* no further output required */
1165 scep_generate_transaction_id(public_key
, &transID
, &serialNumber
);
1166 DBG1(DBG_APP
, " transaction ID: %.*s", (int)transID
.len
, transID
.ptr
);
1169 * read or generate self-signed X.509 certificate
1171 if (filetype_in
& CERT_SELF
)
1173 char path
[PATH_MAX
];
1175 join_paths(path
, sizeof(path
), HOST_CERT_PATH
, file_in_cert_self
);
1177 x509_signer
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1178 BUILD_FROM_FILE
, path
, BUILD_END
);
1181 exit_scepclient("could not read certificate file '%s'", path
);
1186 notBefore
= notBefore
? notBefore
: time(NULL
);
1187 notAfter
= notAfter
? notAfter
: (notBefore
+ validity
);
1188 x509_signer
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1189 BUILD_SIGNING_KEY
, private_key
,
1190 BUILD_PUBLIC_KEY
, public_key
,
1191 BUILD_SUBJECT
, subject
,
1192 BUILD_NOT_BEFORE_TIME
, notBefore
,
1193 BUILD_NOT_AFTER_TIME
, notAfter
,
1194 BUILD_SERIAL
, serialNumber
,
1195 BUILD_SUBJECT_ALTNAMES
, subjectAltNames
,
1199 exit_scepclient("generating certificate failed");
1202 creds
->add_cert(creds
, TRUE
, x509_signer
->get_ref(x509_signer
));
1205 * output of self-signed X.509 certificate file
1207 if (filetype_out
& CERT_SELF
)
1209 char path
[PATH_MAX
];
1211 join_paths(path
, sizeof(path
), HOST_CERT_PATH
, file_out_cert_self
);
1213 if (!x509_signer
->get_encoding(x509_signer
, CERT_ASN1_DER
, &encoding
))
1215 exit_scepclient("encoding certificate failed");
1217 if (!chunk_write(encoding
, path
, "self-signed cert", 0022, force
))
1219 exit_scepclient("could not write self-signed cert file '%s'", path
);
1221 chunk_free(&encoding
);
1222 filetype_out
&= ~CERT_SELF
; /* delete CERT_SELF flag */
1227 exit_scepclient(NULL
); /* no further output required */
1231 * load ca encryption certificate
1234 char path
[PATH_MAX
];
1236 join_paths(path
, sizeof(path
), CA_CERT_PATH
, file_in_cacert_enc
);
1238 x509_ca_enc
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1239 BUILD_FROM_FILE
, path
, BUILD_END
);
1242 exit_scepclient("could not load encryption cacert file '%s'", path
);
1247 * input of PKCS#7 file
1249 if (filetype_in
& PKCS7
)
1251 /* user wants to load a pkcs7 encrypted request
1252 * operation is not yet supported!
1253 * would require additional parsing of transaction-id
1255 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
1261 DBG2(DBG_APP
, "building pkcs7 request");
1262 pkcs7
= scep_build_request(pkcs10_encoding
,
1263 transID
, SCEP_PKCSReq_MSG
, x509_ca_enc
,
1264 pkcs7_symmetric_cipher
, pkcs7_key_size
,
1265 x509_signer
, pkcs7_digest_alg
, private_key
);
1268 exit_scepclient("failed to build pkcs7 request");
1273 * output pkcs7 encrypted and signed certificate request
1275 if (filetype_out
& PKCS7
)
1277 char path
[PATH_MAX
];
1279 join_paths(path
, sizeof(path
), REQ_PATH
, file_out_pkcs7
);
1281 if (!chunk_write(pkcs7
, path
, "pkcs7 encrypted request", 0022, force
))
1283 exit_scepclient("could not write pkcs7 file '%s'", path
);
1285 filetype_out
&= ~PKCS7
; /* delete PKCS7 flag */
1290 exit_scepclient(NULL
); /* no further output required */
1294 * output certificate fetch from SCEP server
1296 if (filetype_out
& CERT
)
1298 bool stored
= FALSE
;
1299 certificate_t
*cert
;
1300 enumerator_t
*enumerator
;
1301 char path
[PATH_MAX
];
1302 time_t poll_start
= 0;
1304 container_t
*container
= NULL
;
1306 scep_attributes_t attrs
= empty_scep_attributes
;
1308 join_paths(path
, sizeof(path
), CA_CERT_PATH
, file_in_cacert_sig
);
1310 x509_ca_sig
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1311 BUILD_FROM_FILE
, path
, BUILD_END
);
1314 exit_scepclient("could not load signature cacert file '%s'", path
);
1317 creds
->add_cert(creds
, TRUE
, x509_ca_sig
->get_ref(x509_ca_sig
));
1319 if (!scep_http_request(scep_url
, pkcs7
, SCEP_PKI_OPERATION
,
1320 http_get_request
, &scep_response
))
1322 exit_scepclient("did not receive a valid scep response");
1324 ugh
= scep_parse_response(scep_response
, transID
, &container
, &attrs
);
1327 exit_scepclient(ugh
);
1330 /* in case of manual mode, we are going into a polling loop */
1331 if (attrs
.pkiStatus
== SCEP_PENDING
)
1333 identification_t
*issuer
= x509_ca_sig
->get_subject(x509_ca_sig
);
1335 DBG1(DBG_APP
, " scep request pending, polling every %d seconds",
1337 poll_start
= time_monotonic(NULL
);
1338 issuerAndSubject
= asn1_wrap(ASN1_SEQUENCE
, "cc",
1339 issuer
->get_encoding(issuer
),
1342 while (attrs
.pkiStatus
== SCEP_PENDING
)
1344 if (max_poll_time
> 0 &&
1345 (time_monotonic(NULL
) - poll_start
>= max_poll_time
))
1347 exit_scepclient("maximum poll time reached: %d seconds"
1350 DBG2(DBG_APP
, "going to sleep for %d seconds", poll_interval
);
1351 sleep(poll_interval
);
1352 free(scep_response
.ptr
);
1353 container
->destroy(container
);
1355 DBG2(DBG_APP
, "fingerprint: %.*s",
1356 (int)fingerprint
.len
, fingerprint
.ptr
);
1357 DBG2(DBG_APP
, "transaction ID: %.*s",
1358 (int)transID
.len
, transID
.ptr
);
1360 chunk_free(&getCertInitial
);
1361 getCertInitial
= scep_build_request(issuerAndSubject
,
1362 transID
, SCEP_GetCertInitial_MSG
, x509_ca_enc
,
1363 pkcs7_symmetric_cipher
, pkcs7_key_size
,
1364 x509_signer
, pkcs7_digest_alg
, private_key
);
1365 if (!getCertInitial
.ptr
)
1367 exit_scepclient("failed to build scep request");
1369 if (!scep_http_request(scep_url
, getCertInitial
, SCEP_PKI_OPERATION
,
1370 http_get_request
, &scep_response
))
1372 exit_scepclient("did not receive a valid scep response");
1374 ugh
= scep_parse_response(scep_response
, transID
, &container
, &attrs
);
1377 exit_scepclient(ugh
);
1381 if (attrs
.pkiStatus
!= SCEP_SUCCESS
)
1383 container
->destroy(container
);
1384 exit_scepclient("reply status is not 'SUCCESS'");
1387 if (!container
->get_data(container
, &chunk
))
1389 container
->destroy(container
);
1390 exit_scepclient("extracting signed-data failed");
1392 container
->destroy(container
);
1394 /* decrypt enveloped-data container */
1395 container
= lib
->creds
->create(lib
->creds
,
1396 CRED_CONTAINER
, CONTAINER_PKCS7
,
1397 BUILD_BLOB_ASN1_DER
, chunk
,
1402 exit_scepclient("could not decrypt envelopedData");
1405 if (!container
->get_data(container
, &chunk
))
1407 container
->destroy(container
);
1408 exit_scepclient("extracting signed-data failed");
1410 container
->destroy(container
);
1412 /* parse signed-data container */
1413 container
= lib
->creds
->create(lib
->creds
,
1414 CRED_CONTAINER
, CONTAINER_PKCS7
,
1415 BUILD_BLOB_ASN1_DER
, chunk
,
1420 exit_scepclient("could not parse singed-data");
1422 /* no need to verify the signed-data container, the signature does NOT
1423 * cover the contained certificates */
1425 /* store the end entity certificate */
1426 join_paths(path
, sizeof(path
), HOST_CERT_PATH
, file_out_cert
);
1428 p7
= (pkcs7_t
*)container
;
1429 enumerator
= p7
->create_cert_enumerator(p7
);
1430 while (enumerator
->enumerate(enumerator
, &cert
))
1432 x509_t
*x509
= (x509_t
*)cert
;
1434 if (!(x509
->get_flags(x509
) & X509_CA
))
1438 exit_scepclient("multiple certs received, only first stored");
1440 if (!cert
->get_encoding(cert
, CERT_ASN1_DER
, &encoding
) ||
1441 !chunk_write(encoding
, path
, "requested cert", 0022, force
))
1443 exit_scepclient("could not write cert file '%s'", path
);
1445 chunk_free(&encoding
);
1449 enumerator
->destroy(enumerator
);
1450 container
->destroy(container
);
1451 filetype_out
&= ~CERT
; /* delete CERT flag */
1454 exit_scepclient(NULL
);
1455 return -1; /* should never be reached */