Check for even more windows version flags, and note any we do not recognize.
[tor.git] / src / common / tortls.c
bloba4cd730b380fbf41ed8f62cf6dc97e6ead2f01cc
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 if (!SSL_CTX_set_cipher_list(*ctx, CIPHER_LIST))
356 goto error;
357 if (!client_only) {
358 if (cert && !SSL_CTX_use_certificate(*ctx,cert))
359 goto error;
360 X509_free(cert); /* We just added a reference to cert. */
361 cert=NULL;
362 if (idcert && !SSL_CTX_add_extra_chain_cert(*ctx,idcert))
363 goto error;
364 idcert=NULL; /* The context now owns the reference to idcert */
366 SSL_CTX_set_session_cache_mode(*ctx, SSL_SESS_CACHE_OFF);
367 if (isServer && !client_only) {
368 tor_assert(rsa);
369 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
370 goto error;
371 if (!SSL_CTX_use_PrivateKey(*ctx, pkey))
372 goto error;
373 EVP_PKEY_free(pkey);
374 pkey = NULL;
375 if (!SSL_CTX_check_private_key(*ctx))
376 goto error;
378 dh = crypto_dh_new();
379 SSL_CTX_set_tmp_dh(*ctx, _crypto_dh_env_get_dh(dh));
380 crypto_dh_free(dh);
381 SSL_CTX_set_verify(*ctx, SSL_VERIFY_PEER,
382 always_accept_verify_cb);
383 /* let us realloc bufs that we're writing from */
384 SSL_CTX_set_mode(*ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
386 /* Free the old context if one exists. */
387 if (global_tls_context) {
388 /* This is safe even if there are open connections: OpenSSL does
389 * reference counting with SSL and SSL_CTX objects. */
390 SSL_CTX_free(global_tls_context->ctx);
391 SSL_CTX_free(global_tls_context->client_only_ctx);
392 tor_free(global_tls_context);
394 global_tls_context = result;
395 if (rsa)
396 crypto_free_pk_env(rsa);
397 return 0;
399 error:
400 tls_log_errors(LOG_WARN, "creating TLS context");
401 if (pkey)
402 EVP_PKEY_free(pkey);
403 if (rsa)
404 crypto_free_pk_env(rsa);
405 if (dh)
406 crypto_dh_free(dh);
407 if (result && result->ctx)
408 SSL_CTX_free(result->ctx);
409 if (result && result->client_only_ctx)
410 SSL_CTX_free(result->client_only_ctx);
411 if (result)
412 tor_free(result);
413 if (cert)
414 X509_free(cert);
415 if (idcert)
416 X509_free(idcert);
417 return -1;
420 /** Create a new TLS object from a file descriptor, and a flag to
421 * determine whether it is functioning as a server.
423 tor_tls_t *
424 tor_tls_new(int sock, int isServer, int use_no_cert)
426 tor_tls_t *result = tor_malloc(sizeof(tor_tls_t));
427 SSL_CTX *ctx;
428 tor_assert(global_tls_context); /* make sure somebody made it first */
429 ctx = use_no_cert ? global_tls_context->client_only_ctx
430 : global_tls_context->ctx;
431 if (!(result->ssl = SSL_new(ctx))) {
432 tls_log_errors(LOG_WARN, "generating TLS context");
433 tor_free(result);
434 return NULL;
436 result->socket = sock;
437 SSL_set_fd(result->ssl, sock);
438 result->state = TOR_TLS_ST_HANDSHAKE;
439 result->isServer = isServer;
440 result->wantwrite_n = 0;
441 /* Not expected to get called. */
442 tls_log_errors(LOG_WARN, "generating TLS context");
443 return result;
446 /** Return whether this tls initiated the connect (client) or
447 * received it (server). */
449 tor_tls_is_server(tor_tls_t *tls)
451 tor_assert(tls);
452 return tls->isServer;
455 /** Release resources associated with a TLS object. Does not close the
456 * underlying file descriptor.
458 void
459 tor_tls_free(tor_tls_t *tls)
461 tor_assert(tls && tls->ssl);
462 SSL_free(tls->ssl);
463 tls->ssl = NULL;
464 tor_free(tls);
467 /** Underlying function for TLS reading. Reads up to <b>len</b>
468 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
469 * number of characters read. On failure, returns TOR_TLS_ERROR,
470 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
473 tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
475 int r, err;
476 tor_assert(tls);
477 tor_assert(tls->ssl);
478 tor_assert(tls->state == TOR_TLS_ST_OPEN);
479 r = SSL_read(tls->ssl, cp, len);
480 if (r > 0)
481 return r;
482 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
483 if (err == _TOR_TLS_ZERORETURN) {
484 debug(LD_NET,"read returned r=%d; TLS is closed",r);
485 tls->state = TOR_TLS_ST_CLOSED;
486 return TOR_TLS_CLOSE;
487 } else {
488 tor_assert(err != TOR_TLS_DONE);
489 debug(LD_NET,"read returned r=%d, err=%d",r,err);
490 return err;
494 /** Underlying function for TLS writing. Write up to <b>n</b>
495 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
496 * number of characters written. On failure, returns TOR_TLS_ERROR,
497 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
500 tor_tls_write(tor_tls_t *tls, char *cp, size_t n)
502 int r, err;
503 tor_assert(tls);
504 tor_assert(tls->ssl);
505 tor_assert(tls->state == TOR_TLS_ST_OPEN);
506 if (n == 0)
507 return 0;
508 if (tls->wantwrite_n) {
509 /* if WANTWRITE last time, we must use the _same_ n as before */
510 tor_assert(n >= tls->wantwrite_n);
511 debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
512 (int)n, (int)tls->wantwrite_n);
513 n = tls->wantwrite_n;
514 tls->wantwrite_n = 0;
516 r = SSL_write(tls->ssl, cp, n);
517 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
518 if (err == TOR_TLS_DONE) {
519 return r;
521 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
522 tls->wantwrite_n = n;
524 return err;
527 /** Perform initial handshake on <b>tls</b>. When finished, returns
528 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
529 * or TOR_TLS_WANTWRITE.
532 tor_tls_handshake(tor_tls_t *tls)
534 int r;
535 tor_assert(tls);
536 tor_assert(tls->ssl);
537 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
538 check_no_tls_errors();
539 if (tls->isServer) {
540 r = SSL_accept(tls->ssl);
541 } else {
542 r = SSL_connect(tls->ssl);
544 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
545 if (ERR_peek_error() != 0) {
546 tls_log_errors(LOG_WARN, "handshaking");
547 return TOR_TLS_ERROR;
549 if (r == TOR_TLS_DONE) {
550 tls->state = TOR_TLS_ST_OPEN;
552 return r;
555 /** Shut down an open tls connection <b>tls</b>. When finished, returns
556 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
557 * or TOR_TLS_WANTWRITE.
560 tor_tls_shutdown(tor_tls_t *tls)
562 int r, err;
563 char buf[128];
564 tor_assert(tls);
565 tor_assert(tls->ssl);
567 while (1) {
568 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
569 /* If we've already called shutdown once to send a close message,
570 * we read until the other side has closed too.
572 do {
573 r = SSL_read(tls->ssl, buf, 128);
574 } while (r>0);
575 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
576 LOG_INFO);
577 if (err == _TOR_TLS_ZERORETURN) {
578 tls->state = TOR_TLS_ST_GOTCLOSE;
579 /* fall through... */
580 } else {
581 return err;
585 r = SSL_shutdown(tls->ssl);
586 if (r == 1) {
587 /* If shutdown returns 1, the connection is entirely closed. */
588 tls->state = TOR_TLS_ST_CLOSED;
589 return TOR_TLS_DONE;
591 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
592 LOG_INFO);
593 if (err == _TOR_TLS_SYSCALL) {
594 /* The underlying TCP connection closed while we were shutting down. */
595 tls->state = TOR_TLS_ST_CLOSED;
596 return TOR_TLS_DONE;
597 } else if (err == _TOR_TLS_ZERORETURN) {
598 /* The TLS connection says that it sent a shutdown record, but
599 * isn't done shutting down yet. Make sure that this hasn't
600 * happened before, then go back to the start of the function
601 * and try to read.
603 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
604 tls->state == TOR_TLS_ST_SENTCLOSE) {
605 log(LOG_WARN, LD_NET,
606 "TLS returned \"half-closed\" value while already half-closed");
607 return TOR_TLS_ERROR;
609 tls->state = TOR_TLS_ST_SENTCLOSE;
610 /* fall through ... */
611 } else {
612 return err;
614 } /* end loop */
617 /** Return true iff this TLS connection is authenticated.
620 tor_tls_peer_has_cert(tor_tls_t *tls)
622 X509 *cert;
623 cert = SSL_get_peer_certificate(tls->ssl);
624 tls_log_errors(LOG_WARN, "getting peer certificate");
625 if (!cert)
626 return 0;
627 X509_free(cert);
628 return 1;
631 /** Write the nickname (if any) that the peer connected on <b>tls</b>
632 * claims to have into the first <b>buflen</b> characters of <b>buf</b>.
633 * Truncate the nickname if it is longer than buflen-1 characters. Always
634 * NUL-terminate. Return 0 on success, -1 on failure.
637 tor_tls_get_peer_cert_nickname(tor_tls_t *tls, char *buf, size_t buflen)
639 X509 *cert = NULL;
640 X509_NAME *name = NULL;
641 int nid;
642 int lenout;
643 int r = -1;
645 if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
646 warn(LD_PROTOCOL, "Peer has no certificate");
647 goto error;
649 if (!(name = X509_get_subject_name(cert))) {
650 warn(LD_PROTOCOL, "Peer certificate has no subject name");
651 goto error;
653 if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
654 goto error;
656 lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
657 if (lenout == -1)
658 goto error;
659 if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
660 warn(LD_PROTOCOL, "Peer certificate nickname \"%s\" has illegal characters.",
661 buf);
662 if (strchr(buf, '.'))
663 warn(LD_PROTOCOL, " (Maybe it is not really running Tor at its advertised OR port.)");
664 goto error;
667 r = 0;
669 error:
670 if (cert)
671 X509_free(cert);
673 tls_log_errors(LOG_WARN, "getting peer certificate nickname");
674 return r;
677 static void
678 log_cert_lifetime(X509 *cert, const char *problem)
680 BIO *bio = NULL;
681 BUF_MEM *buf;
682 char *s1=NULL, *s2=NULL;
683 char mytime[33];
684 time_t now = time(NULL);
685 struct tm tm;
687 if (problem)
688 warn(LD_GENERAL,"Certificate %s: is your system clock set incorrectly?",
689 problem);
691 if (!(bio = BIO_new(BIO_s_mem()))) {
692 warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
694 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
695 tls_log_errors(LOG_WARN, "printing certificate lifetime");
696 goto end;
698 BIO_get_mem_ptr(bio, &buf);
699 s1 = tor_strndup(buf->data, buf->length);
701 BIO_reset(bio);
702 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
703 tls_log_errors(LOG_WARN, "printing certificate lifetime");
704 goto end;
706 BIO_get_mem_ptr(bio, &buf);
707 s2 = tor_strndup(buf->data, buf->length);
709 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
711 warn(LD_GENERAL, "(certificate lifetime runs from %s through %s. Your time is %s.)",s1,s2,mytime);
713 end:
714 /* Not expected to get invoked */
715 tls_log_errors(LOG_WARN, "getting certificate lifetime");
716 if (bio)
717 BIO_free(bio);
718 if (s1)
719 tor_free(s1);
720 if (s2)
721 tor_free(s2);
724 /** If the provided tls connection is authenticated and has a
725 * certificate that is currently valid and signed, then set
726 * *<b>identity_key</b> to the identity certificate's key and return
727 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
730 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
732 X509 *cert = NULL, *id_cert = NULL;
733 STACK_OF(X509) *chain = NULL;
734 EVP_PKEY *id_pkey = NULL;
735 RSA *rsa;
736 int num_in_chain;
737 int r = -1, i;
739 *identity_key = NULL;
741 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
742 goto done;
743 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
744 goto done;
745 num_in_chain = sk_X509_num(chain);
746 /* 1 means we're receiving (server-side), and it's just the id_cert.
747 * 2 means we're connecting (client-side), and it's both the link
748 * cert and the id_cert.
750 if (num_in_chain < 1) {
751 log_fn(severity,LD_PROTOCOL,"Unexpected number of certificates in chain (%d)",
752 num_in_chain);
753 goto done;
755 for (i=0; i<num_in_chain; ++i) {
756 id_cert = sk_X509_value(chain, i);
757 if (X509_cmp(id_cert, cert) != 0)
758 break;
760 if (!id_cert) {
761 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
762 goto done;
765 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
766 X509_verify(cert, id_pkey) <= 0) {
767 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
768 tls_log_errors(severity,"verifying certificate");
769 goto done;
772 rsa = EVP_PKEY_get1_RSA(id_pkey);
773 if (!rsa)
774 goto done;
775 *identity_key = _crypto_new_pk_env_rsa(rsa);
777 r = 0;
779 done:
780 if (cert)
781 X509_free(cert);
782 if (id_pkey)
783 EVP_PKEY_free(id_pkey);
785 /* This should never get invoked, but let's make sure in case OpenSSL
786 * acts unexpectedly. */
787 tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
789 return r;
792 /** Check whether the certificate set on the connection <b>tls</b> is
793 * expired or not-yet-valid, give or take <b>tolerance</b>
794 * seconds. Return 0 for valid, -1 for failure.
796 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
799 tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
801 time_t now, t;
802 X509 *cert;
803 int r = -1;
805 now = time(NULL);
807 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
808 goto done;
810 t = now + tolerance;
811 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
812 log_cert_lifetime(cert, "not yet valid");
813 goto done;
815 t = now - tolerance;
816 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
817 log_cert_lifetime(cert, "already expired");
818 goto done;
821 r = 0;
822 done:
823 if (cert)
824 X509_free(cert);
825 /* Not expected to get invoked */
826 tls_log_errors(LOG_WARN, "checking certificate lifetime");
828 return r;
831 /** Return the number of bytes available for reading from <b>tls</b>.
834 tor_tls_get_pending_bytes(tor_tls_t *tls)
836 tor_assert(tls);
837 #if OPENSSL_VERSION_NUMBER < 0x0090700fl
838 if (tls->ssl->rstate == SSL_ST_READ_BODY)
839 return 0;
840 if (tls->ssl->s3->rrec.type != SSL3_RT_APPLICATION_DATA)
841 return 0;
842 #endif
843 return SSL_pending(tls->ssl);
847 /** Return the number of bytes read across the underlying socket. */
848 unsigned long
849 tor_tls_get_n_bytes_read(tor_tls_t *tls)
851 tor_assert(tls);
852 return BIO_number_read(SSL_get_rbio(tls->ssl));
854 /** Return the number of bytes written across the underlying socket. */
855 unsigned long
856 tor_tls_get_n_bytes_written(tor_tls_t *tls)
858 tor_assert(tls);
859 return BIO_number_written(SSL_get_wbio(tls->ssl));
862 /** Implement check_no_tls_errors: If there are any pending OpenSSL
863 * errors, log an error message and assert(0). */
864 void
865 _check_no_tls_errors(const char *fname, int line)
867 if (ERR_peek_error() == 0)
868 return;
869 log_fn(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
870 fname, line);
871 tls_log_errors(LOG_WARN, NULL);