r17358@pc-10-8-1-079: nickm | 2008-07-25 16:41:03 +0200
[tor.git] / src / tools / tor-gencert.c
blobaccaa5ea0dad411b38ba6667e404d2a3c0723780
1 /* Copyright (c) 2007-2008 The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
3 /* $Id: /tor/trunk/src/tools/tor-resolve.c 12481 2007-04-21T17:27:19.371353Z nickm $ */
5 #include "orconfig.h"
7 #include <stdio.h>
8 #include <string.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <fcntl.h>
13 #include <unistd.h>
15 #include <openssl/evp.h>
16 #include <openssl/pem.h>
17 #include <openssl/objects.h>
18 #include <openssl/obj_mac.h>
19 #include <openssl/err.h>
21 #include <errno.h>
22 #if 0
23 #include <stdlib.h>
24 #include <stdarg.h>
25 #include <assert.h>
26 #endif
28 #define CRYPTO_PRIVATE
30 #include "compat.h"
31 #include "util.h"
32 #include "log.h"
33 #include "crypto.h"
34 #include "address.h"
36 #define IDENTITY_KEY_BITS 3072
37 #define SIGNING_KEY_BITS 1024
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");
70 /* XXXX copied from crypto.c */
71 static void
72 crypto_log_errors(int severity, const char *doing)
74 unsigned int err;
75 const char *msg, *lib, *func;
76 while ((err = ERR_get_error()) != 0) {
77 msg = (const char*)ERR_reason_error_string(err);
78 lib = (const char*)ERR_lib_error_string(err);
79 func = (const char*)ERR_func_error_string(err);
80 if (!msg) msg = "(null)";
81 if (!lib) lib = "(null)";
82 if (!func) func = "(null)";
83 if (doing) {
84 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
85 doing, msg, lib, func);
86 } else {
87 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", 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 int 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 memset(buf, 0, sizeof(buf));
108 return 0;
111 static void
112 clear_passphrase(void)
114 if (passphrase) {
115 memset(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.");
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 (parse_addr_port(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 s = tor_malloc_zero(sizeof(log_severity_list_t));
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>", 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 /** Try to read the identity key from <b>identity_key_file</b>. If no such
223 * file exists and create_identity_key is set, make a new identity key and
224 * store it. Return 0 on success, nonzero on failure.
226 static int
227 load_identity_key(void)
229 file_status_t status = file_status(identity_key_file);
230 FILE *f;
232 if (make_new_id) {
233 open_file_t *open_file = NULL;
234 RSA *key;
235 if (status != FN_NOENT) {
236 log_err(LD_GENERAL, "--create-identity-key was specified, but %s "
237 "already exists.", identity_key_file);
238 return 1;
240 log_notice(LD_GENERAL, "Generating %d-bit RSA identity key.",
241 IDENTITY_KEY_BITS);
242 if (!(key = RSA_generate_key(IDENTITY_KEY_BITS, 65537, NULL, NULL))) {
243 log_err(LD_GENERAL, "Couldn't generate identity key.");
244 crypto_log_errors(LOG_ERR, "Generating identity key");
245 return 1;
247 identity_key = EVP_PKEY_new();
248 if (!(EVP_PKEY_assign_RSA(identity_key, key))) {
249 log_err(LD_GENERAL, "Couldn't assign identity key.");
250 return 1;
253 if (!(f = start_writing_to_stdio_file(identity_key_file,
254 OPEN_FLAGS_REPLACE, 0400,
255 &open_file)))
256 return 1;
258 /* Write the key to the file. If passphrase is not set, takes it from
259 * the terminal. */
260 if (!PEM_write_PKCS8PrivateKey_nid(f, identity_key,
261 NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
262 passphrase, (int)passphrase_len,
263 NULL, NULL)) {
264 log_err(LD_GENERAL, "Couldn't write identity key to %s",
265 identity_key_file);
266 crypto_log_errors(LOG_ERR, "Writing identity key");
267 abort_writing_to_file(open_file);
268 return 1;
270 finish_writing_to_file(open_file);
271 } else {
272 if (status != FN_FILE) {
273 log_err(LD_GENERAL,
274 "No identity key found in %s. To specify a location "
275 "for an identity key, use -i. To generate a new identity key, "
276 "use --create-identity-key.", identity_key_file);
277 return 1;
280 if (!(f = fopen(identity_key_file, "r"))) {
281 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
282 identity_key_file, strerror(errno));
283 return 1;
286 /* Read the key. If passphrase is not set, takes it from the terminal. */
287 identity_key = PEM_read_PrivateKey(f, NULL, NULL, passphrase);
288 if (!identity_key) {
289 log_err(LD_GENERAL, "Couldn't read identity key from %s",
290 identity_key_file);
291 return 1;
293 fclose(f);
295 return 0;
298 /** Load a saved signing key from disk. Return 0 on success, nonzero on
299 * failure. */
300 static int
301 load_signing_key(void)
303 FILE *f;
304 if (!(f = fopen(signing_key_file, "r"))) {
305 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
306 signing_key_file, strerror(errno));
307 return 1;
309 if (!(signing_key = PEM_read_PrivateKey(f, NULL, NULL, NULL))) {
310 log_err(LD_GENERAL, "Couldn't read siging key from %s", signing_key_file);
311 return 1;
313 fclose(f);
314 return 0;
317 /** Generate a new signing key and write it to disk. Return 0 on success,
318 * nonzero on failure. */
319 static int
320 generate_signing_key(void)
322 open_file_t *open_file;
323 FILE *f;
324 RSA *key;
325 log_notice(LD_GENERAL, "Generating %d-bit RSA signing key.",
326 SIGNING_KEY_BITS);
327 if (!(key = RSA_generate_key(SIGNING_KEY_BITS, 65537, NULL, NULL))) {
328 log_err(LD_GENERAL, "Couldn't generate signing key.");
329 crypto_log_errors(LOG_ERR, "Generating signing key");
330 return 1;
332 signing_key = EVP_PKEY_new();
333 if (!(EVP_PKEY_assign_RSA(signing_key, key))) {
334 log_err(LD_GENERAL, "Couldn't assign signing key.");
335 return 1;
338 if (!(f = start_writing_to_stdio_file(signing_key_file,
339 OPEN_FLAGS_REPLACE, 0600,
340 &open_file)))
341 return 1;
343 /* Write signing key with no encryption. */
344 if (!PEM_write_RSAPrivateKey(f, key, NULL, NULL, 0, NULL, NULL)) {
345 crypto_log_errors(LOG_WARN, "writing signing key");
346 abort_writing_to_file(open_file);
347 return 1;
350 finish_writing_to_file(open_file);
352 return 0;
355 /** Encode <b>key</b> in the format used in directory documents; return
356 * a newly allocated string holding the result or NULL on failure. */
357 static char *
358 key_to_string(EVP_PKEY *key)
360 BUF_MEM *buf;
361 BIO *b;
362 RSA *rsa = EVP_PKEY_get1_RSA(key);
363 char *result;
364 if (!rsa)
365 return NULL;
367 b = BIO_new(BIO_s_mem());
368 if (!PEM_write_bio_RSAPublicKey(b, rsa)) {
369 crypto_log_errors(LOG_WARN, "writing public key to string");
370 return NULL;
373 BIO_get_mem_ptr(b, &buf);
374 (void) BIO_set_close(b, BIO_NOCLOSE);
375 BIO_free(b);
376 result = tor_malloc(buf->length + 1);
377 memcpy(result, buf->data, buf->length);
378 result[buf->length] = 0;
379 BUF_MEM_free(buf);
381 return result;
384 /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
385 static int
386 get_fingerprint(EVP_PKEY *pkey, char *out)
388 int r = 1;
389 crypto_pk_env_t *pk = _crypto_new_pk_env_rsa(EVP_PKEY_get1_RSA(pkey));
390 if (pk) {
391 r = crypto_pk_get_fingerprint(pk, out, 0);
392 crypto_free_pk_env(pk);
394 return r;
397 /** Generate a new certificate for our loaded or generated keys, and write it
398 * to disk. Return 0 on success, nonzero on failure. */
399 static int
400 generate_certificate(void)
402 char buf[8192];
403 time_t now = time(NULL);
404 struct tm tm;
405 char published[ISO_TIME_LEN+1];
406 char expires[ISO_TIME_LEN+1];
407 char fingerprint[FINGERPRINT_LEN+1];
408 char *ident = key_to_string(identity_key);
409 char *signing = key_to_string(signing_key);
410 FILE *f;
411 size_t signed_len;
412 char digest[DIGEST_LEN];
413 char signature[1024]; /* handles up to 8192-bit keys. */
414 int r;
416 get_fingerprint(identity_key, fingerprint);
418 tor_localtime_r(&now, &tm);
419 tm.tm_mon += months_lifetime;
421 format_iso_time(published, now);
422 format_iso_time(expires, mktime(&tm));
424 tor_snprintf(buf, sizeof(buf),
425 "dir-key-certificate-version 3"
426 "%s%s"
427 "\nfingerprint %s\n"
428 "dir-key-published %s\n"
429 "dir-key-expires %s\n"
430 "dir-identity-key\n%s"
431 "dir-signing-key\n%s"
432 "dir-key-certification\n",
433 address?"\ndir-address ":"", address?address:"",
434 fingerprint, published, expires, ident, signing);
435 tor_free(ident);
436 tor_free(signing);
437 signed_len = strlen(buf);
438 SHA1((const unsigned char*)buf,signed_len,(unsigned char*)digest);
440 r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)digest,
441 (unsigned char*)signature,
442 EVP_PKEY_get1_RSA(identity_key),
443 RSA_PKCS1_PADDING);
444 strlcat(buf, "-----BEGIN SIGNATURE-----\n", sizeof(buf));
445 signed_len = strlen(buf);
446 base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
447 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
449 if (!(f = fopen(certificate_file, "w"))) {
450 log_err(LD_GENERAL, "Couldn't open %s for writing: %s",
451 certificate_file, strerror(errno));
452 return 1;
455 fputs(buf, f);
456 fclose(f);
457 return 0;
461 /** Entry point to tor-gencert */
463 main(int argc, char **argv)
465 int r = 1;
466 init_logging();
468 /* Don't bother using acceleration. */
469 if (crypto_global_init(0)) {
470 fprintf(stderr, "Couldn't initialize crypto library.\n");
471 return 1;
473 if (crypto_seed_rng(1)) {
474 fprintf(stderr, "Couldn't seed RNG.\n");
475 goto done;
477 /* Make sure that files are made private. */
478 umask(0077);
480 if (parse_commandline(argc, argv))
481 goto done;
482 if (load_identity_key())
483 goto done;
484 if (reuse_signing_key) {
485 if (load_signing_key())
486 goto done;
487 } else {
488 if (generate_signing_key())
489 goto done;
491 if (generate_certificate())
492 goto done;
494 r = 0;
495 done:
496 clear_passphrase();
497 if (identity_key)
498 EVP_PKEY_free(identity_key);
499 if (signing_key)
500 EVP_PKEY_free(signing_key);
501 tor_free(address);
503 crypto_global_cleanup();
504 return r;