SSLSocket.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. /*******************************************************************************
  2. * Copyright (c) 2009, 2019 IBM Corp.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v1.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * http://www.eclipse.org/legal/epl-v10.html
  10. * and the Eclipse Distribution License is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * Contributors:
  14. * Ian Craggs, Allan Stockdill-Mander - initial implementation
  15. * Ian Craggs - fix for bug #409702
  16. * Ian Craggs - allow compilation for OpenSSL < 1.0
  17. * Ian Craggs - fix for bug #453883
  18. * Ian Craggs - fix for bug #480363, issue 13
  19. * Ian Craggs - SNI support
  20. * Ian Craggs - fix for issues #155, #160
  21. *******************************************************************************/
  22. /**
  23. * @file
  24. * \brief SSL related functions
  25. *
  26. */
  27. #if defined(OPENSSL)
  28. #include "SocketBuffer.h"
  29. #include "MQTTClient.h"
  30. #include "MQTTProtocolOut.h"
  31. #include "SSLSocket.h"
  32. #include "Log.h"
  33. #include "StackTrace.h"
  34. #include "Socket.h"
  35. #include "Heap.h"
  36. #include <string.h>
  37. #include <openssl/ssl.h>
  38. #include <openssl/err.h>
  39. #include <openssl/crypto.h>
  40. #include <openssl/x509v3.h>
  41. extern Sockets s;
  42. static int SSLSocket_error(char* aString, SSL* ssl, int sock, int rc, int (*cb)(const char *str, size_t len, void *u), void* u);
  43. char* SSL_get_verify_result_string(int rc);
  44. void SSL_CTX_info_callback(const SSL* ssl, int where, int ret);
  45. char* SSLSocket_get_version_string(int version);
  46. void SSL_CTX_msg_callback(
  47. int write_p,
  48. int version,
  49. int content_type,
  50. const void* buf, size_t len,
  51. SSL* ssl, void* arg);
  52. int pem_passwd_cb(char* buf, int size, int rwflag, void* userdata);
  53. int SSL_create_mutex(ssl_mutex_type* mutex);
  54. int SSL_lock_mutex(ssl_mutex_type* mutex);
  55. int SSL_unlock_mutex(ssl_mutex_type* mutex);
  56. void SSL_destroy_mutex(ssl_mutex_type* mutex);
  57. #if (OPENSSL_VERSION_NUMBER >= 0x010000000)
  58. extern void SSLThread_id(CRYPTO_THREADID *id);
  59. #else
  60. extern unsigned long SSLThread_id(void);
  61. #endif
  62. extern void SSLLocks_callback(int mode, int n, const char *file, int line);
  63. int SSLSocket_createContext(networkHandles* net, MQTTClient_SSLOptions* opts);
  64. void SSLSocket_destroyContext(networkHandles* net);
  65. void SSLSocket_addPendingRead(int sock);
  66. /* 1 ~ we are responsible for initializing openssl; 0 ~ openssl init is done externally */
  67. static int handle_openssl_init = 1;
  68. static ssl_mutex_type* sslLocks = NULL;
  69. static ssl_mutex_type sslCoreMutex;
  70. /* Used to store MQTTClient_SSLOptions for TLS-PSK callback */
  71. static int tls_ex_index_ssl_opts;
  72. #if defined(WIN32) || defined(WIN64)
  73. #define iov_len len
  74. #define iov_base buf
  75. #endif
  76. /**
  77. * Gets the specific error corresponding to SOCKET_ERROR
  78. * @param aString the function that was being used when the error occurred
  79. * @param sock the socket on which the error occurred
  80. * @param rc the return code
  81. * @param cb the callback function to be passed as first argument to ERR_print_errors_cb
  82. * @param u context to be passed as second argument to ERR_print_errors_cb
  83. * @return the specific TCP error code
  84. */
  85. static int SSLSocket_error(char* aString, SSL* ssl, int sock, int rc, int (*cb)(const char *str, size_t len, void *u), void* u)
  86. {
  87. int error;
  88. FUNC_ENTRY;
  89. if (ssl)
  90. error = SSL_get_error(ssl, rc);
  91. else
  92. error = ERR_get_error();
  93. if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)
  94. {
  95. Log(TRACE_MIN, -1, "SSLSocket error WANT_READ/WANT_WRITE");
  96. }
  97. else
  98. {
  99. static char buf[120];
  100. if (strcmp(aString, "shutdown") != 0)
  101. Log(TRACE_MIN, -1, "SSLSocket error %s(%d) in %s for socket %d rc %d errno %d %s\n", buf, error, aString, sock, rc, errno, strerror(errno));
  102. if (cb)
  103. ERR_print_errors_cb(cb, u);
  104. if (error == SSL_ERROR_SSL || error == SSL_ERROR_SYSCALL)
  105. error = SSL_FATAL;
  106. }
  107. FUNC_EXIT_RC(error);
  108. return error;
  109. }
  110. static struct
  111. {
  112. int code;
  113. char* string;
  114. }
  115. X509_message_table[] =
  116. {
  117. { X509_V_OK, "X509_V_OK" },
  118. { X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT" },
  119. { X509_V_ERR_UNABLE_TO_GET_CRL, "X509_V_ERR_UNABLE_TO_GET_CRL" },
  120. { X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, "X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE" },
  121. { X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, "X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE" },
  122. { X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, "X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY" },
  123. { X509_V_ERR_CERT_SIGNATURE_FAILURE, "X509_V_ERR_CERT_SIGNATURE_FAILURE" },
  124. { X509_V_ERR_CRL_SIGNATURE_FAILURE, "X509_V_ERR_CRL_SIGNATURE_FAILURE" },
  125. { X509_V_ERR_CERT_NOT_YET_VALID, "X509_V_ERR_CERT_NOT_YET_VALID" },
  126. { X509_V_ERR_CERT_HAS_EXPIRED, "X509_V_ERR_CERT_HAS_EXPIRED" },
  127. { X509_V_ERR_CRL_NOT_YET_VALID, "X509_V_ERR_CRL_NOT_YET_VALID" },
  128. { X509_V_ERR_CRL_HAS_EXPIRED, "X509_V_ERR_CRL_HAS_EXPIRED" },
  129. { X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, "X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD" },
  130. { X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, "X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD" },
  131. { X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, "X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD" },
  132. { X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, "X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD" },
  133. { X509_V_ERR_OUT_OF_MEM, "X509_V_ERR_OUT_OF_MEM" },
  134. { X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, "X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT" },
  135. { X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, "X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN" },
  136. { X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY" },
  137. { X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, "X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE" },
  138. { X509_V_ERR_CERT_CHAIN_TOO_LONG, "X509_V_ERR_CERT_CHAIN_TOO_LONG" },
  139. { X509_V_ERR_CERT_REVOKED, "X509_V_ERR_CERT_REVOKED" },
  140. { X509_V_ERR_INVALID_CA, "X509_V_ERR_INVALID_CA" },
  141. { X509_V_ERR_PATH_LENGTH_EXCEEDED, "X509_V_ERR_PATH_LENGTH_EXCEEDED" },
  142. { X509_V_ERR_INVALID_PURPOSE, "X509_V_ERR_INVALID_PURPOSE" },
  143. { X509_V_ERR_CERT_UNTRUSTED, "X509_V_ERR_CERT_UNTRUSTED" },
  144. { X509_V_ERR_CERT_REJECTED, "X509_V_ERR_CERT_REJECTED" },
  145. { X509_V_ERR_SUBJECT_ISSUER_MISMATCH, "X509_V_ERR_SUBJECT_ISSUER_MISMATCH" },
  146. { X509_V_ERR_AKID_SKID_MISMATCH, "X509_V_ERR_AKID_SKID_MISMATCH" },
  147. { X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH, "X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH" },
  148. { X509_V_ERR_KEYUSAGE_NO_CERTSIGN, "X509_V_ERR_KEYUSAGE_NO_CERTSIGN" },
  149. { X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, "X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER" },
  150. { X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION, "X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION" },
  151. { X509_V_ERR_KEYUSAGE_NO_CRL_SIGN, "X509_V_ERR_KEYUSAGE_NO_CRL_SIGN" },
  152. { X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION, "X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION" },
  153. { X509_V_ERR_INVALID_NON_CA, "X509_V_ERR_INVALID_NON_CA" },
  154. { X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED, "X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED" },
  155. { X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE, "X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE" },
  156. { X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED, "X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED" },
  157. { X509_V_ERR_INVALID_EXTENSION, "X509_V_ERR_INVALID_EXTENSION" },
  158. { X509_V_ERR_INVALID_POLICY_EXTENSION, "X509_V_ERR_INVALID_POLICY_EXTENSION" },
  159. { X509_V_ERR_NO_EXPLICIT_POLICY, "X509_V_ERR_NO_EXPLICIT_POLICY" },
  160. { X509_V_ERR_UNNESTED_RESOURCE, "X509_V_ERR_UNNESTED_RESOURCE" },
  161. #if defined(X509_V_ERR_DIFFERENT_CRL_SCOPE)
  162. { X509_V_ERR_DIFFERENT_CRL_SCOPE, "X509_V_ERR_DIFFERENT_CRL_SCOPE" },
  163. { X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE, "X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE" },
  164. { X509_V_ERR_PERMITTED_VIOLATION, "X509_V_ERR_PERMITTED_VIOLATION" },
  165. { X509_V_ERR_EXCLUDED_VIOLATION, "X509_V_ERR_EXCLUDED_VIOLATION" },
  166. { X509_V_ERR_SUBTREE_MINMAX, "X509_V_ERR_SUBTREE_MINMAX" },
  167. { X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE, "X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE" },
  168. { X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX, "X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX" },
  169. { X509_V_ERR_UNSUPPORTED_NAME_SYNTAX, "X509_V_ERR_UNSUPPORTED_NAME_SYNTAX" },
  170. #endif
  171. };
  172. #if !defined(ARRAY_SIZE)
  173. /**
  174. * Macro to calculate the number of entries in an array
  175. */
  176. #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
  177. #endif
  178. char* SSL_get_verify_result_string(int rc)
  179. {
  180. int i;
  181. char* retstring = "undef";
  182. for (i = 0; i < ARRAY_SIZE(X509_message_table); ++i)
  183. {
  184. if (X509_message_table[i].code == rc)
  185. {
  186. retstring = X509_message_table[i].string;
  187. break;
  188. }
  189. }
  190. return retstring;
  191. }
  192. void SSL_CTX_info_callback(const SSL* ssl, int where, int ret)
  193. {
  194. if (where & SSL_CB_LOOP)
  195. {
  196. Log(TRACE_PROTOCOL, 1, "SSL state %s:%s:%s",
  197. (where & SSL_ST_CONNECT) ? "connect" : (where & SSL_ST_ACCEPT) ? "accept" : "undef",
  198. SSL_state_string_long(ssl), SSL_get_cipher_name(ssl));
  199. }
  200. else if (where & SSL_CB_EXIT)
  201. {
  202. Log(TRACE_PROTOCOL, 1, "SSL %s:%s",
  203. (where & SSL_ST_CONNECT) ? "connect" : (where & SSL_ST_ACCEPT) ? "accept" : "undef",
  204. SSL_state_string_long(ssl));
  205. }
  206. else if (where & SSL_CB_ALERT)
  207. {
  208. Log(TRACE_PROTOCOL, 1, "SSL alert %s:%s:%s",
  209. (where & SSL_CB_READ) ? "read" : "write",
  210. SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
  211. }
  212. else if (where & SSL_CB_HANDSHAKE_START)
  213. {
  214. Log(TRACE_PROTOCOL, 1, "SSL handshake started %s:%s:%s",
  215. (where & SSL_CB_READ) ? "read" : "write",
  216. SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
  217. }
  218. else if (where & SSL_CB_HANDSHAKE_DONE)
  219. {
  220. Log(TRACE_PROTOCOL, 1, "SSL handshake done %s:%s:%s",
  221. (where & SSL_CB_READ) ? "read" : "write",
  222. SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
  223. Log(TRACE_PROTOCOL, 1, "SSL certificate verification: %s",
  224. SSL_get_verify_result_string(SSL_get_verify_result(ssl)));
  225. }
  226. else
  227. {
  228. Log(TRACE_PROTOCOL, 1, "SSL state %s:%s:%s", SSL_state_string_long(ssl),
  229. SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
  230. }
  231. }
  232. char* SSLSocket_get_version_string(int version)
  233. {
  234. int i;
  235. static char buf[20];
  236. char* retstring = NULL;
  237. static struct
  238. {
  239. int code;
  240. char* string;
  241. }
  242. version_string_table[] =
  243. {
  244. { SSL2_VERSION, "SSL 2.0" },
  245. { SSL3_VERSION, "SSL 3.0" },
  246. { TLS1_VERSION, "TLS 1.0" },
  247. #if defined(TLS2_VERSION)
  248. { TLS2_VERSION, "TLS 1.1" },
  249. #endif
  250. #if defined(TLS3_VERSION)
  251. { TLS3_VERSION, "TLS 1.2" },
  252. #endif
  253. };
  254. for (i = 0; i < ARRAY_SIZE(version_string_table); ++i)
  255. {
  256. if (version_string_table[i].code == version)
  257. {
  258. retstring = version_string_table[i].string;
  259. break;
  260. }
  261. }
  262. if (retstring == NULL)
  263. {
  264. sprintf(buf, "%i", version);
  265. retstring = buf;
  266. }
  267. return retstring;
  268. }
  269. void SSL_CTX_msg_callback(int write_p, int version, int content_type, const void* buf, size_t len,
  270. SSL* ssl, void* arg)
  271. {
  272. /*
  273. called by the SSL/TLS library for a protocol message, the function arguments have the following meaning:
  274. write_p
  275. This flag is 0 when a protocol message has been received and 1 when a protocol message has been sent.
  276. version
  277. The protocol version according to which the protocol message is interpreted by the library. Currently, this is one of SSL2_VERSION, SSL3_VERSION and TLS1_VERSION (for SSL 2.0, SSL 3.0 and TLS 1.0, respectively).
  278. content_type
  279. In the case of SSL 2.0, this is always 0. In the case of SSL 3.0 or TLS 1.0, this is one of the ContentType values defined in the protocol specification (change_cipher_spec(20), alert(21), handshake(22); but never application_data(23) because the callback will only be called for protocol messages).
  280. buf, len
  281. buf points to a buffer containing the protocol message, which consists of len bytes. The buffer is no longer valid after the callback function has returned.
  282. ssl
  283. The SSL object that received or sent the message.
  284. arg
  285. The user-defined argument optionally defined by SSL_CTX_set_msg_callback_arg() or SSL_set_msg_callback_arg().
  286. */
  287. Log(TRACE_MINIMUM, -1, "%s %s %d buflen %d", (write_p ? "sent" : "received"),
  288. SSLSocket_get_version_string(version),
  289. content_type, (int)len);
  290. }
  291. int pem_passwd_cb(char* buf, int size, int rwflag, void* userdata)
  292. {
  293. int rc = 0;
  294. FUNC_ENTRY;
  295. if (!rwflag)
  296. {
  297. strncpy(buf, (char*)(userdata), size);
  298. buf[size-1] = '\0';
  299. rc = (int)strlen(buf);
  300. }
  301. FUNC_EXIT_RC(rc);
  302. return rc;
  303. }
  304. int SSL_create_mutex(ssl_mutex_type* mutex)
  305. {
  306. int rc = 0;
  307. FUNC_ENTRY;
  308. #if defined(WIN32) || defined(WIN64)
  309. *mutex = CreateMutex(NULL, 0, NULL);
  310. #else
  311. rc = pthread_mutex_init(mutex, NULL);
  312. #endif
  313. FUNC_EXIT_RC(rc);
  314. return rc;
  315. }
  316. int SSL_lock_mutex(ssl_mutex_type* mutex)
  317. {
  318. int rc = -1;
  319. /* don't add entry/exit trace points, as trace gets lock too, and it might happen quite frequently */
  320. #if defined(WIN32) || defined(WIN64)
  321. if (WaitForSingleObject(*mutex, INFINITE) != WAIT_FAILED)
  322. #else
  323. if ((rc = pthread_mutex_lock(mutex)) == 0)
  324. #endif
  325. rc = 0;
  326. return rc;
  327. }
  328. int SSL_unlock_mutex(ssl_mutex_type* mutex)
  329. {
  330. int rc = -1;
  331. /* don't add entry/exit trace points, as trace gets lock too, and it might happen quite frequently */
  332. #if defined(WIN32) || defined(WIN64)
  333. if (ReleaseMutex(*mutex) != 0)
  334. #else
  335. if ((rc = pthread_mutex_unlock(mutex)) == 0)
  336. #endif
  337. rc = 0;
  338. return rc;
  339. }
  340. void SSL_destroy_mutex(ssl_mutex_type* mutex)
  341. {
  342. int rc = 0;
  343. FUNC_ENTRY;
  344. #if defined(WIN32) || defined(WIN64)
  345. rc = CloseHandle(*mutex);
  346. #else
  347. rc = pthread_mutex_destroy(mutex);
  348. #endif
  349. FUNC_EXIT_RC(rc);
  350. }
  351. #if (OPENSSL_VERSION_NUMBER >= 0x010000000)
  352. extern void SSLThread_id(CRYPTO_THREADID *id)
  353. {
  354. #if defined(WIN32) || defined(WIN64)
  355. CRYPTO_THREADID_set_numeric(id, (unsigned long)GetCurrentThreadId());
  356. #else
  357. CRYPTO_THREADID_set_numeric(id, (unsigned long)pthread_self());
  358. #endif
  359. }
  360. #else
  361. extern unsigned long SSLThread_id(void)
  362. {
  363. #if defined(WIN32) || defined(WIN64)
  364. return (unsigned long)GetCurrentThreadId();
  365. #else
  366. return (unsigned long)pthread_self();
  367. #endif
  368. }
  369. #endif
  370. extern void SSLLocks_callback(int mode, int n, const char *file, int line)
  371. {
  372. if (sslLocks)
  373. {
  374. if (mode & CRYPTO_LOCK)
  375. SSL_lock_mutex(&sslLocks[n]);
  376. else
  377. SSL_unlock_mutex(&sslLocks[n]);
  378. }
  379. }
  380. void SSLSocket_handleOpensslInit(int bool_value)
  381. {
  382. handle_openssl_init = bool_value;
  383. }
  384. int SSLSocket_initialize(void)
  385. {
  386. int rc = 0;
  387. /*int prc;*/
  388. int i;
  389. int lockMemSize;
  390. FUNC_ENTRY;
  391. if (handle_openssl_init)
  392. {
  393. if ((rc = SSL_library_init()) != 1)
  394. rc = -1;
  395. ERR_load_crypto_strings();
  396. SSL_load_error_strings();
  397. /* OpenSSL 0.9.8o and 1.0.0a and later added SHA2 algorithms to SSL_library_init().
  398. Applications which need to use SHA2 in earlier versions of OpenSSL should call
  399. OpenSSL_add_all_algorithms() as well. */
  400. OpenSSL_add_all_algorithms();
  401. lockMemSize = CRYPTO_num_locks() * sizeof(ssl_mutex_type);
  402. sslLocks = malloc(lockMemSize);
  403. if (!sslLocks)
  404. {
  405. rc = -1;
  406. goto exit;
  407. }
  408. else
  409. memset(sslLocks, 0, lockMemSize);
  410. for (i = 0; i < CRYPTO_num_locks(); i++)
  411. {
  412. /* prc = */SSL_create_mutex(&sslLocks[i]);
  413. }
  414. #if (OPENSSL_VERSION_NUMBER >= 0x010000000)
  415. CRYPTO_THREADID_set_callback(SSLThread_id);
  416. #else
  417. CRYPTO_set_id_callback(SSLThread_id);
  418. #endif
  419. CRYPTO_set_locking_callback(SSLLocks_callback);
  420. }
  421. SSL_create_mutex(&sslCoreMutex);
  422. tls_ex_index_ssl_opts = SSL_get_ex_new_index(0, "paho ssl options", NULL, NULL, NULL);
  423. exit:
  424. FUNC_EXIT_RC(rc);
  425. return rc;
  426. }
  427. void SSLSocket_terminate(void)
  428. {
  429. FUNC_ENTRY;
  430. if (handle_openssl_init)
  431. {
  432. EVP_cleanup();
  433. ERR_free_strings();
  434. CRYPTO_set_locking_callback(NULL);
  435. if (sslLocks)
  436. {
  437. int i = 0;
  438. for (i = 0; i < CRYPTO_num_locks(); i++)
  439. {
  440. SSL_destroy_mutex(&sslLocks[i]);
  441. }
  442. free(sslLocks);
  443. }
  444. }
  445. SSL_destroy_mutex(&sslCoreMutex);
  446. FUNC_EXIT;
  447. }
  448. static unsigned int call_ssl_psk_cb(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len)
  449. {
  450. int rc = 0;
  451. FUNC_ENTRY;
  452. SSL_CTX *ctx = SSL_get_SSL_CTX(ssl);
  453. MQTTClient_SSLOptions* opts = SSL_CTX_get_ex_data(ctx, tls_ex_index_ssl_opts);
  454. if (opts == NULL)
  455. goto exit;
  456. if (opts->ssl_psk_cb != NULL)
  457. rc = opts->ssl_psk_cb(hint, identity, max_identity_len, psk, max_psk_len, opts->ssl_psk_context);
  458. exit:
  459. FUNC_EXIT_RC(rc);
  460. return rc;
  461. }
  462. int SSLSocket_createContext(networkHandles* net, MQTTClient_SSLOptions* opts)
  463. {
  464. int rc = 1;
  465. FUNC_ENTRY;
  466. if (net->ctx == NULL)
  467. {
  468. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  469. net->ctx = SSL_CTX_new(TLS_client_method());
  470. #else
  471. int sslVersion = MQTT_SSL_VERSION_DEFAULT;
  472. if (opts->struct_version >= 1) sslVersion = opts->sslVersion;
  473. /* SSL_OP_NO_TLSv1_1 is defined in ssl.h if the library version supports TLSv1.1.
  474. * OPENSSL_NO_TLS1 is defined in opensslconf.h or on the compiler command line
  475. * if TLS1.x was removed at OpenSSL library build time via Configure options.
  476. */
  477. switch (sslVersion)
  478. {
  479. case MQTT_SSL_VERSION_DEFAULT:
  480. net->ctx = SSL_CTX_new(SSLv23_client_method()); /* SSLv23 for compatibility with SSLv2, SSLv3 and TLSv1 */
  481. break;
  482. #if defined(SSL_OP_NO_TLSv1) && !defined(OPENSSL_NO_TLS1)
  483. case MQTT_SSL_VERSION_TLS_1_0:
  484. net->ctx = SSL_CTX_new(TLSv1_client_method());
  485. break;
  486. #endif
  487. #if defined(SSL_OP_NO_TLSv1_1) && !defined(OPENSSL_NO_TLS1)
  488. case MQTT_SSL_VERSION_TLS_1_1:
  489. net->ctx = SSL_CTX_new(TLSv1_1_client_method());
  490. break;
  491. #endif
  492. #if defined(SSL_OP_NO_TLSv1_2) && !defined(OPENSSL_NO_TLS1)
  493. case MQTT_SSL_VERSION_TLS_1_2:
  494. net->ctx = SSL_CTX_new(TLSv1_2_client_method());
  495. break;
  496. #endif
  497. default:
  498. break;
  499. }
  500. #endif
  501. if (net->ctx == NULL)
  502. {
  503. if (opts->struct_version >= 3)
  504. SSLSocket_error("SSL_CTX_new", NULL, net->socket, rc, opts->ssl_error_cb, opts->ssl_error_context);
  505. else
  506. SSLSocket_error("SSL_CTX_new", NULL, net->socket, rc, NULL, NULL);
  507. goto exit;
  508. }
  509. }
  510. if (opts->keyStore)
  511. {
  512. if ((rc = SSL_CTX_use_certificate_chain_file(net->ctx, opts->keyStore)) != 1)
  513. {
  514. if (opts->struct_version >= 3)
  515. SSLSocket_error("SSL_CTX_use_certificate_chain_file", NULL, net->socket, rc, opts->ssl_error_cb, opts->ssl_error_context);
  516. else
  517. SSLSocket_error("SSL_CTX_use_certificate_chain_file", NULL, net->socket, rc, NULL, NULL);
  518. goto free_ctx; /*If we can't load the certificate (chain) file then loading the privatekey won't work either as it needs a matching cert already loaded */
  519. }
  520. if (opts->privateKey == NULL)
  521. opts->privateKey = opts->keyStore; /* the privateKey can be included in the keyStore */
  522. if (opts->privateKeyPassword != NULL)
  523. {
  524. SSL_CTX_set_default_passwd_cb(net->ctx, pem_passwd_cb);
  525. SSL_CTX_set_default_passwd_cb_userdata(net->ctx, (void*)opts->privateKeyPassword);
  526. }
  527. /* support for ASN.1 == DER format? DER can contain only one certificate? */
  528. rc = SSL_CTX_use_PrivateKey_file(net->ctx, opts->privateKey, SSL_FILETYPE_PEM);
  529. if (opts->privateKey == opts->keyStore)
  530. opts->privateKey = NULL;
  531. if (rc != 1)
  532. {
  533. if (opts->struct_version >= 3)
  534. SSLSocket_error("SSL_CTX_use_PrivateKey_file", NULL, net->socket, rc, opts->ssl_error_cb, opts->ssl_error_context);
  535. else
  536. SSLSocket_error("SSL_CTX_use_PrivateKey_file", NULL, net->socket, rc, NULL, NULL);
  537. goto free_ctx;
  538. }
  539. }
  540. if (opts->trustStore || opts->CApath)
  541. {
  542. if ((rc = SSL_CTX_load_verify_locations(net->ctx, opts->trustStore, opts->CApath)) != 1)
  543. {
  544. if (opts->struct_version >= 3)
  545. SSLSocket_error("SSL_CTX_load_verify_locations", NULL, net->socket, rc, opts->ssl_error_cb, opts->ssl_error_context);
  546. else
  547. SSLSocket_error("SSL_CTX_load_verify_locations", NULL, net->socket, rc, NULL, NULL);
  548. goto free_ctx;
  549. }
  550. }
  551. else if (!opts->disableDefaultTrustStore)
  552. {
  553. if ((rc = SSL_CTX_set_default_verify_paths(net->ctx)) != 1)
  554. {
  555. if (opts->struct_version >= 3)
  556. SSLSocket_error("SSL_CTX_set_default_verify_paths", NULL, net->socket, rc, opts->ssl_error_cb, opts->ssl_error_context);
  557. else
  558. SSLSocket_error("SSL_CTX_set_default_verify_paths", NULL, net->socket, rc, NULL, NULL);
  559. goto free_ctx;
  560. }
  561. }
  562. if (opts->enabledCipherSuites)
  563. {
  564. if ((rc = SSL_CTX_set_cipher_list(net->ctx, opts->enabledCipherSuites)) != 1)
  565. {
  566. if (opts->struct_version >= 3)
  567. SSLSocket_error("SSL_CTX_set_cipher_list", NULL, net->socket, rc, opts->ssl_error_cb, opts->ssl_error_context);
  568. else
  569. SSLSocket_error("SSL_CTX_set_cipher_list", NULL, net->socket, rc, NULL, NULL);
  570. goto free_ctx;
  571. }
  572. }
  573. #ifndef OPENSSL_NO_PSK
  574. if (opts->ssl_psk_cb != NULL)
  575. {
  576. SSL_CTX_set_ex_data(net->ctx, tls_ex_index_ssl_opts, opts);
  577. SSL_CTX_set_psk_client_callback(net->ctx, call_ssl_psk_cb);
  578. }
  579. #endif
  580. SSL_CTX_set_mode(net->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  581. goto exit;
  582. free_ctx:
  583. SSL_CTX_free(net->ctx);
  584. net->ctx = NULL;
  585. exit:
  586. FUNC_EXIT_RC(rc);
  587. return rc;
  588. }
  589. int SSLSocket_setSocketForSSL(networkHandles* net, MQTTClient_SSLOptions* opts,
  590. const char* hostname, size_t hostname_len)
  591. {
  592. int rc = 1;
  593. FUNC_ENTRY;
  594. if (net->ctx != NULL || (rc = SSLSocket_createContext(net, opts)) == 1)
  595. {
  596. char *hostname_plus_null;
  597. int i;
  598. SSL_CTX_set_info_callback(net->ctx, SSL_CTX_info_callback);
  599. SSL_CTX_set_msg_callback(net->ctx, SSL_CTX_msg_callback);
  600. if (opts->enableServerCertAuth)
  601. SSL_CTX_set_verify(net->ctx, SSL_VERIFY_PEER, NULL);
  602. net->ssl = SSL_new(net->ctx);
  603. /* Log all ciphers available to the SSL sessions (loaded in ctx) */
  604. for (i = 0; ;i++)
  605. {
  606. const char* cipher = SSL_get_cipher_list(net->ssl, i);
  607. if (cipher == NULL)
  608. break;
  609. Log(TRACE_PROTOCOL, 1, "SSL cipher available: %d:%s", i, cipher);
  610. }
  611. if ((rc = SSL_set_fd(net->ssl, net->socket)) != 1) {
  612. if (opts->struct_version >= 3)
  613. SSLSocket_error("SSL_set_fd", net->ssl, net->socket, rc, opts->ssl_error_cb, opts->ssl_error_context);
  614. else
  615. SSLSocket_error("SSL_set_fd", net->ssl, net->socket, rc, NULL, NULL);
  616. }
  617. hostname_plus_null = malloc(hostname_len + 1u );
  618. MQTTStrncpy(hostname_plus_null, hostname, hostname_len + 1u);
  619. if ((rc = SSL_set_tlsext_host_name(net->ssl, hostname_plus_null)) != 1) {
  620. if (opts->struct_version >= 3)
  621. SSLSocket_error("SSL_set_tlsext_host_name", NULL, net->socket, rc, opts->ssl_error_cb, opts->ssl_error_context);
  622. else
  623. SSLSocket_error("SSL_set_tlsext_host_name", NULL, net->socket, rc, NULL, NULL);
  624. }
  625. free(hostname_plus_null);
  626. }
  627. FUNC_EXIT_RC(rc);
  628. return rc;
  629. }
  630. /*
  631. * Return value: 1 - success, TCPSOCKET_INTERRUPTED - try again, anything else is failure
  632. */
  633. int SSLSocket_connect(SSL* ssl, int sock, const char* hostname, int verify, int (*cb)(const char *str, size_t len, void *u), void* u)
  634. {
  635. int rc = 0;
  636. FUNC_ENTRY;
  637. rc = SSL_connect(ssl);
  638. if (rc != 1)
  639. {
  640. int error;
  641. error = SSLSocket_error("SSL_connect", ssl, sock, rc, cb, u);
  642. if (error == SSL_FATAL)
  643. rc = error;
  644. if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)
  645. rc = TCPSOCKET_INTERRUPTED;
  646. }
  647. #if (OPENSSL_VERSION_NUMBER >= 0x010002000) /* 1.0.2 and later */
  648. else if (verify == 1)
  649. {
  650. char* peername = NULL;
  651. int port;
  652. size_t hostname_len;
  653. X509* cert = SSL_get_peer_certificate(ssl);
  654. hostname_len = MQTTProtocol_addressPort(hostname, &port, NULL);
  655. rc = X509_check_host(cert, hostname, hostname_len, 0, &peername);
  656. if (rc == 1)
  657. Log(TRACE_PROTOCOL, -1, "peername from X509_check_host is %s", peername);
  658. else
  659. Log(TRACE_PROTOCOL, -1, "X509_check_host for hostname %.*s failed, rc %d",
  660. hostname_len, hostname, rc);
  661. if (peername != NULL)
  662. OPENSSL_free(peername);
  663. // 0 == fail, -1 == SSL internal error, -2 == mailformed input
  664. if (rc == 0 || rc == -1 || rc == -2)
  665. {
  666. char* ip_addr = malloc(hostname_len + 1);
  667. // cannot use = strndup(hostname, hostname_len); here because of custom Heap
  668. if (ip_addr)
  669. {
  670. strncpy(ip_addr, hostname, hostname_len);
  671. ip_addr[hostname_len] = '\0';
  672. rc = X509_check_ip_asc(cert, ip_addr, 0);
  673. Log(TRACE_MIN, -1, "rc from X509_check_ip_asc is %d", rc);
  674. free(ip_addr);
  675. }
  676. if (rc == 0 || rc == -1 || rc == -2)
  677. rc = SSL_FATAL;
  678. }
  679. if (cert)
  680. X509_free(cert);
  681. }
  682. #endif
  683. FUNC_EXIT_RC(rc);
  684. return rc;
  685. }
  686. /**
  687. * Reads one byte from a socket
  688. * @param socket the socket to read from
  689. * @param c the character read, returned
  690. * @return completion code
  691. */
  692. int SSLSocket_getch(SSL* ssl, int socket, char* c)
  693. {
  694. int rc = SOCKET_ERROR;
  695. FUNC_ENTRY;
  696. if ((rc = SocketBuffer_getQueuedChar(socket, c)) != SOCKETBUFFER_INTERRUPTED)
  697. goto exit;
  698. if ((rc = SSL_read(ssl, c, (size_t)1)) < 0)
  699. {
  700. int err = SSLSocket_error("SSL_read - getch", ssl, socket, rc, NULL, NULL);
  701. if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE)
  702. {
  703. rc = TCPSOCKET_INTERRUPTED;
  704. SocketBuffer_interrupted(socket, 0);
  705. }
  706. }
  707. else if (rc == 0)
  708. rc = SOCKET_ERROR; /* The return value from recv is 0 when the peer has performed an orderly shutdown. */
  709. else if (rc == 1)
  710. {
  711. SocketBuffer_queueChar(socket, *c);
  712. rc = TCPSOCKET_COMPLETE;
  713. }
  714. exit:
  715. FUNC_EXIT_RC(rc);
  716. return rc;
  717. }
  718. /**
  719. * Attempts to read a number of bytes from a socket, non-blocking. If a previous read did not
  720. * finish, then retrieve that data.
  721. * @param socket the socket to read from
  722. * @param bytes the number of bytes to read
  723. * @param actual_len the actual number of bytes read
  724. * @return completion code
  725. */
  726. char *SSLSocket_getdata(SSL* ssl, int socket, size_t bytes, size_t* actual_len)
  727. {
  728. int rc;
  729. char* buf;
  730. FUNC_ENTRY;
  731. if (bytes == 0)
  732. {
  733. buf = SocketBuffer_complete(socket);
  734. goto exit;
  735. }
  736. buf = SocketBuffer_getQueuedData(socket, bytes, actual_len);
  737. if ((rc = SSL_read(ssl, buf + (*actual_len), (int)(bytes - (*actual_len)))) < 0)
  738. {
  739. rc = SSLSocket_error("SSL_read - getdata", ssl, socket, rc, NULL, NULL);
  740. if (rc != SSL_ERROR_WANT_READ && rc != SSL_ERROR_WANT_WRITE)
  741. {
  742. buf = NULL;
  743. goto exit;
  744. }
  745. }
  746. else if (rc == 0) /* rc 0 means the other end closed the socket */
  747. {
  748. buf = NULL;
  749. goto exit;
  750. }
  751. else
  752. *actual_len += rc;
  753. if (*actual_len == bytes)
  754. {
  755. SocketBuffer_complete(socket);
  756. /* if we read the whole packet, there might still be data waiting in the SSL buffer, which
  757. isn't picked up by select. So here we should check for any data remaining in the SSL buffer, and
  758. if so, add this socket to a new "pending SSL reads" list.
  759. */
  760. if (SSL_pending(ssl) > 0) /* return no of bytes pending */
  761. SSLSocket_addPendingRead(socket);
  762. }
  763. else /* we didn't read the whole packet */
  764. {
  765. SocketBuffer_interrupted(socket, *actual_len);
  766. Log(TRACE_MAX, -1, "SSL_read: %d bytes expected but %d bytes now received", bytes, *actual_len);
  767. }
  768. exit:
  769. FUNC_EXIT;
  770. return buf;
  771. }
  772. void SSLSocket_destroyContext(networkHandles* net)
  773. {
  774. FUNC_ENTRY;
  775. if (net->ctx)
  776. SSL_CTX_free(net->ctx);
  777. net->ctx = NULL;
  778. FUNC_EXIT;
  779. }
  780. static List pending_reads = {NULL, NULL, NULL, 0, 0};
  781. int SSLSocket_close(networkHandles* net)
  782. {
  783. int rc = 1;
  784. FUNC_ENTRY;
  785. /* clean up any pending reads for this socket */
  786. if (pending_reads.count > 0 && ListFindItem(&pending_reads, &net->socket, intcompare))
  787. ListRemoveItem(&pending_reads, &net->socket, intcompare);
  788. if (net->ssl)
  789. {
  790. rc = SSL_shutdown(net->ssl);
  791. SSL_free(net->ssl);
  792. net->ssl = NULL;
  793. }
  794. SSLSocket_destroyContext(net);
  795. FUNC_EXIT_RC(rc);
  796. return rc;
  797. }
  798. /* No SSL_writev() provided by OpenSSL. Boo. */
  799. int SSLSocket_putdatas(SSL* ssl, int socket, char* buf0, size_t buf0len, int count, char** buffers, size_t* buflens, int* frees)
  800. {
  801. int rc = 0;
  802. int i;
  803. char *ptr;
  804. iobuf iovec;
  805. int sslerror;
  806. FUNC_ENTRY;
  807. iovec.iov_len = (ULONG)buf0len;
  808. for (i = 0; i < count; i++)
  809. iovec.iov_len += (ULONG)buflens[i];
  810. ptr = iovec.iov_base = (char *)malloc(iovec.iov_len);
  811. memcpy(ptr, buf0, buf0len);
  812. ptr += buf0len;
  813. for (i = 0; i < count; i++)
  814. {
  815. memcpy(ptr, buffers[i], buflens[i]);
  816. ptr += buflens[i];
  817. }
  818. SSL_lock_mutex(&sslCoreMutex);
  819. if ((rc = SSL_write(ssl, iovec.iov_base, iovec.iov_len)) == iovec.iov_len)
  820. rc = TCPSOCKET_COMPLETE;
  821. else
  822. {
  823. sslerror = SSLSocket_error("SSL_write", ssl, socket, rc, NULL, NULL);
  824. if (sslerror == SSL_ERROR_WANT_WRITE)
  825. {
  826. int* sockmem = (int*)malloc(sizeof(int));
  827. int free = 1;
  828. Log(TRACE_MIN, -1, "Partial write: incomplete write of %d bytes on SSL socket %d",
  829. iovec.iov_len, socket);
  830. SocketBuffer_pendingWrite(socket, ssl, 1, &iovec, &free, iovec.iov_len, 0);
  831. *sockmem = socket;
  832. ListAppend(s.write_pending, sockmem, sizeof(int));
  833. FD_SET(socket, &(s.pending_wset));
  834. rc = TCPSOCKET_INTERRUPTED;
  835. }
  836. else
  837. rc = SOCKET_ERROR;
  838. }
  839. SSL_unlock_mutex(&sslCoreMutex);
  840. if (rc != TCPSOCKET_INTERRUPTED)
  841. free(iovec.iov_base);
  842. else
  843. {
  844. int i;
  845. free(buf0);
  846. for (i = 0; i < count; ++i)
  847. {
  848. if (frees[i])
  849. {
  850. free(buffers[i]);
  851. buffers[i] = NULL;
  852. }
  853. }
  854. }
  855. FUNC_EXIT_RC(rc);
  856. return rc;
  857. }
  858. void SSLSocket_addPendingRead(int sock)
  859. {
  860. FUNC_ENTRY;
  861. if (ListFindItem(&pending_reads, &sock, intcompare) == NULL) /* make sure we don't add the same socket twice */
  862. {
  863. int* psock = (int*)malloc(sizeof(sock));
  864. *psock = sock;
  865. ListAppend(&pending_reads, psock, sizeof(sock));
  866. }
  867. else
  868. Log(TRACE_MIN, -1, "SSLSocket_addPendingRead: socket %d already in the list", sock);
  869. FUNC_EXIT;
  870. }
  871. int SSLSocket_getPendingRead(void)
  872. {
  873. int sock = -1;
  874. if (pending_reads.count > 0)
  875. {
  876. sock = *(int*)(pending_reads.first->content);
  877. ListRemoveHead(&pending_reads);
  878. }
  879. return sock;
  880. }
  881. int SSLSocket_continueWrite(pending_writes* pw)
  882. {
  883. int rc = 0;
  884. FUNC_ENTRY;
  885. if ((rc = SSL_write(pw->ssl, pw->iovecs[0].iov_base, pw->iovecs[0].iov_len)) == pw->iovecs[0].iov_len)
  886. {
  887. /* topic and payload buffers are freed elsewhere, when all references to them have been removed */
  888. free(pw->iovecs[0].iov_base);
  889. Log(TRACE_MIN, -1, "SSL continueWrite: partial write now complete for socket %d", pw->socket);
  890. rc = 1;
  891. }
  892. else
  893. {
  894. int sslerror = SSLSocket_error("SSL_write", pw->ssl, pw->socket, rc, NULL, NULL);
  895. if (sslerror == SSL_ERROR_WANT_WRITE)
  896. rc = 0; /* indicate we haven't finished writing the payload yet */
  897. }
  898. FUNC_EXIT_RC(rc);
  899. return rc;
  900. }
  901. #endif