Hm; looks like the callback business was unnecessary, since DHparams_dup() copies...
[tor.git] / src / common / tortls.c
blob27a54e14d108c81f7c2868a021035c599d93fb5c
1 /* Copyright 2003 Roger Dingledine.
2 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
3 /* See LICENSE for licensing information */
4 /* $Id$ */
5 const char tortls_c_id[] = "$Id$";
7 /**
8 * \file tortls.c
9 * \brief Wrapper functions to present a consistent interface to
10 * TLS, SSL, and X.509 functions from OpenSSL.
11 **/
13 /* (Unlike other tor functions, these
14 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
15 * functions and variables.)
18 #include "orconfig.h"
19 #include "./crypto.h"
20 #include "./tortls.h"
21 #include "./util.h"
22 #include "./log.h"
23 #include <string.h>
25 /* Copied from or.h */
26 #define LEGAL_NICKNAME_CHARACTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
28 #include <assert.h>
29 #include <openssl/ssl.h>
30 #include <openssl/err.h>
31 #include <openssl/tls1.h>
32 #include <openssl/asn1.h>
33 #include <openssl/bio.h>
35 /** How long do identity certificates live? (sec) */
36 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
38 /* DOCDOC */
39 typedef struct tor_tls_context_t {
40 SSL_CTX *ctx;
41 SSL_CTX *client_only_ctx;
42 } tor_tls_context_t;
44 /** Holds a SSL object and its associated data. Members are only
45 * accessed from within tortls.c.
47 struct tor_tls_t {
48 SSL *ssl; /**< An OpenSSL SSL object. */
49 int socket; /**< The underlying file descriptor for this TLS connection. */
50 enum {
51 TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
52 TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED
53 } state; /**< The current SSL state, depending on which operations have
54 * completed successfully. */
55 int isServer;
56 size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last time. */
59 static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
60 crypto_pk_env_t *rsa_sign,
61 const char *cname,
62 const char *cname_sign,
63 unsigned int lifetime);
65 /** Global tls context. We keep it here because nobody else needs to
66 * touch it. */
67 static tor_tls_context_t *global_tls_context = NULL;
68 /** True iff tor_tls_init() has been called. */
69 static int tls_library_is_initialized = 0;
71 /* Module-internal error codes. */
72 #define _TOR_TLS_SYSCALL -6
73 #define _TOR_TLS_ZERORETURN -5
75 /* These functions are declared in crypto.c but not exported. */
76 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
77 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
78 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
80 /** Log all pending tls errors at level <b>severity</b>. Use
81 * <b>doing</b> to describe our current activities.
83 static void
84 tls_log_errors(int severity, const char *doing)
86 int err;
87 const char *msg, *lib, *func;
88 while ((err = ERR_get_error()) != 0) {
89 msg = (const char*)ERR_reason_error_string(err);
90 lib = (const char*)ERR_lib_error_string(err);
91 func = (const char*)ERR_func_error_string(err);
92 if (!msg) msg = "(null)";
93 if (doing) {
94 log(severity, LD_NET, "TLS error while %s: %s (in %s:%s)", doing, msg, lib,func);
95 } else {
96 log(severity, LD_NET, "TLS error: %s (in %s:%s)", msg, lib, func);
101 #define CATCH_SYSCALL 1
102 #define CATCH_ZERO 2
104 /** Given a TLS object and the result of an SSL_* call, use
105 * SSL_get_error to determine whether an error has occurred, and if so
106 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
107 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
108 * reporting syscall errors. If extra&CATCH_ZERO is true, return
109 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
111 * If an error has occurred, log it at level <b>severity</b> and describe the
112 * current action as <b>doing</b>.
114 static int
115 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
116 const char *doing, int severity)
118 int err = SSL_get_error(tls->ssl, r);
119 switch (err) {
120 case SSL_ERROR_NONE:
121 return TOR_TLS_DONE;
122 case SSL_ERROR_WANT_READ:
123 return TOR_TLS_WANTREAD;
124 case SSL_ERROR_WANT_WRITE:
125 return TOR_TLS_WANTWRITE;
126 case SSL_ERROR_SYSCALL:
127 if (extra&CATCH_SYSCALL)
128 return _TOR_TLS_SYSCALL;
129 if (r == 0)
130 log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
131 else {
132 int e = tor_socket_errno(tls->socket);
133 log(severity, LD_NET, "TLS error: <syscall error while %s> (errno=%d: %s)",
134 doing, e, tor_socket_strerror(e));
136 tls_log_errors(severity, doing);
137 return TOR_TLS_ERROR;
138 case SSL_ERROR_ZERO_RETURN:
139 if (extra&CATCH_ZERO)
140 return _TOR_TLS_ZERORETURN;
141 log(severity, LD_NET, "TLS error: Zero return");
142 tls_log_errors(severity, doing);
143 return TOR_TLS_ERROR;
144 default:
145 tls_log_errors(severity, doing);
146 return TOR_TLS_ERROR;
150 /** Initialize OpenSSL, unless it has already been initialized.
152 static void
153 tor_tls_init(void)
155 if (!tls_library_is_initialized) {
156 SSL_library_init();
157 SSL_load_error_strings();
158 crypto_global_init(-1);
159 tls_library_is_initialized = 1;
163 void
164 tor_tls_free_all(void)
166 if (global_tls_context) {
167 SSL_CTX_free(global_tls_context->ctx);
168 SSL_CTX_free(global_tls_context->client_only_ctx);
169 tor_free(global_tls_context);
170 global_tls_context = NULL;
174 /** We need to give OpenSSL a callback to verify certificates. This is
175 * it: We always accept peer certs and complete the handshake. We
176 * don't validate them until later.
178 static int
179 always_accept_verify_cb(int preverify_ok,
180 X509_STORE_CTX *x509_ctx)
182 /* avoid "unused parameter" warning. */
183 preverify_ok = 0;
184 x509_ctx = NULL;
185 return 1;
188 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
189 * signed by the private key <b>rsa_sign</b>. The commonName of the
190 * certificate will be <b>cname</b>; the commonName of the issuer will be
191 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
192 * starting from now. Return a certificate on success, NULL on
193 * failure.
195 static X509 *
196 tor_tls_create_certificate(crypto_pk_env_t *rsa,
197 crypto_pk_env_t *rsa_sign,
198 const char *cname,
199 const char *cname_sign,
200 unsigned int cert_lifetime)
202 time_t start_time, end_time;
203 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
204 X509 *x509 = NULL;
205 X509_NAME *name = NULL, *name_issuer=NULL;
206 int nid;
208 tor_tls_init();
210 start_time = time(NULL);
212 tor_assert(rsa);
213 tor_assert(cname);
214 tor_assert(rsa_sign);
215 tor_assert(cname_sign);
216 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
217 goto error;
218 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
219 goto error;
220 if (!(x509 = X509_new()))
221 goto error;
222 if (!(X509_set_version(x509, 2)))
223 goto error;
224 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
225 goto error;
227 if (!(name = X509_NAME_new()))
228 goto error;
229 if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
230 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
231 (unsigned char*)"TOR", -1, -1, 0))) goto error;
232 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
233 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
234 (unsigned char*)cname, -1, -1, 0))) goto error;
235 if (!(X509_set_subject_name(x509, name)))
236 goto error;
238 if (!(name_issuer = X509_NAME_new()))
239 goto error;
240 if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
241 if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
242 (unsigned char*)"TOR", -1, -1, 0))) goto error;
243 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
244 if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
245 (unsigned char*)cname_sign, -1, -1, 0))) goto error;
246 if (!(X509_set_issuer_name(x509, name_issuer)))
247 goto error;
249 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
250 goto error;
251 end_time = start_time + cert_lifetime;
252 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
253 goto error;
254 if (!X509_set_pubkey(x509, pkey))
255 goto error;
256 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
257 goto error;
259 goto done;
260 error:
261 if (x509) {
262 X509_free(x509);
263 x509 = NULL;
265 done:
266 tls_log_errors(LOG_WARN, "generating certificate");
267 if (sign_pkey)
268 EVP_PKEY_free(sign_pkey);
269 if (pkey)
270 EVP_PKEY_free(pkey);
271 if (name)
272 X509_NAME_free(name);
273 if (name_issuer)
274 X509_NAME_free(name_issuer);
275 return x509;
278 #ifdef EVERYONE_HAS_AES
279 /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
280 * is needed. */
281 #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
282 #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
283 /* Some people are running OpenSSL before 0.9.7, but we aren't.
284 * We can support AES and 3DES.
286 #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
287 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
288 #else
289 /* We're running OpenSSL before 0.9.7. We only support 3DES. */
290 #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
291 #endif
293 /** Create a new TLS context. If we are going to be using it as a
294 * server, it must have isServer set to true, <b>identity</b> set to the
295 * identity key used to sign that certificate, and <b>nickname</b> set to
296 * the server's nickname. If we're only going to be a client,
297 * isServer should be false, identity should be NULL, and nickname
298 * should be NULL. Return -1 if failure, else 0.
300 * You can call this function multiple times. Each time you call it,
301 * it generates new certificates; all new connections will use
302 * the new SSL context.
305 tor_tls_context_new(crypto_pk_env_t *identity,
306 int isServer, const char *nickname,
307 unsigned int key_lifetime)
309 crypto_pk_env_t *rsa = NULL;
310 crypto_dh_env_t *dh = NULL;
311 EVP_PKEY *pkey = NULL;
312 tor_tls_context_t *result = NULL;
313 X509 *cert = NULL, *idcert = NULL;
314 char nn2[128];
315 int client_only;
316 SSL_CTX **ctx;
317 if (!nickname)
318 nickname = "null";
319 tor_snprintf(nn2, sizeof(nn2), "%s <identity>", nickname);
321 tor_tls_init();
323 if (isServer) {
324 /* Generate short-term RSA key. */
325 if (!(rsa = crypto_new_pk_env()))
326 goto error;
327 if (crypto_pk_generate_key(rsa)<0)
328 goto error;
329 /* Create certificate signed by identity key. */
330 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
331 key_lifetime);
332 /* Create self-signed certificate for identity key. */
333 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
334 IDENTITY_CERT_LIFETIME);
335 if (!cert || !idcert) {
336 log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
337 goto error;
341 result = tor_malloc(sizeof(tor_tls_context_t));
342 result->ctx = result->client_only_ctx = NULL;
343 for (client_only=0; client_only <= 1; ++client_only) {
344 ctx = client_only ? &result->client_only_ctx : &result->ctx;
345 #ifdef EVERYONE_HAS_AES
346 /* Tell OpenSSL to only use TLS1 */
347 if (!(*ctx = SSL_CTX_new(TLSv1_method())))
348 goto error;
349 #else
350 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
351 if (!(*ctx = SSL_CTX_new(SSLv23_method())))
352 goto error;
353 SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
354 #endif
355 SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_DH_USE);
356 if (!SSL_CTX_set_cipher_list(*ctx, CIPHER_LIST))
357 goto error;
358 if (!client_only) {
359 if (cert && !SSL_CTX_use_certificate(*ctx,cert))
360 goto error;
361 X509_free(cert); /* We just added a reference to cert. */
362 cert=NULL;
363 if (idcert && !SSL_CTX_add_extra_chain_cert(*ctx,idcert))
364 goto error;
365 idcert=NULL; /* The context now owns the reference to idcert */
367 SSL_CTX_set_session_cache_mode(*ctx, SSL_SESS_CACHE_OFF);
368 if (isServer && !client_only) {
369 tor_assert(rsa);
370 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
371 goto error;
372 if (!SSL_CTX_use_PrivateKey(*ctx, pkey))
373 goto error;
374 EVP_PKEY_free(pkey);
375 pkey = NULL;
376 if (!SSL_CTX_check_private_key(*ctx))
377 goto error;
379 dh = crypto_dh_new();
380 SSL_CTX_set_tmp_dh(*ctx, _crypto_dh_env_get_dh(dh));
381 crypto_dh_free(dh);
382 SSL_CTX_set_verify(*ctx, SSL_VERIFY_PEER,
383 always_accept_verify_cb);
384 /* let us realloc bufs that we're writing from */
385 SSL_CTX_set_mode(*ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
387 /* Free the old context if one exists. */
388 if (global_tls_context) {
389 /* This is safe even if there are open connections: OpenSSL does
390 * reference counting with SSL and SSL_CTX objects. */
391 SSL_CTX_free(global_tls_context->ctx);
392 SSL_CTX_free(global_tls_context->client_only_ctx);
393 tor_free(global_tls_context);
395 global_tls_context = result;
396 if (rsa)
397 crypto_free_pk_env(rsa);
398 return 0;
400 error:
401 tls_log_errors(LOG_WARN, "creating TLS context");
402 if (pkey)
403 EVP_PKEY_free(pkey);
404 if (rsa)
405 crypto_free_pk_env(rsa);
406 if (dh)
407 crypto_dh_free(dh);
408 if (result && result->ctx)
409 SSL_CTX_free(result->ctx);
410 if (result && result->client_only_ctx)
411 SSL_CTX_free(result->client_only_ctx);
412 if (result)
413 tor_free(result);
414 if (cert)
415 X509_free(cert);
416 if (idcert)
417 X509_free(idcert);
418 return -1;
421 /** Create a new TLS object from a file descriptor, and a flag to
422 * determine whether it is functioning as a server.
424 tor_tls_t *
425 tor_tls_new(int sock, int isServer, int use_no_cert)
427 tor_tls_t *result = tor_malloc(sizeof(tor_tls_t));
428 SSL_CTX *ctx;
429 tor_assert(global_tls_context); /* make sure somebody made it first */
430 ctx = use_no_cert ? global_tls_context->client_only_ctx
431 : global_tls_context->ctx;
432 if (!(result->ssl = SSL_new(ctx))) {
433 tls_log_errors(LOG_WARN, "generating TLS context");
434 tor_free(result);
435 return NULL;
437 result->socket = sock;
438 SSL_set_fd(result->ssl, sock);
439 result->state = TOR_TLS_ST_HANDSHAKE;
440 result->isServer = isServer;
441 result->wantwrite_n = 0;
442 /* Not expected to get called. */
443 tls_log_errors(LOG_WARN, "generating TLS context");
444 return result;
447 /** Return whether this tls initiated the connect (client) or
448 * received it (server). */
450 tor_tls_is_server(tor_tls_t *tls)
452 tor_assert(tls);
453 return tls->isServer;
456 /** Release resources associated with a TLS object. Does not close the
457 * underlying file descriptor.
459 void
460 tor_tls_free(tor_tls_t *tls)
462 tor_assert(tls && tls->ssl);
463 SSL_free(tls->ssl);
464 tls->ssl = NULL;
465 tor_free(tls);
468 /** Underlying function for TLS reading. Reads up to <b>len</b>
469 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
470 * number of characters read. On failure, returns TOR_TLS_ERROR,
471 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
474 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
476 int r, err;
477 tor_assert(tls);
478 tor_assert(tls->ssl);
479 tor_assert(tls->state == TOR_TLS_ST_OPEN);
480 r = SSL_read(tls->ssl, cp, len);
481 if (r > 0)
482 return r;
483 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
484 if (err == _TOR_TLS_ZERORETURN) {
485 debug(LD_NET,"read returned r=%d; TLS is closed",r);
486 tls->state = TOR_TLS_ST_CLOSED;
487 return TOR_TLS_CLOSE;
488 } else {
489 tor_assert(err != TOR_TLS_DONE);
490 debug(LD_NET,"read returned r=%d, err=%d",r,err);
491 return err;
495 /** Underlying function for TLS writing. Write up to <b>n</b>
496 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
497 * number of characters written. On failure, returns TOR_TLS_ERROR,
498 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
501 tor_tls_write(tor_tls_t *tls, char *cp, size_t n)
503 int r, err;
504 tor_assert(tls);
505 tor_assert(tls->ssl);
506 tor_assert(tls->state == TOR_TLS_ST_OPEN);
507 if (n == 0)
508 return 0;
509 if (tls->wantwrite_n) {
510 /* if WANTWRITE last time, we must use the _same_ n as before */
511 tor_assert(n >= tls->wantwrite_n);
512 debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
513 (int)n, (int)tls->wantwrite_n);
514 n = tls->wantwrite_n;
515 tls->wantwrite_n = 0;
517 r = SSL_write(tls->ssl, cp, n);
518 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
519 if (err == TOR_TLS_DONE) {
520 return r;
522 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
523 tls->wantwrite_n = n;
525 return err;
528 /** Perform initial handshake on <b>tls</b>. When finished, returns
529 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
530 * or TOR_TLS_WANTWRITE.
533 tor_tls_handshake(tor_tls_t *tls)
535 int r;
536 tor_assert(tls);
537 tor_assert(tls->ssl);
538 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
539 check_no_tls_errors();
540 if (tls->isServer) {
541 r = SSL_accept(tls->ssl);
542 } else {
543 r = SSL_connect(tls->ssl);
545 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
546 if (ERR_peek_error() != 0) {
547 tls_log_errors(LOG_WARN, "handshaking");
548 return TOR_TLS_ERROR;
550 if (r == TOR_TLS_DONE) {
551 tls->state = TOR_TLS_ST_OPEN;
553 return r;
556 /** Shut down an open tls connection <b>tls</b>. When finished, returns
557 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
558 * or TOR_TLS_WANTWRITE.
561 tor_tls_shutdown(tor_tls_t *tls)
563 int r, err;
564 char buf[128];
565 tor_assert(tls);
566 tor_assert(tls->ssl);
568 while (1) {
569 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
570 /* If we've already called shutdown once to send a close message,
571 * we read until the other side has closed too.
573 do {
574 r = SSL_read(tls->ssl, buf, 128);
575 } while (r>0);
576 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
577 LOG_INFO);
578 if (err == _TOR_TLS_ZERORETURN) {
579 tls->state = TOR_TLS_ST_GOTCLOSE;
580 /* fall through... */
581 } else {
582 return err;
586 r = SSL_shutdown(tls->ssl);
587 if (r == 1) {
588 /* If shutdown returns 1, the connection is entirely closed. */
589 tls->state = TOR_TLS_ST_CLOSED;
590 return TOR_TLS_DONE;
592 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
593 LOG_INFO);
594 if (err == _TOR_TLS_SYSCALL) {
595 /* The underlying TCP connection closed while we were shutting down. */
596 tls->state = TOR_TLS_ST_CLOSED;
597 return TOR_TLS_DONE;
598 } else if (err == _TOR_TLS_ZERORETURN) {
599 /* The TLS connection says that it sent a shutdown record, but
600 * isn't done shutting down yet. Make sure that this hasn't
601 * happened before, then go back to the start of the function
602 * and try to read.
604 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
605 tls->state == TOR_TLS_ST_SENTCLOSE) {
606 log(LOG_WARN, LD_NET,
607 "TLS returned \"half-closed\" value while already half-closed");
608 return TOR_TLS_ERROR;
610 tls->state = TOR_TLS_ST_SENTCLOSE;
611 /* fall through ... */
612 } else {
613 return err;
615 } /* end loop */
618 /** Return true iff this TLS connection is authenticated.
621 tor_tls_peer_has_cert(tor_tls_t *tls)
623 X509 *cert;
624 cert = SSL_get_peer_certificate(tls->ssl);
625 tls_log_errors(LOG_WARN, "getting peer certificate");
626 if (!cert)
627 return 0;
628 X509_free(cert);
629 return 1;
632 /** Write the nickname (if any) that the peer connected on <b>tls</b>
633 * claims to have into the first <b>buflen</b> characters of <b>buf</b>.
634 * Truncate the nickname if it is longer than buflen-1 characters. Always
635 * NUL-terminate. Return 0 on success, -1 on failure.
638 tor_tls_get_peer_cert_nickname(tor_tls_t *tls, char *buf, size_t buflen)
640 X509 *cert = NULL;
641 X509_NAME *name = NULL;
642 int nid;
643 int lenout;
644 int r = -1;
646 if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
647 warn(LD_PROTOCOL, "Peer has no certificate");
648 goto error;
650 if (!(name = X509_get_subject_name(cert))) {
651 warn(LD_PROTOCOL, "Peer certificate has no subject name");
652 goto error;
654 if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
655 goto error;
657 lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
658 if (lenout == -1)
659 goto error;
660 if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
661 warn(LD_PROTOCOL, "Peer certificate nickname \"%s\" has illegal characters.",
662 buf);
663 if (strchr(buf, '.'))
664 warn(LD_PROTOCOL, " (Maybe it is not really running Tor at its advertised OR port.)");
665 goto error;
668 r = 0;
670 error:
671 if (cert)
672 X509_free(cert);
674 tls_log_errors(LOG_WARN, "getting peer certificate nickname");
675 return r;
678 static void
679 log_cert_lifetime(X509 *cert, const char *problem)
681 BIO *bio = NULL;
682 BUF_MEM *buf;
683 char *s1=NULL, *s2=NULL;
684 char mytime[33];
685 time_t now = time(NULL);
686 struct tm tm;
688 if (problem)
689 warn(LD_GENERAL,"Certificate %s: is your system clock set incorrectly?",
690 problem);
692 if (!(bio = BIO_new(BIO_s_mem()))) {
693 warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
695 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
696 tls_log_errors(LOG_WARN, "printing certificate lifetime");
697 goto end;
699 BIO_get_mem_ptr(bio, &buf);
700 s1 = tor_strndup(buf->data, buf->length);
702 BIO_reset(bio);
703 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
704 tls_log_errors(LOG_WARN, "printing certificate lifetime");
705 goto end;
707 BIO_get_mem_ptr(bio, &buf);
708 s2 = tor_strndup(buf->data, buf->length);
710 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
712 warn(LD_GENERAL, "(certificate lifetime runs from %s through %s. Your time is %s.)",s1,s2,mytime);
714 end:
715 /* Not expected to get invoked */
716 tls_log_errors(LOG_WARN, "getting certificate lifetime");
717 if (bio)
718 BIO_free(bio);
719 if (s1)
720 tor_free(s1);
721 if (s2)
722 tor_free(s2);
725 /** If the provided tls connection is authenticated and has a
726 * certificate that is currently valid and signed, then set
727 * *<b>identity_key</b> to the identity certificate's key and return
728 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
731 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
733 X509 *cert = NULL, *id_cert = NULL;
734 STACK_OF(X509) *chain = NULL;
735 EVP_PKEY *id_pkey = NULL;
736 RSA *rsa;
737 int num_in_chain;
738 int r = -1, i;
740 *identity_key = NULL;
742 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
743 goto done;
744 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
745 goto done;
746 num_in_chain = sk_X509_num(chain);
747 /* 1 means we're receiving (server-side), and it's just the id_cert.
748 * 2 means we're connecting (client-side), and it's both the link
749 * cert and the id_cert.
751 if (num_in_chain < 1) {
752 log_fn(severity,LD_PROTOCOL,"Unexpected number of certificates in chain (%d)",
753 num_in_chain);
754 goto done;
756 for (i=0; i<num_in_chain; ++i) {
757 id_cert = sk_X509_value(chain, i);
758 if (X509_cmp(id_cert, cert) != 0)
759 break;
761 if (!id_cert) {
762 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
763 goto done;
766 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
767 X509_verify(cert, id_pkey) <= 0) {
768 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
769 tls_log_errors(severity,"verifying certificate");
770 goto done;
773 rsa = EVP_PKEY_get1_RSA(id_pkey);
774 if (!rsa)
775 goto done;
776 *identity_key = _crypto_new_pk_env_rsa(rsa);
778 r = 0;
780 done:
781 if (cert)
782 X509_free(cert);
783 if (id_pkey)
784 EVP_PKEY_free(id_pkey);
786 /* This should never get invoked, but let's make sure in case OpenSSL
787 * acts unexpectedly. */
788 tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
790 return r;
793 /** Check whether the certificate set on the connection <b>tls</b> is
794 * expired or not-yet-valid, give or take <b>tolerance</b>
795 * seconds. Return 0 for valid, -1 for failure.
797 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
800 tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
802 time_t now, t;
803 X509 *cert;
804 int r = -1;
806 now = time(NULL);
808 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
809 goto done;
811 t = now + tolerance;
812 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
813 log_cert_lifetime(cert, "not yet valid");
814 goto done;
816 t = now - tolerance;
817 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
818 log_cert_lifetime(cert, "already expired");
819 goto done;
822 r = 0;
823 done:
824 if (cert)
825 X509_free(cert);
826 /* Not expected to get invoked */
827 tls_log_errors(LOG_WARN, "checking certificate lifetime");
829 return r;
832 /** Return the number of bytes available for reading from <b>tls</b>.
835 tor_tls_get_pending_bytes(tor_tls_t *tls)
837 tor_assert(tls);
838 #if OPENSSL_VERSION_NUMBER < 0x0090700fl
839 if (tls->ssl->rstate == SSL_ST_READ_BODY)
840 return 0;
841 if (tls->ssl->s3->rrec.type != SSL3_RT_APPLICATION_DATA)
842 return 0;
843 #endif
844 return SSL_pending(tls->ssl);
848 /** Return the number of bytes read across the underlying socket. */
849 unsigned long
850 tor_tls_get_n_bytes_read(tor_tls_t *tls)
852 tor_assert(tls);
853 return BIO_number_read(SSL_get_rbio(tls->ssl));
855 /** Return the number of bytes written across the underlying socket. */
856 unsigned long
857 tor_tls_get_n_bytes_written(tor_tls_t *tls)
859 tor_assert(tls);
860 return BIO_number_written(SSL_get_wbio(tls->ssl));
863 /** Implement check_no_tls_errors: If there are any pending OpenSSL
864 * errors, log an error message and assert(0). */
865 void
866 _check_no_tls_errors(const char *fname, int line)
868 if (ERR_peek_error() == 0)
869 return;
870 log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
871 tor_fix_source_file(fname), line);
872 tls_log_errors(LOG_WARN, NULL);