forward-port the 0.2.4.25 changelog to release-0.2.5 changelog and releasenotes
[tor.git] / src / tools / tor-gencert.c
blobe799df5cad7597d3ad305d31d9ecc75337e9b02a
1 /* Copyright (c) 2007-2013, 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 <openssl/evp.h>
17 #include <openssl/pem.h>
18 #include <openssl/rsa.h>
19 #include <openssl/objects.h>
20 #include <openssl/obj_mac.h>
21 #include <openssl/err.h>
23 #include <errno.h>
24 #if 0
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <assert.h>
28 #endif
30 #include "compat.h"
31 #include "../common/util.h"
32 #include "../common/torlog.h"
33 #include "crypto.h"
34 #include "address.h"
36 #define IDENTITY_KEY_BITS 3072
37 #define SIGNING_KEY_BITS 2048
38 #define DEFAULT_LIFETIME 12
40 /* These globals are set via command line options. */
41 char *identity_key_file = NULL;
42 char *signing_key_file = NULL;
43 char *certificate_file = NULL;
44 int reuse_signing_key = 0;
45 int verbose = 0;
46 int make_new_id = 0;
47 int months_lifetime = DEFAULT_LIFETIME;
48 int passphrase_fd = -1;
49 char *address = NULL;
51 char *passphrase = NULL;
52 size_t passphrase_len = 0;
54 EVP_PKEY *identity_key = NULL;
55 EVP_PKEY *signing_key = NULL;
57 /** Write a usage message for tor-gencert to stderr. */
58 static void
59 show_help(void)
61 fprintf(stderr, "Syntax:\n"
62 "tor-gencert [-h|--help] [-v] [-r|--reuse] [--create-identity-key]\n"
63 " [-i identity_key_file] [-s signing_key_file] "
64 "[-c certificate_file]\n"
65 " [-m lifetime_in_months] [-a address:port] "
66 "[--passphrase-fd <fd>]\n");
69 /* XXXX copied from crypto.c */
70 static void
71 crypto_log_errors(int severity, const char *doing)
73 unsigned long err;
74 const char *msg, *lib, *func;
75 while ((err = ERR_get_error()) != 0) {
76 msg = (const char*)ERR_reason_error_string(err);
77 lib = (const char*)ERR_lib_error_string(err);
78 func = (const char*)ERR_func_error_string(err);
79 if (!msg) msg = "(null)";
80 if (!lib) lib = "(null)";
81 if (!func) func = "(null)";
82 if (doing) {
83 tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
84 doing, msg, lib, func);
85 } else {
86 tor_log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)",
87 msg, lib, func);
92 /** Read the passphrase from the passphrase fd. */
93 static int
94 load_passphrase(void)
96 char *cp;
97 char buf[1024]; /* "Ought to be enough for anybody." */
98 ssize_t n = read_all(passphrase_fd, buf, sizeof(buf), 0);
99 if (n < 0) {
100 log_err(LD_GENERAL, "Couldn't read from passphrase fd: %s",
101 strerror(errno));
102 return -1;
104 cp = memchr(buf, '\n', n);
105 passphrase_len = cp-buf;
106 passphrase = tor_strndup(buf, passphrase_len);
107 memwipe(buf, 0, sizeof(buf));
108 return 0;
111 static void
112 clear_passphrase(void)
114 if (passphrase) {
115 memwipe(passphrase, 0, passphrase_len);
116 tor_free(passphrase);
120 /** Read the command line options from <b>argc</b> and <b>argv</b>,
121 * setting global option vars as needed.
123 static int
124 parse_commandline(int argc, char **argv)
126 int i;
127 log_severity_list_t s;
128 for (i = 1; i < argc; ++i) {
129 if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
130 show_help();
131 return 1;
132 } else if (!strcmp(argv[i], "-i")) {
133 if (i+1>=argc) {
134 fprintf(stderr, "No argument to -i\n");
135 return 1;
137 identity_key_file = tor_strdup(argv[++i]);
138 } else if (!strcmp(argv[i], "-s")) {
139 if (i+1>=argc) {
140 fprintf(stderr, "No argument to -s\n");
141 return 1;
143 signing_key_file = tor_strdup(argv[++i]);
144 } else if (!strcmp(argv[i], "-c")) {
145 if (i+1>=argc) {
146 fprintf(stderr, "No argument to -c\n");
147 return 1;
149 certificate_file = tor_strdup(argv[++i]);
150 } else if (!strcmp(argv[i], "-m")) {
151 if (i+1>=argc) {
152 fprintf(stderr, "No argument to -m\n");
153 return 1;
155 months_lifetime = atoi(argv[++i]);
156 if (months_lifetime > 24 || months_lifetime < 0) {
157 fprintf(stderr, "Lifetime (in months) was out of range.\n");
158 return 1;
160 } else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--reuse")) {
161 reuse_signing_key = 1;
162 } else if (!strcmp(argv[i], "-v")) {
163 verbose = 1;
164 } else if (!strcmp(argv[i], "-a")) {
165 uint32_t addr;
166 uint16_t port;
167 char b[INET_NTOA_BUF_LEN];
168 struct in_addr in;
169 if (i+1>=argc) {
170 fprintf(stderr, "No argument to -a\n");
171 return 1;
173 if (addr_port_lookup(LOG_ERR, argv[++i], NULL, &addr, &port)<0)
174 return 1;
175 in.s_addr = htonl(addr);
176 tor_inet_ntoa(&in, b, sizeof(b));
177 address = tor_malloc(INET_NTOA_BUF_LEN+32);
178 tor_snprintf(address, INET_NTOA_BUF_LEN+32, "%s:%d", b, (int)port);
179 } else if (!strcmp(argv[i], "--create-identity-key")) {
180 make_new_id = 1;
181 } else if (!strcmp(argv[i], "--passphrase-fd")) {
182 if (i+1>=argc) {
183 fprintf(stderr, "No argument to --passphrase-fd\n");
184 return 1;
186 passphrase_fd = atoi(argv[++i]);
187 } else {
188 fprintf(stderr, "Unrecognized option %s\n", argv[i]);
189 return 1;
193 memwipe(&s, 0, sizeof(s));
194 if (verbose)
195 set_log_severity_config(LOG_DEBUG, LOG_ERR, &s);
196 else
197 set_log_severity_config(LOG_WARN, LOG_ERR, &s);
198 add_stream_log(&s, "<stderr>", fileno(stderr));
200 if (!identity_key_file) {
201 identity_key_file = tor_strdup("./authority_identity_key");
202 log_info(LD_GENERAL, "No identity key file given; defaulting to %s",
203 identity_key_file);
205 if (!signing_key_file) {
206 signing_key_file = tor_strdup("./authority_signing_key");
207 log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
208 signing_key_file);
210 if (!certificate_file) {
211 certificate_file = tor_strdup("./authority_certificate");
212 log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
213 certificate_file);
215 if (passphrase_fd >= 0) {
216 if (load_passphrase()<0)
217 return 1;
219 return 0;
222 static RSA *
223 generate_key(int bits)
225 RSA *rsa = NULL;
226 crypto_pk_t *env = crypto_pk_new();
227 if (crypto_pk_generate_key_with_bits(env,bits)<0)
228 goto done;
229 rsa = crypto_pk_get_rsa_(env);
230 rsa = RSAPrivateKey_dup(rsa);
231 done:
232 crypto_pk_free(env);
233 return rsa;
236 /** Try to read the identity key from <b>identity_key_file</b>. If no such
237 * file exists and create_identity_key is set, make a new identity key and
238 * store it. Return 0 on success, nonzero on failure.
240 static int
241 load_identity_key(void)
243 file_status_t status = file_status(identity_key_file);
244 FILE *f;
246 if (make_new_id) {
247 open_file_t *open_file = NULL;
248 RSA *key;
249 if (status != FN_NOENT) {
250 log_err(LD_GENERAL, "--create-identity-key was specified, but %s "
251 "already exists.", identity_key_file);
252 return 1;
254 log_notice(LD_GENERAL, "Generating %d-bit RSA identity key.",
255 IDENTITY_KEY_BITS);
256 if (!(key = generate_key(IDENTITY_KEY_BITS))) {
257 log_err(LD_GENERAL, "Couldn't generate identity key.");
258 crypto_log_errors(LOG_ERR, "Generating identity key");
259 return 1;
261 identity_key = EVP_PKEY_new();
262 if (!(EVP_PKEY_assign_RSA(identity_key, key))) {
263 log_err(LD_GENERAL, "Couldn't assign identity key.");
264 return 1;
267 if (!(f = start_writing_to_stdio_file(identity_key_file,
268 OPEN_FLAGS_REPLACE | O_TEXT, 0400,
269 &open_file)))
270 return 1;
272 /* Write the key to the file. If passphrase is not set, takes it from
273 * the terminal. */
274 if (!PEM_write_PKCS8PrivateKey_nid(f, identity_key,
275 NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
276 passphrase, (int)passphrase_len,
277 NULL, NULL)) {
278 log_err(LD_GENERAL, "Couldn't write identity key to %s",
279 identity_key_file);
280 crypto_log_errors(LOG_ERR, "Writing identity key");
281 abort_writing_to_file(open_file);
282 return 1;
284 finish_writing_to_file(open_file);
285 } else {
286 if (status != FN_FILE) {
287 log_err(LD_GENERAL,
288 "No identity key found in %s. To specify a location "
289 "for an identity key, use -i. To generate a new identity key, "
290 "use --create-identity-key.", identity_key_file);
291 return 1;
294 if (!(f = fopen(identity_key_file, "r"))) {
295 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
296 identity_key_file, strerror(errno));
297 return 1;
300 /* Read the key. If passphrase is not set, takes it from the terminal. */
301 identity_key = PEM_read_PrivateKey(f, NULL, NULL, passphrase);
302 if (!identity_key) {
303 log_err(LD_GENERAL, "Couldn't read identity key from %s",
304 identity_key_file);
305 fclose(f);
306 return 1;
308 fclose(f);
310 return 0;
313 /** Load a saved signing key from disk. Return 0 on success, nonzero on
314 * failure. */
315 static int
316 load_signing_key(void)
318 FILE *f;
319 if (!(f = fopen(signing_key_file, "r"))) {
320 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
321 signing_key_file, strerror(errno));
322 return 1;
324 if (!(signing_key = PEM_read_PrivateKey(f, NULL, NULL, NULL))) {
325 log_err(LD_GENERAL, "Couldn't read siging key from %s", signing_key_file);
326 fclose(f);
327 return 1;
329 fclose(f);
330 return 0;
333 /** Generate a new signing key and write it to disk. Return 0 on success,
334 * nonzero on failure. */
335 static int
336 generate_signing_key(void)
338 open_file_t *open_file;
339 FILE *f;
340 RSA *key;
341 log_notice(LD_GENERAL, "Generating %d-bit RSA signing key.",
342 SIGNING_KEY_BITS);
343 if (!(key = generate_key(SIGNING_KEY_BITS))) {
344 log_err(LD_GENERAL, "Couldn't generate signing key.");
345 crypto_log_errors(LOG_ERR, "Generating signing key");
346 return 1;
348 signing_key = EVP_PKEY_new();
349 if (!(EVP_PKEY_assign_RSA(signing_key, key))) {
350 log_err(LD_GENERAL, "Couldn't assign signing key.");
351 return 1;
354 if (!(f = start_writing_to_stdio_file(signing_key_file,
355 OPEN_FLAGS_REPLACE | O_TEXT, 0600,
356 &open_file)))
357 return 1;
359 /* Write signing key with no encryption. */
360 if (!PEM_write_RSAPrivateKey(f, key, NULL, NULL, 0, NULL, NULL)) {
361 crypto_log_errors(LOG_WARN, "writing signing key");
362 abort_writing_to_file(open_file);
363 return 1;
366 finish_writing_to_file(open_file);
368 return 0;
371 /** Encode <b>key</b> in the format used in directory documents; return
372 * a newly allocated string holding the result or NULL on failure. */
373 static char *
374 key_to_string(EVP_PKEY *key)
376 BUF_MEM *buf;
377 BIO *b;
378 RSA *rsa = EVP_PKEY_get1_RSA(key);
379 char *result;
380 if (!rsa)
381 return NULL;
383 b = BIO_new(BIO_s_mem());
384 if (!PEM_write_bio_RSAPublicKey(b, rsa)) {
385 crypto_log_errors(LOG_WARN, "writing public key to string");
386 return NULL;
389 BIO_get_mem_ptr(b, &buf);
390 (void) BIO_set_close(b, BIO_NOCLOSE);
391 BIO_free(b);
392 result = tor_malloc(buf->length + 1);
393 memcpy(result, buf->data, buf->length);
394 result[buf->length] = 0;
395 BUF_MEM_free(buf);
397 return result;
400 /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
401 static int
402 get_fingerprint(EVP_PKEY *pkey, char *out)
404 int r = 1;
405 crypto_pk_t *pk = crypto_new_pk_from_rsa_(EVP_PKEY_get1_RSA(pkey));
406 if (pk) {
407 r = crypto_pk_get_fingerprint(pk, out, 0);
408 crypto_pk_free(pk);
410 return r;
413 /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
414 static int
415 get_digest(EVP_PKEY *pkey, char *out)
417 int r = 1;
418 crypto_pk_t *pk = crypto_new_pk_from_rsa_(EVP_PKEY_get1_RSA(pkey));
419 if (pk) {
420 r = crypto_pk_get_digest(pk, out);
421 crypto_pk_free(pk);
423 return r;
426 /** Generate a new certificate for our loaded or generated keys, and write it
427 * to disk. Return 0 on success, nonzero on failure. */
428 static int
429 generate_certificate(void)
431 char buf[8192];
432 time_t now = time(NULL);
433 struct tm tm;
434 char published[ISO_TIME_LEN+1];
435 char expires[ISO_TIME_LEN+1];
436 char id_digest[DIGEST_LEN];
437 char fingerprint[FINGERPRINT_LEN+1];
438 char *ident = key_to_string(identity_key);
439 char *signing = key_to_string(signing_key);
440 FILE *f;
441 size_t signed_len;
442 char digest[DIGEST_LEN];
443 char signature[1024]; /* handles up to 8192-bit keys. */
444 int r;
446 get_fingerprint(identity_key, fingerprint);
447 get_digest(identity_key, id_digest);
449 tor_localtime_r(&now, &tm);
450 tm.tm_mon += months_lifetime;
452 format_iso_time(published, now);
453 format_iso_time(expires, mktime(&tm));
455 tor_snprintf(buf, sizeof(buf),
456 "dir-key-certificate-version 3"
457 "%s%s"
458 "\nfingerprint %s\n"
459 "dir-key-published %s\n"
460 "dir-key-expires %s\n"
461 "dir-identity-key\n%s"
462 "dir-signing-key\n%s"
463 "dir-key-crosscert\n"
464 "-----BEGIN ID SIGNATURE-----\n",
465 address?"\ndir-address ":"", address?address:"",
466 fingerprint, published, expires, ident, signing
468 tor_free(ident);
469 tor_free(signing);
471 /* Append a cross-certification */
472 r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)id_digest,
473 (unsigned char*)signature,
474 EVP_PKEY_get1_RSA(signing_key),
475 RSA_PKCS1_PADDING);
476 signed_len = strlen(buf);
477 base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
479 strlcat(buf,
480 "-----END ID SIGNATURE-----\n"
481 "dir-key-certification\n", sizeof(buf));
483 signed_len = strlen(buf);
484 SHA1((const unsigned char*)buf,signed_len,(unsigned char*)digest);
486 r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)digest,
487 (unsigned char*)signature,
488 EVP_PKEY_get1_RSA(identity_key),
489 RSA_PKCS1_PADDING);
490 strlcat(buf, "-----BEGIN SIGNATURE-----\n", sizeof(buf));
491 signed_len = strlen(buf);
492 base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
493 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
495 if (!(f = fopen(certificate_file, "w"))) {
496 log_err(LD_GENERAL, "Couldn't open %s for writing: %s",
497 certificate_file, strerror(errno));
498 return 1;
501 if (fputs(buf, f) < 0) {
502 log_err(LD_GENERAL, "Couldn't write to %s: %s",
503 certificate_file, strerror(errno));
504 fclose(f);
505 return 1;
507 fclose(f);
508 return 0;
511 /** Entry point to tor-gencert */
513 main(int argc, char **argv)
515 int r = 1;
516 init_logging();
518 /* Don't bother using acceleration. */
519 if (crypto_global_init(0, NULL, NULL)) {
520 fprintf(stderr, "Couldn't initialize crypto library.\n");
521 return 1;
523 if (crypto_seed_rng(1)) {
524 fprintf(stderr, "Couldn't seed RNG.\n");
525 goto done;
527 /* Make sure that files are made private. */
528 umask(0077);
530 if (parse_commandline(argc, argv))
531 goto done;
532 if (load_identity_key())
533 goto done;
534 if (reuse_signing_key) {
535 if (load_signing_key())
536 goto done;
537 } else {
538 if (generate_signing_key())
539 goto done;
541 if (generate_certificate())
542 goto done;
544 r = 0;
545 done:
546 clear_passphrase();
547 if (identity_key)
548 EVP_PKEY_free(identity_key);
549 if (signing_key)
550 EVP_PKEY_free(signing_key);
551 tor_free(address);
552 tor_free(identity_key_file);
553 tor_free(signing_key_file);
554 tor_free(certificate_file);
556 crypto_global_cleanup();
557 return r;