minor updates on upcoming changelog
[tor.git] / src / tools / tor-gencert.c
blobfb7465c0eb8df741a15ce6ed5a13acf214a488d6
1 /* Copyright (c) 2007-2017, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 #include "orconfig.h"
6 #include <stdio.h>
7 #include <string.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <fcntl.h>
12 #ifdef HAVE_UNISTD_H
13 #include <unistd.h>
14 #endif
16 #include "compat.h"
18 /* Some versions of OpenSSL declare X509_STORE_CTX_set_verify_cb twice in
19 * x509.h and x509_vfy.h. Suppress the GCC warning so we can build with
20 * -Wredundant-decl. */
21 DISABLE_GCC_WARNING(redundant-decls)
23 #include <openssl/evp.h>
24 #include <openssl/pem.h>
25 #include <openssl/rsa.h>
26 #include <openssl/objects.h>
27 #include <openssl/obj_mac.h>
28 #include <openssl/err.h>
30 ENABLE_GCC_WARNING(redundant-decls)
32 #include <errno.h>
33 #if 0
34 #include <stdlib.h>
35 #include <stdarg.h>
36 #include <assert.h>
37 #endif
39 #include "compat.h"
40 #include "util.h"
41 #include "torlog.h"
42 #include "crypto.h"
43 #include "address.h"
44 #include "util_format.h"
46 #define IDENTITY_KEY_BITS 3072
47 #define SIGNING_KEY_BITS 2048
48 #define DEFAULT_LIFETIME 12
50 /* These globals are set via command line options. */
51 static char *identity_key_file = NULL;
52 static char *signing_key_file = NULL;
53 static char *certificate_file = NULL;
54 static int reuse_signing_key = 0;
55 static int verbose = 0;
56 static int make_new_id = 0;
57 static int months_lifetime = DEFAULT_LIFETIME;
58 static int passphrase_fd = -1;
59 static char *address = NULL;
61 static char *passphrase = NULL;
62 static size_t passphrase_len = 0;
64 static EVP_PKEY *identity_key = NULL;
65 static EVP_PKEY *signing_key = NULL;
67 /** Write a usage message for tor-gencert to stderr. */
68 static void
69 show_help(void)
71 fprintf(stderr, "Syntax:\n"
72 "tor-gencert [-h|--help] [-v] [-r|--reuse] [--create-identity-key]\n"
73 " [-i identity_key_file] [-s signing_key_file] "
74 "[-c certificate_file]\n"
75 " [-m lifetime_in_months] [-a address:port] "
76 "[--passphrase-fd <fd>]\n");
79 /* XXXX copied from crypto.c */
80 static void
81 crypto_log_errors(int severity, const char *doing)
83 unsigned long err;
84 const char *msg, *lib, *func;
85 while ((err = ERR_get_error()) != 0) {
86 msg = (const char*)ERR_reason_error_string(err);
87 lib = (const char*)ERR_lib_error_string(err);
88 func = (const char*)ERR_func_error_string(err);
89 if (!msg) msg = "(null)";
90 if (!lib) lib = "(null)";
91 if (!func) func = "(null)";
92 if (doing) {
93 tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
94 doing, msg, lib, func);
95 } else {
96 tor_log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)",
97 msg, lib, func);
102 /** Read the passphrase from the passphrase fd. */
103 static int
104 load_passphrase(void)
106 char *cp;
107 char buf[1024]; /* "Ought to be enough for anybody." */
108 memset(buf, 0, sizeof(buf)); /* should be needless */
109 ssize_t n = read_all(passphrase_fd, buf, sizeof(buf), 0);
110 if (n < 0) {
111 log_err(LD_GENERAL, "Couldn't read from passphrase fd: %s",
112 strerror(errno));
113 return -1;
115 /* We'll take everything from the buffer except for optional terminating
116 * newline. */
117 cp = memchr(buf, '\n', n);
118 if (cp == NULL) {
119 passphrase_len = n;
120 } else {
121 passphrase_len = cp-buf;
123 passphrase = tor_strndup(buf, passphrase_len);
124 memwipe(buf, 0, sizeof(buf));
125 return 0;
128 static void
129 clear_passphrase(void)
131 if (passphrase) {
132 memwipe(passphrase, 0, passphrase_len);
133 tor_free(passphrase);
137 /** Read the command line options from <b>argc</b> and <b>argv</b>,
138 * setting global option vars as needed.
140 static int
141 parse_commandline(int argc, char **argv)
143 int i;
144 log_severity_list_t s;
145 for (i = 1; i < argc; ++i) {
146 if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
147 show_help();
148 return 1;
149 } else if (!strcmp(argv[i], "-i")) {
150 if (i+1>=argc) {
151 fprintf(stderr, "No argument to -i\n");
152 return 1;
154 if (identity_key_file) {
155 fprintf(stderr, "Duplicate values for -i\n");
156 return -1;
158 identity_key_file = tor_strdup(argv[++i]);
159 } else if (!strcmp(argv[i], "-s")) {
160 if (i+1>=argc) {
161 fprintf(stderr, "No argument to -s\n");
162 return 1;
164 if (signing_key_file) {
165 fprintf(stderr, "Duplicate values for -s\n");
166 return -1;
168 signing_key_file = tor_strdup(argv[++i]);
169 } else if (!strcmp(argv[i], "-c")) {
170 if (i+1>=argc) {
171 fprintf(stderr, "No argument to -c\n");
172 return 1;
174 if (certificate_file) {
175 fprintf(stderr, "Duplicate values for -c\n");
176 return -1;
178 certificate_file = tor_strdup(argv[++i]);
179 } else if (!strcmp(argv[i], "-m")) {
180 if (i+1>=argc) {
181 fprintf(stderr, "No argument to -m\n");
182 return 1;
184 months_lifetime = atoi(argv[++i]);
185 if (months_lifetime > 24 || months_lifetime < 0) {
186 fprintf(stderr, "Lifetime (in months) was out of range.\n");
187 return 1;
189 } else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--reuse")) {
190 reuse_signing_key = 1;
191 } else if (!strcmp(argv[i], "-v")) {
192 verbose = 1;
193 } else if (!strcmp(argv[i], "-a")) {
194 uint32_t addr;
195 uint16_t port;
196 char b[INET_NTOA_BUF_LEN];
197 struct in_addr in;
198 if (i+1>=argc) {
199 fprintf(stderr, "No argument to -a\n");
200 return 1;
202 if (addr_port_lookup(LOG_ERR, argv[++i], NULL, &addr, &port)<0)
203 return 1;
204 in.s_addr = htonl(addr);
205 tor_inet_ntoa(&in, b, sizeof(b));
206 tor_asprintf(&address, "%s:%d", b, (int)port);
207 } else if (!strcmp(argv[i], "--create-identity-key")) {
208 make_new_id = 1;
209 } else if (!strcmp(argv[i], "--passphrase-fd")) {
210 if (i+1>=argc) {
211 fprintf(stderr, "No argument to --passphrase-fd\n");
212 return 1;
214 passphrase_fd = atoi(argv[++i]);
215 } else {
216 fprintf(stderr, "Unrecognized option %s\n", argv[i]);
217 return 1;
221 memwipe(&s, 0, sizeof(s));
222 if (verbose)
223 set_log_severity_config(LOG_DEBUG, LOG_ERR, &s);
224 else
225 set_log_severity_config(LOG_WARN, LOG_ERR, &s);
226 add_stream_log(&s, "<stderr>", fileno(stderr));
228 if (!identity_key_file) {
229 identity_key_file = tor_strdup("./authority_identity_key");
230 log_info(LD_GENERAL, "No identity key file given; defaulting to %s",
231 identity_key_file);
233 if (!signing_key_file) {
234 signing_key_file = tor_strdup("./authority_signing_key");
235 log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
236 signing_key_file);
238 if (!certificate_file) {
239 certificate_file = tor_strdup("./authority_certificate");
240 log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
241 certificate_file);
243 if (passphrase_fd >= 0) {
244 if (load_passphrase()<0)
245 return 1;
247 return 0;
250 static RSA *
251 generate_key(int bits)
253 RSA *rsa = NULL;
254 crypto_pk_t *env = crypto_pk_new();
255 if (crypto_pk_generate_key_with_bits(env,bits)<0)
256 goto done;
257 rsa = crypto_pk_get_rsa_(env);
258 rsa = RSAPrivateKey_dup(rsa);
259 done:
260 crypto_pk_free(env);
261 return rsa;
264 /** Try to read the identity key from <b>identity_key_file</b>. If no such
265 * file exists and create_identity_key is set, make a new identity key and
266 * store it. Return 0 on success, nonzero on failure.
268 static int
269 load_identity_key(void)
271 file_status_t status = file_status(identity_key_file);
272 FILE *f;
274 if (make_new_id) {
275 open_file_t *open_file = NULL;
276 RSA *key;
277 if (status != FN_NOENT) {
278 log_err(LD_GENERAL, "--create-identity-key was specified, but %s "
279 "already exists.", identity_key_file);
280 return 1;
282 log_notice(LD_GENERAL, "Generating %d-bit RSA identity key.",
283 IDENTITY_KEY_BITS);
284 if (!(key = generate_key(IDENTITY_KEY_BITS))) {
285 log_err(LD_GENERAL, "Couldn't generate identity key.");
286 crypto_log_errors(LOG_ERR, "Generating identity key");
287 return 1;
289 identity_key = EVP_PKEY_new();
290 if (!(EVP_PKEY_assign_RSA(identity_key, key))) {
291 log_err(LD_GENERAL, "Couldn't assign identity key.");
292 return 1;
295 if (!(f = start_writing_to_stdio_file(identity_key_file,
296 OPEN_FLAGS_REPLACE | O_TEXT, 0400,
297 &open_file)))
298 return 1;
300 /* Write the key to the file. If passphrase is not set, takes it from
301 * the terminal. */
302 if (!PEM_write_PKCS8PrivateKey_nid(f, identity_key,
303 NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
304 passphrase, (int)passphrase_len,
305 NULL, NULL)) {
306 log_err(LD_GENERAL, "Couldn't write identity key to %s",
307 identity_key_file);
308 crypto_log_errors(LOG_ERR, "Writing identity key");
309 abort_writing_to_file(open_file);
310 return 1;
312 finish_writing_to_file(open_file);
313 } else {
314 if (status != FN_FILE) {
315 log_err(LD_GENERAL,
316 "No identity key found in %s. To specify a location "
317 "for an identity key, use -i. To generate a new identity key, "
318 "use --create-identity-key.", identity_key_file);
319 return 1;
322 if (!(f = fopen(identity_key_file, "r"))) {
323 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
324 identity_key_file, strerror(errno));
325 return 1;
328 /* Read the key. If passphrase is not set, takes it from the terminal. */
329 identity_key = PEM_read_PrivateKey(f, NULL, NULL, passphrase);
330 if (!identity_key) {
331 log_err(LD_GENERAL, "Couldn't read identity key from %s",
332 identity_key_file);
333 fclose(f);
334 return 1;
336 fclose(f);
338 return 0;
341 /** Load a saved signing key from disk. Return 0 on success, nonzero on
342 * failure. */
343 static int
344 load_signing_key(void)
346 FILE *f;
347 if (!(f = fopen(signing_key_file, "r"))) {
348 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
349 signing_key_file, strerror(errno));
350 return 1;
352 if (!(signing_key = PEM_read_PrivateKey(f, NULL, NULL, NULL))) {
353 log_err(LD_GENERAL, "Couldn't read siging key from %s", signing_key_file);
354 fclose(f);
355 return 1;
357 fclose(f);
358 return 0;
361 /** Generate a new signing key and write it to disk. Return 0 on success,
362 * nonzero on failure. */
363 static int
364 generate_signing_key(void)
366 open_file_t *open_file;
367 FILE *f;
368 RSA *key;
369 log_notice(LD_GENERAL, "Generating %d-bit RSA signing key.",
370 SIGNING_KEY_BITS);
371 if (!(key = generate_key(SIGNING_KEY_BITS))) {
372 log_err(LD_GENERAL, "Couldn't generate signing key.");
373 crypto_log_errors(LOG_ERR, "Generating signing key");
374 return 1;
376 signing_key = EVP_PKEY_new();
377 if (!(EVP_PKEY_assign_RSA(signing_key, key))) {
378 log_err(LD_GENERAL, "Couldn't assign signing key.");
379 return 1;
382 if (!(f = start_writing_to_stdio_file(signing_key_file,
383 OPEN_FLAGS_REPLACE | O_TEXT, 0600,
384 &open_file)))
385 return 1;
387 /* Write signing key with no encryption. */
388 if (!PEM_write_RSAPrivateKey(f, key, NULL, NULL, 0, NULL, NULL)) {
389 crypto_log_errors(LOG_WARN, "writing signing key");
390 abort_writing_to_file(open_file);
391 return 1;
394 finish_writing_to_file(open_file);
396 return 0;
399 /** Encode <b>key</b> in the format used in directory documents; return
400 * a newly allocated string holding the result or NULL on failure. */
401 static char *
402 key_to_string(EVP_PKEY *key)
404 BUF_MEM *buf;
405 BIO *b;
406 RSA *rsa = EVP_PKEY_get1_RSA(key);
407 char *result;
408 if (!rsa)
409 return NULL;
411 b = BIO_new(BIO_s_mem());
412 if (!PEM_write_bio_RSAPublicKey(b, rsa)) {
413 crypto_log_errors(LOG_WARN, "writing public key to string");
414 RSA_free(rsa);
415 return NULL;
418 BIO_get_mem_ptr(b, &buf);
419 result = tor_malloc(buf->length + 1);
420 memcpy(result, buf->data, buf->length);
421 result[buf->length] = 0;
423 BIO_free(b);
425 RSA_free(rsa);
426 return result;
429 /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
430 static int
431 get_fingerprint(EVP_PKEY *pkey, char *out)
433 int r = -1;
434 crypto_pk_t *pk = crypto_new_pk_from_rsa_(EVP_PKEY_get1_RSA(pkey));
435 if (pk) {
436 r = crypto_pk_get_fingerprint(pk, out, 0);
437 crypto_pk_free(pk);
439 return r;
442 /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
443 static int
444 get_digest(EVP_PKEY *pkey, char *out)
446 int r = -1;
447 crypto_pk_t *pk = crypto_new_pk_from_rsa_(EVP_PKEY_get1_RSA(pkey));
448 if (pk) {
449 r = crypto_pk_get_digest(pk, out);
450 crypto_pk_free(pk);
452 return r;
455 /** Generate a new certificate for our loaded or generated keys, and write it
456 * to disk. Return 0 on success, nonzero on failure. */
457 static int
458 generate_certificate(void)
460 char buf[8192];
461 time_t now = time(NULL);
462 struct tm tm;
463 char published[ISO_TIME_LEN+1];
464 char expires[ISO_TIME_LEN+1];
465 char id_digest[DIGEST_LEN];
466 char fingerprint[FINGERPRINT_LEN+1];
467 FILE *f;
468 size_t signed_len;
469 char digest[DIGEST_LEN];
470 char signature[1024]; /* handles up to 8192-bit keys. */
471 int r;
473 if (get_fingerprint(identity_key, fingerprint) < 0) {
474 return -1;
476 if (get_digest(identity_key, id_digest)) {
477 return -1;
479 char *ident = key_to_string(identity_key);
480 char *signing = key_to_string(signing_key);
482 tor_localtime_r(&now, &tm);
483 tm.tm_mon += months_lifetime;
485 format_iso_time(published, now);
486 format_iso_time(expires, mktime(&tm));
488 tor_snprintf(buf, sizeof(buf),
489 "dir-key-certificate-version 3"
490 "%s%s"
491 "\nfingerprint %s\n"
492 "dir-key-published %s\n"
493 "dir-key-expires %s\n"
494 "dir-identity-key\n%s"
495 "dir-signing-key\n%s"
496 "dir-key-crosscert\n"
497 "-----BEGIN ID SIGNATURE-----\n",
498 address?"\ndir-address ":"", address?address:"",
499 fingerprint, published, expires, ident, signing
501 tor_free(ident);
502 tor_free(signing);
504 /* Append a cross-certification */
505 RSA *rsa = EVP_PKEY_get1_RSA(signing_key);
506 r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)id_digest,
507 (unsigned char*)signature,
508 rsa,
509 RSA_PKCS1_PADDING);
510 RSA_free(rsa);
512 signed_len = strlen(buf);
513 base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r,
514 BASE64_ENCODE_MULTILINE);
516 strlcat(buf,
517 "-----END ID SIGNATURE-----\n"
518 "dir-key-certification\n", sizeof(buf));
520 signed_len = strlen(buf);
521 SHA1((const unsigned char*)buf,signed_len,(unsigned char*)digest);
523 rsa = EVP_PKEY_get1_RSA(identity_key);
524 r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)digest,
525 (unsigned char*)signature,
526 rsa,
527 RSA_PKCS1_PADDING);
528 RSA_free(rsa);
529 strlcat(buf, "-----BEGIN SIGNATURE-----\n", sizeof(buf));
530 signed_len = strlen(buf);
531 base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r,
532 BASE64_ENCODE_MULTILINE);
533 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
535 if (!(f = fopen(certificate_file, "w"))) {
536 log_err(LD_GENERAL, "Couldn't open %s for writing: %s",
537 certificate_file, strerror(errno));
538 return 1;
541 if (fputs(buf, f) < 0) {
542 log_err(LD_GENERAL, "Couldn't write to %s: %s",
543 certificate_file, strerror(errno));
544 fclose(f);
545 return 1;
547 fclose(f);
548 return 0;
551 /** Entry point to tor-gencert */
553 main(int argc, char **argv)
555 int r = 1;
556 init_logging(1);
558 /* Don't bother using acceleration. */
559 if (crypto_global_init(0, NULL, NULL)) {
560 fprintf(stderr, "Couldn't initialize crypto library.\n");
561 return 1;
563 if (crypto_seed_rng()) {
564 fprintf(stderr, "Couldn't seed RNG.\n");
565 goto done;
567 /* Make sure that files are made private. */
568 umask(0077);
570 if (parse_commandline(argc, argv))
571 goto done;
572 if (load_identity_key())
573 goto done;
574 if (reuse_signing_key) {
575 if (load_signing_key())
576 goto done;
577 } else {
578 if (generate_signing_key())
579 goto done;
581 if (generate_certificate())
582 goto done;
584 r = 0;
585 done:
586 clear_passphrase();
587 if (identity_key)
588 EVP_PKEY_free(identity_key);
589 if (signing_key)
590 EVP_PKEY_free(signing_key);
591 tor_free(address);
592 tor_free(identity_key_file);
593 tor_free(signing_key_file);
594 tor_free(certificate_file);
595 tor_free(address);
597 crypto_global_cleanup();
598 return r;