2
0

ssl.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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 <pthread.h>
  36. #include <errno.h>
  37. #include <string.h>
  38. #include <openssl/ssl.h>
  39. #include <openssl/err.h>
  40. #include "async_private.h"
  41. void __redisSetError(redisContext *c, int type, const char *str);
  42. /* The SSL context is attached to SSL/TLS connections as a privdata. */
  43. typedef struct redisSSLContext {
  44. /**
  45. * OpenSSL SSL_CTX; It is optional and will not be set when using
  46. * user-supplied SSL.
  47. */
  48. SSL_CTX *ssl_ctx;
  49. /**
  50. * OpenSSL SSL object.
  51. */
  52. SSL *ssl;
  53. /**
  54. * SSL_write() requires to be called again with the same arguments it was
  55. * previously called with in the event of an SSL_read/SSL_write situation
  56. */
  57. size_t lastLen;
  58. /** Whether the SSL layer requires read (possibly before a write) */
  59. int wantRead;
  60. /**
  61. * Whether a write was requested prior to a read. If set, the write()
  62. * should resume whenever a read takes place, if possible
  63. */
  64. int pendingWrite;
  65. } redisSSLContext;
  66. /* Forward declaration */
  67. redisContextFuncs redisContextSSLFuncs;
  68. #ifdef HIREDIS_SSL_TRACE
  69. /**
  70. * Callback used for debugging
  71. */
  72. static void sslLogCallback(const SSL *ssl, int where, int ret) {
  73. const char *retstr = "";
  74. int should_log = 1;
  75. /* Ignore low-level SSL stuff */
  76. if (where & SSL_CB_ALERT) {
  77. should_log = 1;
  78. }
  79. if (where == SSL_CB_HANDSHAKE_START || where == SSL_CB_HANDSHAKE_DONE) {
  80. should_log = 1;
  81. }
  82. if ((where & SSL_CB_EXIT) && ret == 0) {
  83. should_log = 1;
  84. }
  85. if (!should_log) {
  86. return;
  87. }
  88. retstr = SSL_alert_type_string(ret);
  89. printf("ST(0x%x). %s. R(0x%x)%s\n", where, SSL_state_string_long(ssl), ret, retstr);
  90. if (where == SSL_CB_HANDSHAKE_DONE) {
  91. printf("Using SSL version %s. Cipher=%s\n", SSL_get_version(ssl), SSL_get_cipher_name(ssl));
  92. }
  93. }
  94. #endif
  95. /**
  96. * OpenSSL global initialization and locking handling callbacks.
  97. * Note that this is only required for OpenSSL < 1.1.0.
  98. */
  99. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  100. #define HIREDIS_USE_CRYPTO_LOCKS
  101. #endif
  102. #ifdef HIREDIS_USE_CRYPTO_LOCKS
  103. typedef pthread_mutex_t sslLockType;
  104. static void sslLockInit(sslLockType *l) {
  105. pthread_mutex_init(l, NULL);
  106. }
  107. static void sslLockAcquire(sslLockType *l) {
  108. pthread_mutex_lock(l);
  109. }
  110. static void sslLockRelease(sslLockType *l) {
  111. pthread_mutex_unlock(l);
  112. }
  113. static pthread_mutex_t *ossl_locks;
  114. static void opensslDoLock(int mode, int lkid, const char *f, int line) {
  115. sslLockType *l = ossl_locks + lkid;
  116. if (mode & CRYPTO_LOCK) {
  117. sslLockAcquire(l);
  118. } else {
  119. sslLockRelease(l);
  120. }
  121. (void)f;
  122. (void)line;
  123. }
  124. static void initOpensslLocks(void) {
  125. unsigned ii, nlocks;
  126. if (CRYPTO_get_locking_callback() != NULL) {
  127. /* Someone already set the callback before us. Don't destroy it! */
  128. return;
  129. }
  130. nlocks = CRYPTO_num_locks();
  131. ossl_locks = malloc(sizeof(*ossl_locks) * nlocks);
  132. for (ii = 0; ii < nlocks; ii++) {
  133. sslLockInit(ossl_locks + ii);
  134. }
  135. CRYPTO_set_locking_callback(opensslDoLock);
  136. }
  137. #endif /* HIREDIS_USE_CRYPTO_LOCKS */
  138. /**
  139. * SSL Connection initialization.
  140. */
  141. static int redisSSLConnect(redisContext *c, SSL_CTX *ssl_ctx, SSL *ssl) {
  142. if (c->privdata) {
  143. __redisSetError(c, REDIS_ERR_OTHER, "redisContext was already associated");
  144. return REDIS_ERR;
  145. }
  146. c->privdata = calloc(1, sizeof(redisSSLContext));
  147. c->funcs = &redisContextSSLFuncs;
  148. redisSSLContext *rssl = c->privdata;
  149. rssl->ssl_ctx = ssl_ctx;
  150. rssl->ssl = ssl;
  151. SSL_set_mode(rssl->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  152. SSL_set_fd(rssl->ssl, c->fd);
  153. SSL_set_connect_state(rssl->ssl);
  154. ERR_clear_error();
  155. int rv = SSL_connect(rssl->ssl);
  156. if (rv == 1) {
  157. return REDIS_OK;
  158. }
  159. rv = SSL_get_error(rssl->ssl, rv);
  160. if (((c->flags & REDIS_BLOCK) == 0) &&
  161. (rv == SSL_ERROR_WANT_READ || rv == SSL_ERROR_WANT_WRITE)) {
  162. return REDIS_OK;
  163. }
  164. if (c->err == 0) {
  165. char err[512];
  166. if (rv == SSL_ERROR_SYSCALL)
  167. snprintf(err,sizeof(err)-1,"SSL_connect failed: %s",strerror(errno));
  168. else {
  169. unsigned long e = ERR_peek_last_error();
  170. snprintf(err,sizeof(err)-1,"SSL_connect failed: %s",
  171. ERR_reason_error_string(e));
  172. }
  173. __redisSetError(c, REDIS_ERR_IO, err);
  174. }
  175. return REDIS_ERR;
  176. }
  177. int redisInitiateSSL(redisContext *c, SSL *ssl) {
  178. return redisSSLConnect(c, NULL, ssl);
  179. }
  180. int redisSecureConnection(redisContext *c, const char *capath,
  181. const char *certpath, const char *keypath, const char *servername) {
  182. SSL_CTX *ssl_ctx = NULL;
  183. SSL *ssl = NULL;
  184. /* Initialize global OpenSSL stuff */
  185. static int isInit = 0;
  186. if (!isInit) {
  187. isInit = 1;
  188. SSL_library_init();
  189. #ifdef HIREDIS_USE_CRYPTO_LOCKS
  190. initOpensslLocks();
  191. #endif
  192. }
  193. ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  194. if (!ssl_ctx) {
  195. __redisSetError(c, REDIS_ERR_OTHER, "Failed to create SSL_CTX");
  196. goto error;
  197. }
  198. #ifdef HIREDIS_SSL_TRACE
  199. SSL_CTX_set_info_callback(ssl_ctx, sslLogCallback);
  200. #endif
  201. SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
  202. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
  203. if ((certpath != NULL && keypath == NULL) || (keypath != NULL && certpath == NULL)) {
  204. __redisSetError(c, REDIS_ERR_OTHER, "certpath and keypath must be specified together");
  205. goto error;
  206. }
  207. if (capath) {
  208. if (!SSL_CTX_load_verify_locations(ssl_ctx, capath, NULL)) {
  209. __redisSetError(c, REDIS_ERR_OTHER, "Invalid CA certificate");
  210. goto error;
  211. }
  212. }
  213. if (certpath) {
  214. if (!SSL_CTX_use_certificate_chain_file(ssl_ctx, certpath)) {
  215. __redisSetError(c, REDIS_ERR_OTHER, "Invalid client certificate");
  216. goto error;
  217. }
  218. if (!SSL_CTX_use_PrivateKey_file(ssl_ctx, keypath, SSL_FILETYPE_PEM)) {
  219. __redisSetError(c, REDIS_ERR_OTHER, "Invalid client key");
  220. goto error;
  221. }
  222. }
  223. ssl = SSL_new(ssl_ctx);
  224. if (!ssl) {
  225. __redisSetError(c, REDIS_ERR_OTHER, "Couldn't create new SSL instance");
  226. goto error;
  227. }
  228. if (servername) {
  229. if (!SSL_set_tlsext_host_name(ssl, servername)) {
  230. __redisSetError(c, REDIS_ERR_OTHER, "Couldn't set server name indication");
  231. goto error;
  232. }
  233. }
  234. return redisSSLConnect(c, ssl_ctx, ssl);
  235. error:
  236. if (ssl) SSL_free(ssl);
  237. if (ssl_ctx) SSL_CTX_free(ssl_ctx);
  238. return REDIS_ERR;
  239. }
  240. static int maybeCheckWant(redisSSLContext *rssl, int rv) {
  241. /**
  242. * If the error is WANT_READ or WANT_WRITE, the appropriate flags are set
  243. * and true is returned. False is returned otherwise
  244. */
  245. if (rv == SSL_ERROR_WANT_READ) {
  246. rssl->wantRead = 1;
  247. return 1;
  248. } else if (rv == SSL_ERROR_WANT_WRITE) {
  249. rssl->pendingWrite = 1;
  250. return 1;
  251. } else {
  252. return 0;
  253. }
  254. }
  255. /**
  256. * Implementation of redisContextFuncs for SSL connections.
  257. */
  258. static void redisSSLFreeContext(void *privdata){
  259. redisSSLContext *rsc = privdata;
  260. if (!rsc) return;
  261. if (rsc->ssl) {
  262. SSL_free(rsc->ssl);
  263. rsc->ssl = NULL;
  264. }
  265. if (rsc->ssl_ctx) {
  266. SSL_CTX_free(rsc->ssl_ctx);
  267. rsc->ssl_ctx = NULL;
  268. }
  269. free(rsc);
  270. }
  271. static int redisSSLRead(redisContext *c, char *buf, size_t bufcap) {
  272. redisSSLContext *rssl = c->privdata;
  273. int nread = SSL_read(rssl->ssl, buf, bufcap);
  274. if (nread > 0) {
  275. return nread;
  276. } else if (nread == 0) {
  277. __redisSetError(c, REDIS_ERR_EOF, "Server closed the connection");
  278. return -1;
  279. } else {
  280. int err = SSL_get_error(rssl->ssl, nread);
  281. if (c->flags & REDIS_BLOCK) {
  282. /**
  283. * In blocking mode, we should never end up in a situation where
  284. * we get an error without it being an actual error, except
  285. * in the case of EINTR, which can be spuriously received from
  286. * debuggers or whatever.
  287. */
  288. if (errno == EINTR) {
  289. return 0;
  290. } else {
  291. const char *msg = NULL;
  292. if (errno == EAGAIN) {
  293. msg = "Resource temporarily unavailable";
  294. }
  295. __redisSetError(c, REDIS_ERR_IO, msg);
  296. return -1;
  297. }
  298. }
  299. /**
  300. * We can very well get an EWOULDBLOCK/EAGAIN, however
  301. */
  302. if (maybeCheckWant(rssl, err)) {
  303. return 0;
  304. } else {
  305. __redisSetError(c, REDIS_ERR_IO, NULL);
  306. return -1;
  307. }
  308. }
  309. }
  310. static int redisSSLWrite(redisContext *c) {
  311. redisSSLContext *rssl = c->privdata;
  312. size_t len = rssl->lastLen ? rssl->lastLen : sdslen(c->obuf);
  313. int rv = SSL_write(rssl->ssl, c->obuf, len);
  314. if (rv > 0) {
  315. rssl->lastLen = 0;
  316. } else if (rv < 0) {
  317. rssl->lastLen = len;
  318. int err = SSL_get_error(rssl->ssl, rv);
  319. if ((c->flags & REDIS_BLOCK) == 0 && maybeCheckWant(rssl, err)) {
  320. return 0;
  321. } else {
  322. __redisSetError(c, REDIS_ERR_IO, NULL);
  323. return -1;
  324. }
  325. }
  326. return rv;
  327. }
  328. static void redisSSLAsyncRead(redisAsyncContext *ac) {
  329. int rv;
  330. redisSSLContext *rssl = ac->c.privdata;
  331. redisContext *c = &ac->c;
  332. rssl->wantRead = 0;
  333. if (rssl->pendingWrite) {
  334. int done;
  335. /* This is probably just a write event */
  336. rssl->pendingWrite = 0;
  337. rv = redisBufferWrite(c, &done);
  338. if (rv == REDIS_ERR) {
  339. __redisAsyncDisconnect(ac);
  340. return;
  341. } else if (!done) {
  342. _EL_ADD_WRITE(ac);
  343. }
  344. }
  345. rv = redisBufferRead(c);
  346. if (rv == REDIS_ERR) {
  347. __redisAsyncDisconnect(ac);
  348. } else {
  349. _EL_ADD_READ(ac);
  350. redisProcessCallbacks(ac);
  351. }
  352. }
  353. static void redisSSLAsyncWrite(redisAsyncContext *ac) {
  354. int rv, done = 0;
  355. redisSSLContext *rssl = ac->c.privdata;
  356. redisContext *c = &ac->c;
  357. rssl->pendingWrite = 0;
  358. rv = redisBufferWrite(c, &done);
  359. if (rv == REDIS_ERR) {
  360. __redisAsyncDisconnect(ac);
  361. return;
  362. }
  363. if (!done) {
  364. if (rssl->wantRead) {
  365. /* Need to read-before-write */
  366. rssl->pendingWrite = 1;
  367. _EL_DEL_WRITE(ac);
  368. } else {
  369. /* No extra reads needed, just need to write more */
  370. _EL_ADD_WRITE(ac);
  371. }
  372. } else {
  373. /* Already done! */
  374. _EL_DEL_WRITE(ac);
  375. }
  376. /* Always reschedule a read */
  377. _EL_ADD_READ(ac);
  378. }
  379. redisContextFuncs redisContextSSLFuncs = {
  380. .free_privdata = redisSSLFreeContext,
  381. .async_read = redisSSLAsyncRead,
  382. .async_write = redisSSLAsyncWrite,
  383. .read = redisSSLRead,
  384. .write = redisSSLWrite
  385. };