ssl.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /*
  2. * Copyright (c) 2009-2011, Salvatore Sanfilippo <antirez at gmail dot com>
  3. * Copyright (c) 2010-2011, Pieter Noordhuis <pcnoordhuis at gmail dot com>
  4. * Copyright (c) 2019, Redis Labs
  5. *
  6. * All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions are met:
  10. *
  11. * * Redistributions of source code must retain the above copyright notice,
  12. * this list of conditions and the following disclaimer.
  13. * * Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. * * Neither the name of Redis nor the names of its contributors may be used
  17. * to endorse or promote products derived from this software without
  18. * specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  21. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  23. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  24. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  25. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  26. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  27. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  30. * POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. #include "hiredis.h"
  33. #include "async.h"
  34. #include <assert.h>
  35. #include <errno.h>
  36. #include <string.h>
  37. #ifdef _WIN32
  38. #include <windows.h>
  39. #else
  40. #include <pthread.h>
  41. #endif
  42. #include <openssl/ssl.h>
  43. #include <openssl/err.h>
  44. #include "win32.h"
  45. #include "async_private.h"
  46. #include "hiredis_ssl.h"
  47. void __redisSetError(redisContext *c, int type, const char *str);
  48. struct redisSSLContext {
  49. /* Associated OpenSSL SSL_CTX as created by redisCreateSSLContext() */
  50. SSL_CTX *ssl_ctx;
  51. /* Requested SNI, or NULL */
  52. char *server_name;
  53. };
  54. /* The SSL connection context is attached to SSL/TLS connections as a privdata. */
  55. typedef struct redisSSL {
  56. /**
  57. * OpenSSL SSL object.
  58. */
  59. SSL *ssl;
  60. /**
  61. * SSL_write() requires to be called again with the same arguments it was
  62. * previously called with in the event of an SSL_read/SSL_write situation
  63. */
  64. size_t lastLen;
  65. /** Whether the SSL layer requires read (possibly before a write) */
  66. int wantRead;
  67. /**
  68. * Whether a write was requested prior to a read. If set, the write()
  69. * should resume whenever a read takes place, if possible
  70. */
  71. int pendingWrite;
  72. } redisSSL;
  73. /* Forward declaration */
  74. redisContextFuncs redisContextSSLFuncs;
  75. /**
  76. * OpenSSL global initialization and locking handling callbacks.
  77. * Note that this is only required for OpenSSL < 1.1.0.
  78. */
  79. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  80. #define HIREDIS_USE_CRYPTO_LOCKS
  81. #endif
  82. #ifdef HIREDIS_USE_CRYPTO_LOCKS
  83. #ifdef _WIN32
  84. typedef CRITICAL_SECTION sslLockType;
  85. static void sslLockInit(sslLockType* l) {
  86. InitializeCriticalSection(l);
  87. }
  88. static void sslLockAcquire(sslLockType* l) {
  89. EnterCriticalSection(l);
  90. }
  91. static void sslLockRelease(sslLockType* l) {
  92. LeaveCriticalSection(l);
  93. }
  94. #else
  95. typedef pthread_mutex_t sslLockType;
  96. static void sslLockInit(sslLockType *l) {
  97. pthread_mutex_init(l, NULL);
  98. }
  99. static void sslLockAcquire(sslLockType *l) {
  100. pthread_mutex_lock(l);
  101. }
  102. static void sslLockRelease(sslLockType *l) {
  103. pthread_mutex_unlock(l);
  104. }
  105. #endif
  106. static sslLockType* ossl_locks;
  107. static void opensslDoLock(int mode, int lkid, const char *f, int line) {
  108. sslLockType *l = ossl_locks + lkid;
  109. if (mode & CRYPTO_LOCK) {
  110. sslLockAcquire(l);
  111. } else {
  112. sslLockRelease(l);
  113. }
  114. (void)f;
  115. (void)line;
  116. }
  117. static int initOpensslLocks(void) {
  118. unsigned ii, nlocks;
  119. if (CRYPTO_get_locking_callback() != NULL) {
  120. /* Someone already set the callback before us. Don't destroy it! */
  121. return REDIS_OK;
  122. }
  123. nlocks = CRYPTO_num_locks();
  124. ossl_locks = hi_malloc(sizeof(*ossl_locks) * nlocks);
  125. if (ossl_locks == NULL)
  126. return REDIS_ERR;
  127. for (ii = 0; ii < nlocks; ii++) {
  128. sslLockInit(ossl_locks + ii);
  129. }
  130. CRYPTO_set_locking_callback(opensslDoLock);
  131. return REDIS_OK;
  132. }
  133. #endif /* HIREDIS_USE_CRYPTO_LOCKS */
  134. int redisInitOpenSSL(void)
  135. {
  136. SSL_library_init();
  137. #ifdef HIREDIS_USE_CRYPTO_LOCKS
  138. initOpensslLocks();
  139. #endif
  140. return REDIS_OK;
  141. }
  142. /**
  143. * redisSSLContext helper context destruction.
  144. */
  145. const char *redisSSLContextGetError(redisSSLContextError error)
  146. {
  147. switch (error) {
  148. case REDIS_SSL_CTX_NONE:
  149. return "No Error";
  150. case REDIS_SSL_CTX_CREATE_FAILED:
  151. return "Failed to create OpenSSL SSL_CTX";
  152. case REDIS_SSL_CTX_CERT_KEY_REQUIRED:
  153. return "Client cert and key must both be specified or skipped";
  154. case REDIS_SSL_CTX_CA_CERT_LOAD_FAILED:
  155. return "Failed to load CA Certificate or CA Path";
  156. case REDIS_SSL_CTX_CLIENT_CERT_LOAD_FAILED:
  157. return "Failed to load client certificate";
  158. case REDIS_SSL_CTX_PRIVATE_KEY_LOAD_FAILED:
  159. return "Failed to load private key";
  160. default:
  161. return "Unknown error code";
  162. }
  163. }
  164. void redisFreeSSLContext(redisSSLContext *ctx)
  165. {
  166. if (!ctx)
  167. return;
  168. if (ctx->server_name) {
  169. hi_free(ctx->server_name);
  170. ctx->server_name = NULL;
  171. }
  172. if (ctx->ssl_ctx) {
  173. SSL_CTX_free(ctx->ssl_ctx);
  174. ctx->ssl_ctx = NULL;
  175. }
  176. hi_free(ctx);
  177. }
  178. /**
  179. * redisSSLContext helper context initialization.
  180. */
  181. redisSSLContext *redisCreateSSLContext(const char *cacert_filename, const char *capath,
  182. const char *cert_filename, const char *private_key_filename,
  183. const char *server_name, redisSSLContextError *error)
  184. {
  185. redisSSLContext *ctx = hi_calloc(1, sizeof(redisSSLContext));
  186. if (ctx == NULL)
  187. goto error;
  188. ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  189. if (!ctx->ssl_ctx) {
  190. if (error) *error = REDIS_SSL_CTX_CREATE_FAILED;
  191. goto error;
  192. }
  193. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
  194. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  195. if ((cert_filename != NULL && private_key_filename == NULL) ||
  196. (private_key_filename != NULL && cert_filename == NULL)) {
  197. if (error) *error = REDIS_SSL_CTX_CERT_KEY_REQUIRED;
  198. goto error;
  199. }
  200. if (capath || cacert_filename) {
  201. if (!SSL_CTX_load_verify_locations(ctx->ssl_ctx, cacert_filename, capath)) {
  202. if (error) *error = REDIS_SSL_CTX_CA_CERT_LOAD_FAILED;
  203. goto error;
  204. }
  205. }
  206. if (cert_filename) {
  207. if (!SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, cert_filename)) {
  208. if (error) *error = REDIS_SSL_CTX_CLIENT_CERT_LOAD_FAILED;
  209. goto error;
  210. }
  211. if (!SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, private_key_filename, SSL_FILETYPE_PEM)) {
  212. if (error) *error = REDIS_SSL_CTX_PRIVATE_KEY_LOAD_FAILED;
  213. goto error;
  214. }
  215. }
  216. if (server_name)
  217. ctx->server_name = hi_strdup(server_name);
  218. return ctx;
  219. error:
  220. redisFreeSSLContext(ctx);
  221. return NULL;
  222. }
  223. /**
  224. * SSL Connection initialization.
  225. */
  226. static int redisSSLConnect(redisContext *c, SSL *ssl) {
  227. if (c->privctx) {
  228. __redisSetError(c, REDIS_ERR_OTHER, "redisContext was already associated");
  229. return REDIS_ERR;
  230. }
  231. redisSSL *rssl = hi_calloc(1, sizeof(redisSSL));
  232. if (rssl == NULL) {
  233. __redisSetError(c, REDIS_ERR_OOM, "Out of memory");
  234. return REDIS_ERR;
  235. }
  236. c->funcs = &redisContextSSLFuncs;
  237. rssl->ssl = ssl;
  238. SSL_set_mode(rssl->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  239. SSL_set_fd(rssl->ssl, c->fd);
  240. SSL_set_connect_state(rssl->ssl);
  241. ERR_clear_error();
  242. int rv = SSL_connect(rssl->ssl);
  243. if (rv == 1) {
  244. c->privctx = rssl;
  245. return REDIS_OK;
  246. }
  247. rv = SSL_get_error(rssl->ssl, rv);
  248. if (((c->flags & REDIS_BLOCK) == 0) &&
  249. (rv == SSL_ERROR_WANT_READ || rv == SSL_ERROR_WANT_WRITE)) {
  250. c->privctx = rssl;
  251. return REDIS_OK;
  252. }
  253. if (c->err == 0) {
  254. char err[512];
  255. if (rv == SSL_ERROR_SYSCALL)
  256. snprintf(err,sizeof(err)-1,"SSL_connect failed: %s",strerror(errno));
  257. else {
  258. unsigned long e = ERR_peek_last_error();
  259. snprintf(err,sizeof(err)-1,"SSL_connect failed: %s",
  260. ERR_reason_error_string(e));
  261. }
  262. __redisSetError(c, REDIS_ERR_IO, err);
  263. }
  264. hi_free(rssl);
  265. return REDIS_ERR;
  266. }
  267. /**
  268. * A wrapper around redisSSLConnect() for users who manage their own context and
  269. * create their own SSL object.
  270. */
  271. int redisInitiateSSL(redisContext *c, SSL *ssl) {
  272. return redisSSLConnect(c, ssl);
  273. }
  274. /**
  275. * A wrapper around redisSSLConnect() for users who use redisSSLContext and don't
  276. * manage their own SSL objects.
  277. */
  278. int redisInitiateSSLWithContext(redisContext *c, redisSSLContext *redis_ssl_ctx)
  279. {
  280. if (!c || !redis_ssl_ctx)
  281. return REDIS_ERR;
  282. /* We want to verify that redisSSLConnect() won't fail on this, as it will
  283. * not own the SSL object in that case and we'll end up leaking.
  284. */
  285. if (c->privctx)
  286. return REDIS_ERR;
  287. SSL *ssl = SSL_new(redis_ssl_ctx->ssl_ctx);
  288. if (!ssl) {
  289. __redisSetError(c, REDIS_ERR_OTHER, "Couldn't create new SSL instance");
  290. goto error;
  291. }
  292. if (redis_ssl_ctx->server_name) {
  293. if (!SSL_set_tlsext_host_name(ssl, redis_ssl_ctx->server_name)) {
  294. __redisSetError(c, REDIS_ERR_OTHER, "Failed to set server_name/SNI");
  295. goto error;
  296. }
  297. }
  298. return redisSSLConnect(c, ssl);
  299. error:
  300. if (ssl)
  301. SSL_free(ssl);
  302. return REDIS_ERR;
  303. }
  304. static int maybeCheckWant(redisSSL *rssl, int rv) {
  305. /**
  306. * If the error is WANT_READ or WANT_WRITE, the appropriate flags are set
  307. * and true is returned. False is returned otherwise
  308. */
  309. if (rv == SSL_ERROR_WANT_READ) {
  310. rssl->wantRead = 1;
  311. return 1;
  312. } else if (rv == SSL_ERROR_WANT_WRITE) {
  313. rssl->pendingWrite = 1;
  314. return 1;
  315. } else {
  316. return 0;
  317. }
  318. }
  319. /**
  320. * Implementation of redisContextFuncs for SSL connections.
  321. */
  322. static void redisSSLFree(void *privctx){
  323. redisSSL *rsc = privctx;
  324. if (!rsc) return;
  325. if (rsc->ssl) {
  326. SSL_free(rsc->ssl);
  327. rsc->ssl = NULL;
  328. }
  329. hi_free(rsc);
  330. }
  331. static ssize_t redisSSLRead(redisContext *c, char *buf, size_t bufcap) {
  332. redisSSL *rssl = c->privctx;
  333. int nread = SSL_read(rssl->ssl, buf, bufcap);
  334. if (nread > 0) {
  335. return nread;
  336. } else if (nread == 0) {
  337. __redisSetError(c, REDIS_ERR_EOF, "Server closed the connection");
  338. return -1;
  339. } else {
  340. int err = SSL_get_error(rssl->ssl, nread);
  341. if (c->flags & REDIS_BLOCK) {
  342. /**
  343. * In blocking mode, we should never end up in a situation where
  344. * we get an error without it being an actual error, except
  345. * in the case of EINTR, which can be spuriously received from
  346. * debuggers or whatever.
  347. */
  348. if (errno == EINTR) {
  349. return 0;
  350. } else {
  351. const char *msg = NULL;
  352. if (errno == EAGAIN) {
  353. msg = "Resource temporarily unavailable";
  354. }
  355. __redisSetError(c, REDIS_ERR_IO, msg);
  356. return -1;
  357. }
  358. }
  359. /**
  360. * We can very well get an EWOULDBLOCK/EAGAIN, however
  361. */
  362. if (maybeCheckWant(rssl, err)) {
  363. return 0;
  364. } else {
  365. __redisSetError(c, REDIS_ERR_IO, NULL);
  366. return -1;
  367. }
  368. }
  369. }
  370. static ssize_t redisSSLWrite(redisContext *c) {
  371. redisSSL *rssl = c->privctx;
  372. size_t len = rssl->lastLen ? rssl->lastLen : hi_sdslen(c->obuf);
  373. int rv = SSL_write(rssl->ssl, c->obuf, len);
  374. if (rv > 0) {
  375. rssl->lastLen = 0;
  376. } else if (rv < 0) {
  377. rssl->lastLen = len;
  378. int err = SSL_get_error(rssl->ssl, rv);
  379. if ((c->flags & REDIS_BLOCK) == 0 && maybeCheckWant(rssl, err)) {
  380. return 0;
  381. } else {
  382. __redisSetError(c, REDIS_ERR_IO, NULL);
  383. return -1;
  384. }
  385. }
  386. return rv;
  387. }
  388. static void redisSSLAsyncRead(redisAsyncContext *ac) {
  389. int rv;
  390. redisSSL *rssl = ac->c.privctx;
  391. redisContext *c = &ac->c;
  392. rssl->wantRead = 0;
  393. if (rssl->pendingWrite) {
  394. int done;
  395. /* This is probably just a write event */
  396. rssl->pendingWrite = 0;
  397. rv = redisBufferWrite(c, &done);
  398. if (rv == REDIS_ERR) {
  399. __redisAsyncDisconnect(ac);
  400. return;
  401. } else if (!done) {
  402. _EL_ADD_WRITE(ac);
  403. }
  404. }
  405. rv = redisBufferRead(c);
  406. if (rv == REDIS_ERR) {
  407. __redisAsyncDisconnect(ac);
  408. } else {
  409. _EL_ADD_READ(ac);
  410. redisProcessCallbacks(ac);
  411. }
  412. }
  413. static void redisSSLAsyncWrite(redisAsyncContext *ac) {
  414. int rv, done = 0;
  415. redisSSL *rssl = ac->c.privctx;
  416. redisContext *c = &ac->c;
  417. rssl->pendingWrite = 0;
  418. rv = redisBufferWrite(c, &done);
  419. if (rv == REDIS_ERR) {
  420. __redisAsyncDisconnect(ac);
  421. return;
  422. }
  423. if (!done) {
  424. if (rssl->wantRead) {
  425. /* Need to read-before-write */
  426. rssl->pendingWrite = 1;
  427. _EL_DEL_WRITE(ac);
  428. } else {
  429. /* No extra reads needed, just need to write more */
  430. _EL_ADD_WRITE(ac);
  431. }
  432. } else {
  433. /* Already done! */
  434. _EL_DEL_WRITE(ac);
  435. }
  436. /* Always reschedule a read */
  437. _EL_ADD_READ(ac);
  438. }
  439. redisContextFuncs redisContextSSLFuncs = {
  440. .free_privctx = redisSSLFree,
  441. .async_read = redisSSLAsyncRead,
  442. .async_write = redisSSLAsyncWrite,
  443. .read = redisSSLRead,
  444. .write = redisSSLWrite
  445. };