1 /******************************************************************
3 * Copyright 2016 Samsung Electronics All Rights Reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 ******************************************************************/
22 #include "iotivity_config.h"
28 #include "ca_adapter_net_ssl.h"
30 #include "caipinterface.h"
31 #include "oic_malloc.h"
33 #include "byte_array.h"
37 // headers required for mbed TLS
38 #include "mbedtls/platform.h"
39 #include "mbedtls/ssl.h"
40 #include "mbedtls/entropy.h"
41 #include "mbedtls/ctr_drbg.h"
42 #include "mbedtls/pkcs12.h"
43 #include "mbedtls/ssl_internal.h"
44 #include "mbedtls/net_sockets.h"
46 #include "mbedtls/timing.h"
47 #include "mbedtls/ssl_cookie.h"
50 #if !defined(NDEBUG) || defined(TB_LOG)
51 #include "mbedtls/debug.h"
52 #include "mbedtls/version.h"
55 #ifdef HAVE_SYS_TYPES_H
56 #include <sys/types.h>
58 #ifdef HAVE_SYS_STAT_H
70 * @def MBED_TLS_VERSION_LEN
71 * @brief mbedTLS version string length
73 #define MBED_TLS_VERSION_LEN (16)
75 * @def PERSONALIZATION_STRING
76 * @brief Personalization string for the mbedtls RNG
78 #define PERSONALIZATION_STRING "IOTIVITY_RND"
81 * @brief uuid prefix in certificate subject field
83 #define UUID_PREFIX "uuid:"
86 * @brief userid prefix in certificate alternative subject name field
88 #define USERID_PREFIX "userid:"
92 * @brief Logging tag for module name
94 #define NET_SSL_TAG "OIC_CA_NET_SSL"
97 * @brief Logging tag for mbedTLS library
99 #define MBED_TLS_TAG "MBED_TLS"
101 * @def MMBED_TLS_DEBUG_LEVEL
102 * @brief Logging level for mbedTLS library
104 #define MBED_TLS_DEBUG_LEVEL (4)
107 * @def TLS_MSG_BUF_LEN
108 * @brief Buffer size for TLS record. A single TLS record may be up to 16384 octets in length
111 #define TLS_MSG_BUF_LEN (16384)
114 * @brief PSK keys max length
116 #define PSK_LENGTH (256/8)
118 * @def UUID_LENGTHPSK_LENGTH
119 * @brief Identity max length
121 #define UUID_LENGTH (128/8)
123 * @def MASTER_SECRET_LEN
124 * @brief TLS master secret length
126 #define MASTER_SECRET_LEN (48)
129 * @brief TLS client and server random bytes length
131 #define RANDOM_LEN (32)
133 * @def SHA384_MAC_KEY_LENGTH
134 * @brief MAC key length for SHA384 cipher suites
136 #define SHA384_MAC_KEY_LENGTH (48)
138 * @def SHA256_MAC_KEY_LENGTH
139 * @brief MAC key length for SHA256 cipher suites
141 #define SHA256_MAC_KEY_LENGTH (32)
143 * @def CCM_MAC_KEY_LENGTH
144 * @brief MAC key length for CCM cipher suites
146 #define CCM_MAC_KEY_LENGTH (0)
148 * @def AES256_KEY_LENGTH
149 * @brief key material length for AES256 cipher suites
151 #define AES256_KEY_LENGTH (32)
153 * @def AES128_KEY_LENGTH
154 * @brief key material length for AES128 cipher suites
156 #define AES128_KEY_LENGTH (16)
159 * @brief length of nonce for GCM cipher suites
161 #define GCM_IV_LENGTH (12)
164 * @brief length of nonce for CCM cipher suites
166 #define CCM_IV_LENGTH (4)
169 * @brief length of nonce for CBC cipher suites
171 #define CBC_IV_LENGTH (0)
174 * @var RETRANSMISSION_TIME
175 * @brief Maximum timeout value (in seconds) to start DTLS retransmission.
177 #define RETRANSMISSION_TIME 1
179 /**@def SSL_CLOSE_NOTIFY(peer, ret)
181 * Notifies of existing \a peer about closing TLS connection.
183 * @param[in] peer remote peer
184 * @param[in] ret used internaly
186 #define SSL_CLOSE_NOTIFY(peer, ret) \
189 (ret) = mbedtls_ssl_close_notify(&(peer)->ssl); \
190 } while (MBEDTLS_ERR_SSL_WANT_WRITE == (ret))
192 /**@def SSL_RES(peer, status)
194 * Sets SSL result for callback.
196 * @param[in] peer remote peer
198 #define SSL_RES(peer, status) \
201 CAErrorInfo_t errorInfo; \
202 errorInfo.result = (status); \
203 g_sslCallback(&(peer)->sep.endpoint, &errorInfo); \
205 /**@def SSL_CHECK_FAIL(peer, ret, str, mutex, error, msg)
207 * Checks handshake result and send alert if needed.
209 * @param[in] peer remote peer
210 * @param[in] ret error code
211 * @param[in] str debug string
212 * @param[in] mutex ca mutex
213 * @param[in] if code does not equal to -1 returns error code
214 * @param[in] msg allert message
216 #define SSL_CHECK_FAIL(peer, ret, str, mutex, error, msg) \
217 if (0 != (ret) && MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY != (int) (ret) && \
218 MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED != (int) (ret) && \
219 MBEDTLS_ERR_SSL_WANT_READ != (int) (ret) && \
220 MBEDTLS_ERR_SSL_WANT_WRITE != (int) (ret) && \
221 MBEDTLS_ERR_SSL_NON_FATAL != (int) (ret) && \
222 MBEDTLS_SSL_ALERT_MSG_USER_CANCELED != (int) (ret) && \
223 MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION != (int) (ret) && \
224 MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT != (int) (ret) && \
225 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY != (int) (ret) && \
226 MBEDTLS_SSL_ALERT_MSG_NO_CERT != (int) (ret) && \
227 MBEDTLS_SSL_ALERT_MSG_BAD_CERT != (int) (ret) && \
228 MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT != (int) (ret) && \
229 MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED != (int) (ret) && \
230 MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED != (int) (ret) && \
231 MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN != (int) (ret) && \
232 MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK != (int) (ret) && \
233 MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME != (int) (ret) && \
234 MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY != (int) (ret) && \
235 MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL != (int) (ret)) \
237 OIC_LOG_V(ERROR, NET_SSL_TAG, "%s: -0x%x", (str), -(ret)); \
238 if ((int) MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE != (int) (ret) && \
239 (int) MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != (int) (ret)) \
241 mbedtls_ssl_send_alert_message(&(peer)->ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, (msg)); \
243 RemovePeerFromList(&(peer)->sep.endpoint); \
246 oc_mutex_unlock(g_sslContextMutex); \
248 if ((int) MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != (int)(ret)) \
250 SSL_RES((peer), CA_DTLS_AUTHENTICATION_FAILURE); \
252 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__); \
258 /**@def CONF_SSL(clientConf, serverConf, fn, ...)
260 * Calls \a fn for \a clientConf and \a serverConf.
263 #define CONF_SSL(clientConf, serverConf, fn, ...) do { \
264 fn((clientConf), __VA_ARGS__); \
265 fn((serverConf), __VA_ARGS__); \
268 /** @def CHECK_MBEDTLS_RET(f, ...)
269 * A macro that checks \a f function return code
271 * If function returns error code it goes to error processing.
273 * **IMPORTANT:** Any time CHECK_MBEDTLS_RET is used an `exit:` goto label must
274 * be present to handle error processing.
276 * @param[in] f Function to call
278 #define CHECK_MBEDTLS_RET(f, ...) do { \
279 int ret = (f)(__VA_ARGS__); \
281 OIC_LOG_V(ERROR, NET_SSL_TAG, "%s returned -0x%04x\n", __func__, -(ret)); \
287 SSL_RSA_WITH_AES_256_CBC_SHA256,
288 SSL_RSA_WITH_AES_128_GCM_SHA256,
289 SSL_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
290 SSL_ECDHE_ECDSA_WITH_AES_128_CCM_8,
291 SSL_ECDHE_ECDSA_WITH_AES_128_CCM,
292 SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
293 SSL_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
294 SSL_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
295 SSL_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
296 SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
297 SSL_ECDH_ANON_WITH_AES_128_CBC_SHA256,
303 ADAPTER_CURVE_SECP256R1,
307 static const int tlsCipher[SSL_CIPHER_MAX][2] =
309 {MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256, 0},
310 {MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, 0},
311 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
312 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, 0},
313 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, 0},
314 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 0},
315 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, 0},
316 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 0},
317 {MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, 0},
318 {MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 0},
319 {MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256, 0}
322 static int g_cipherSuitesList[SSL_CIPHER_MAX];
324 mbedtls_ecp_group_id curve[ADAPTER_CURVE_MAX][2] =
326 {MBEDTLS_ECP_DP_SECP256R1, MBEDTLS_ECP_DP_NONE}
329 static PkiInfo_t g_pkiInfo = {{NULL, 0}, {NULL, 0}, {NULL, 0}, {NULL, 0}};
336 static const CrtVerifyAlert_t crtVerifyAlerts[] = {
337 {MBEDTLS_X509_BADCERT_EXPIRED, MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED},
338 {MBEDTLS_X509_BADCERT_REVOKED, MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED},
339 {MBEDTLS_X509_BADCERT_CN_MISMATCH, MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN},
340 {MBEDTLS_X509_BADCERT_NOT_TRUSTED, MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
341 {MBEDTLS_X509_BADCRL_NOT_TRUSTED, MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
342 {MBEDTLS_X509_BADCRL_EXPIRED, MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
343 {MBEDTLS_X509_BADCERT_MISSING, MBEDTLS_SSL_ALERT_MSG_NO_CERT},
344 {MBEDTLS_X509_BADCERT_SKIP_VERIFY, MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
345 {MBEDTLS_X509_BADCERT_OTHER, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR},
346 {MBEDTLS_X509_BADCERT_FUTURE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
347 {MBEDTLS_X509_BADCRL_FUTURE, MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
348 {MBEDTLS_X509_BADCERT_KEY_USAGE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
349 {MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
350 {MBEDTLS_X509_BADCERT_NS_CERT_TYPE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
351 {MBEDTLS_X509_BADCERT_BAD_MD, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
352 {MBEDTLS_X509_BADCERT_BAD_PK, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
353 {MBEDTLS_X509_BADCERT_BAD_KEY, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
354 {MBEDTLS_X509_BADCRL_BAD_MD, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
355 {MBEDTLS_X509_BADCRL_BAD_PK, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
356 {MBEDTLS_X509_BADCRL_BAD_KEY, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
360 static int GetAlertCode(uint32_t flags)
362 const CrtVerifyAlert_t *cur;
364 for (cur = crtVerifyAlerts; cur->alert != 0 ; cur++)
366 if (flags & cur->code)
374 #if !defined(NDEBUG) || defined(TB_LOG)
376 * Pass a message to the OIC logger.
378 * @param[in] ctx opaque context for the callback
379 * @param[in] level debug level
380 * @param[in] file file name
381 * @param[in] line line number
382 * @param[in] str message
384 static void DebugSsl(void *ctx, int level, const char *file, int line, const char *str)
391 char * temp = (char*) str;
392 size_t len = strlen(temp);
393 if (1 <= len && temp[len - 1] == '\n')
395 temp[len - 1] = '\0';
398 OIC_LOG_V(DEBUG, MBED_TLS_TAG, "%s", str);
403 * structure to holds the information of cache message and address info.
405 typedef ByteArray_t SslCacheMessage_t;
409 * Data structure for holding the send and recv callbacks.
411 typedef struct TlsCallBacks
413 CAPacketReceivedCallback recvCallback; /**< Callback used to send data to upper layer. */
414 CAPacketSendCallback sendCallback; /**< Callback used to send data to socket layer. */
418 * Data structure for holding the mbedTLS interface related info.
420 typedef struct SslContext
422 u_arraylist_t *peerList; /**< peer list which holds the mapping between
423 peer id, it's n/w address and mbedTLS context. */
424 mbedtls_entropy_context entropy;
425 mbedtls_ctr_drbg_context rnd;
427 mbedtls_x509_crt crt;
428 mbedtls_pk_context pkey;
430 mbedtls_ssl_config clientTlsConf;
431 mbedtls_ssl_config serverTlsConf;
432 mbedtls_ssl_config clientDtlsConf;
433 mbedtls_ssl_config serverDtlsConf;
436 SslCallbacks_t adapterCallbacks[MAX_SUPPORTED_ADAPTERS];
437 mbedtls_x509_crl crl;
448 * @var g_caSslContext
449 * @brief global context which holds tls context and cache list information.
451 static SslContext_t * g_caSslContext = NULL;
454 * @var g_getCredentialsCallback
455 * @brief callback to get TLS credentials (same as for DTLS)
457 static CAgetPskCredentialsHandler g_getCredentialsCallback = NULL;
459 * @var g_getCerdentilTypesCallback
460 * @brief callback to get different credential types from SRM
462 static CAgetCredentialTypesHandler g_getCredentialTypesCallback = NULL;
464 * @var g_getPkixInfoCallback
466 * @brief callback to get X.509-based Public Key Infrastructure
468 static CAgetPkixInfoHandler g_getPkixInfoCallback = NULL;
471 * @var g_dtlsContextMutex
472 * @brief Mutex to synchronize access to g_caSslContext.
474 static oc_mutex g_sslContextMutex = NULL;
478 * @brief callback to deliver the TLS handshake result
480 static CAErrorCallback g_sslCallback = NULL;
483 * Data structure for holding the data to be received.
485 typedef struct SslRecBuf
492 * Data structure for holding the data related to endpoint
495 typedef struct SslEndPoint
497 mbedtls_ssl_context ssl;
498 CASecureEndpoint_t sep;
499 u_arraylist_t * cacheList;
501 uint8_t master[MASTER_SECRET_LEN];
502 uint8_t random[2*RANDOM_LEN];
504 mbedtls_ssl_cookie_ctx cookieCtx;
505 mbedtls_timing_delay_context timer;
506 #endif // __WITH_DTLS__
509 void CAsetPskCredentialsCallback(CAgetPskCredentialsHandler credCallback)
511 // TODO Does this method needs protection of tlsContextMutex?
512 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
513 g_getCredentialsCallback = credCallback;
514 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
517 void CAsetPkixInfoCallback(CAgetPkixInfoHandler infoCallback)
519 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
520 g_getPkixInfoCallback = infoCallback;
521 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
523 void CAsetCredentialTypesCallback(CAgetCredentialTypesHandler credTypesCallback)
525 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
526 g_getCredentialTypesCallback = credTypesCallback;
527 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
530 static int GetAdapterIndex(CATransportAdapter_t adapter)
538 case CA_ADAPTER_GATT_BTLE:
541 OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
548 * @param[in] tep TLS endpoint
549 * @param[in] data message
550 * @param[in] dataLen message length
552 * @return message length or -1 on error.
554 static int SendCallBack(void * tep, const unsigned char * data, size_t dataLen)
556 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
557 VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "secure endpoint is NULL", -1);
558 VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", -1);
559 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
560 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data len: %zu", dataLen);
561 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Adapter: %u", ((SslEndPoint_t * )tep)->sep.endpoint.adapter);
563 int adapterIndex = GetAdapterIndex(((SslEndPoint_t * )tep)->sep.endpoint.adapter);
564 if (0 <= adapterIndex && MAX_SUPPORTED_ADAPTERS > adapterIndex)
566 CAPacketSendCallback sendCallback = g_caSslContext->adapterCallbacks[adapterIndex].sendCallback;
567 sentLen = sendCallback(&(((SslEndPoint_t * )tep)->sep.endpoint), (const void *) data, dataLen);
568 if (sentLen != dataLen)
570 OIC_LOG_V(DEBUG, NET_SSL_TAG,
571 "Packet was partially sent - total/sent/remained bytes : %d/%d/%d",
572 sentLen, dataLen, (dataLen - sentLen));
577 OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
581 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
587 * @param[in] tep TLS endpoint
588 * @param[in] data message
589 * @param[in] dataLen message length
591 * @return read length
593 static int RecvCallBack(void * tep, unsigned char * data, size_t dataLen)
595 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
596 VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "endpoint is NULL", 0);
597 VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", 0);
599 SslRecBuf_t *recBuf = &((SslEndPoint_t *)tep)->recBuf;
600 size_t retLen = (recBuf->len > recBuf->loaded ? recBuf->len - recBuf->loaded : 0);
601 retLen = (retLen < dataLen ? retLen : dataLen);
603 if (retLen > INT_MAX)
608 memcpy(data, recBuf->buff + recBuf->loaded, retLen);
609 recBuf->loaded += retLen;
611 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
616 * Parse chain of X.509 certificates.
618 * @param[out] crt container for X.509 certificates
619 * @param[in] data buffer with X.509 certificates. Certificates may be in either in PEM
620 or DER format in a jumble, delimiting symbols does not matter.
621 * @param[in] bufLen buffer length
622 * @param[in] errNum number certificates that failed to parse
624 * @return number of successfully parsed certificates or -1 on error
626 static int ParseChain(mbedtls_x509_crt * crt, unsigned char * buf, int bufLen, int * errNum)
628 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
629 VERIFY_NON_NULL_RET(crt, NET_SSL_TAG, "Param crt is NULL" , -1);
630 VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "Param buf is NULL" , -1);
632 char pemCertHeader[] = {
633 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52,
634 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
636 char pemCertFooter[] = {
637 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49,
638 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
640 size_t pemCertHeaderLen = sizeof(pemCertHeader);
641 size_t pemCertFooterLen = sizeof(pemCertFooter);
644 unsigned char * tmp = NULL;
652 if (buf[pos] == 0x30 && buf[pos + 1] == 0x82)
654 tmp = (unsigned char *)buf + pos + 1;
655 CHECK_MBEDTLS_RET(mbedtls_asn1_get_len, &tmp, buf + bufLen, &len);
656 if (pos + len < bufLen)
658 ret = mbedtls_x509_crt_parse_der(crt, buf + pos, len + 4);
666 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse_der returned -0x%04x\n", -(ret));
671 else if ((buf + pos + pemCertHeaderLen < buf + bufLen) &&
672 (0 == memcmp(buf + pos, pemCertHeader, pemCertHeaderLen)))
674 void * endPos = NULL;
675 endPos = memmem(&(buf[pos]), bufLen - pos, pemCertFooter, pemCertFooterLen);
678 OIC_LOG(ERROR, NET_SSL_TAG, "Error: end of PEM certificate not found.");
679 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
682 len = (char*)endPos - ((char*)buf + pos) + pemCertFooterLen;
683 if (pos + len + 1 <= bufLen)
685 char con = buf[pos + len];
686 buf[pos + len] = 0x00;
687 ret = mbedtls_x509_crt_parse(crt, buf + pos, len + 1);
695 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse returned -0x%04x\n", -(ret));
697 buf[pos + len] = con;
701 unsigned char * lastCert = (unsigned char *)OICMalloc((len + 1) * sizeof(unsigned char));
702 memcpy(lastCert, buf + pos, len);
703 lastCert[len] = 0x00;
704 ret = mbedtls_x509_crt_parse(crt, lastCert, len + 1);
712 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse returned -0x%04x\n", -(ret));
723 OIC_LOG_V(DEBUG, NET_SSL_TAG, "%s successfully parsed %d certificates", __func__, count);
724 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
731 //Loads PKIX related information from SRM
732 static int InitPKIX(CATransportAdapter_t adapter)
734 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
735 VERIFY_NON_NULL_RET(g_getPkixInfoCallback, NET_SSL_TAG, "PKIX info callback is NULL", -1);
736 // load pk key, cert, trust chain and crl
737 if (g_getPkixInfoCallback)
739 g_getPkixInfoCallback(&g_pkiInfo);
742 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
744 mbedtls_x509_crt_free(&g_caSslContext->ca);
745 mbedtls_x509_crt_free(&g_caSslContext->crt);
746 mbedtls_pk_free(&g_caSslContext->pkey);
747 mbedtls_x509_crl_free(&g_caSslContext->crl);
749 mbedtls_x509_crt_init(&g_caSslContext->ca);
750 mbedtls_x509_crt_init(&g_caSslContext->crt);
751 mbedtls_pk_init(&g_caSslContext->pkey);
752 mbedtls_x509_crl_init(&g_caSslContext->crl);
754 mbedtls_ssl_config * serverConf = (adapter == CA_ADAPTER_IP ||
755 adapter == CA_ADAPTER_GATT_BTLE ?
756 &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
757 mbedtls_ssl_config * clientConf = (adapter == CA_ADAPTER_IP ||
758 adapter == CA_ADAPTER_GATT_BTLE ?
759 &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
763 int count = ParseChain(&g_caSslContext->crt, g_pkiInfo.crt.data, g_pkiInfo.crt.len, &errNum);
766 OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate chain parsing error");
771 OIC_LOG_V(WARNING, NET_SSL_TAG, "Own certificate chain parsing error: %d certs failed to parse", errNum);
774 ret = mbedtls_pk_parse_key(&g_caSslContext->pkey, g_pkiInfo.key.data, g_pkiInfo.key.len,
778 OIC_LOG(WARNING, NET_SSL_TAG, "Key parsing error");
782 ret = mbedtls_ssl_conf_own_cert(serverConf, &g_caSslContext->crt, &g_caSslContext->pkey);
785 OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate parsing error");
788 ret = mbedtls_ssl_conf_own_cert(clientConf, &g_caSslContext->crt, &g_caSslContext->pkey);
791 OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate configuration error");
796 count = ParseChain(&g_caSslContext->ca, g_pkiInfo.ca.data, g_pkiInfo.ca.len, &errNum);
799 OIC_LOG(ERROR, NET_SSL_TAG, "CA chain parsing error");
800 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
805 OIC_LOG_V(WARNING, NET_SSL_TAG, "CA chain parsing warning: %d certs failed to parse", errNum);
808 ret = mbedtls_x509_crl_parse_der(&g_caSslContext->crl, g_pkiInfo.crl.data, g_pkiInfo.crl.len);
811 OIC_LOG(WARNING, NET_SSL_TAG, "CRL parsing error");
812 CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain, &g_caSslContext->ca, NULL);
816 CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain,
817 &g_caSslContext->ca, &g_caSslContext->crl);
820 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
827 * @param[in] notUsed opaque context
828 * @param[in] ssl mbedTLS context
829 * @param[in] desc identity
830 * @param[in] descLen identity length
832 * @return 0 on success any other return value will result in a denied PSK identity
834 static int GetPskCredentialsCallback(void * notUsed, mbedtls_ssl_context * ssl,
835 const unsigned char * desc, size_t descLen)
837 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
838 VERIFY_NON_NULL_RET(g_getCredentialsCallback, NET_SSL_TAG, "Credential callback s NULL", -1);
839 VERIFY_NON_NULL_RET(ssl, NET_SSL_TAG, "ssl pointer is NULL", -1);
840 VERIFY_NON_NULL_RET(desc, NET_SSL_TAG, "desc pointer is NULL", -1);
841 if (descLen > CA_MAX_ENDPOINT_IDENTITY_LEN)
843 OIC_LOG(ERROR, NET_SSL_TAG, "desc too long!");
847 uint8_t keyBuf[PSK_LENGTH] = {0};
849 // Retrieve the credentials blob from security module
850 int ret = g_getCredentialsCallback(CA_DTLS_PSK_KEY, desc, descLen, keyBuf, PSK_LENGTH);
853 memcpy(((SslEndPoint_t *) ssl)->sep.identity.id, desc, descLen);
854 ((SslEndPoint_t *) ssl)->sep.identity.id_length = descLen;
855 OIC_LOG(DEBUG, NET_SSL_TAG, "PSK:");
856 OIC_LOG_BUFFER(DEBUG, NET_SSL_TAG, keyBuf, ret);
858 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
859 return(mbedtls_ssl_set_hs_psk(ssl, keyBuf, ret));
861 OIC_LOG_V(WARNING, NET_SSL_TAG, "Out %s", __func__);
865 * Gets session corresponding for endpoint.
867 * @param[in] peer remote address
869 * @return TLS session or NULL
871 static SslEndPoint_t *GetSslPeer(const CAEndpoint_t *peer)
873 uint32_t listIndex = 0;
874 uint32_t listLength = 0;
875 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
876 VERIFY_NON_NULL_RET(peer, NET_SSL_TAG, "TLS peer is NULL", NULL);
877 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
879 SslEndPoint_t *tep = NULL;
880 listLength = u_arraylist_length(g_caSslContext->peerList);
881 for (listIndex = 0; listIndex < listLength; listIndex++)
883 tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
889 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Compare [%s:%d] and [%s:%d] for %d adapter",
890 peer->addr, peer->port, tep->sep.endpoint.addr, tep->sep.endpoint.port,
893 if((peer->adapter == tep->sep.endpoint.adapter)
894 && (0 == strncmp(peer->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA))
895 && (peer->port == tep->sep.endpoint.port || CA_ADAPTER_GATT_BTLE == peer->adapter))
897 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
901 OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
902 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
906 #ifdef MULTIPLE_OWNER
908 * Gets CA secure endpoint info corresponding for endpoint.
910 * @param[in] peer remote address
912 * @return CASecureEndpoint or NULL
914 const CASecureEndpoint_t *GetCASecureEndpointData(const CAEndpoint_t* peer)
916 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
918 oc_mutex_lock(g_sslContextMutex);
919 if (NULL == g_caSslContext)
921 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
922 oc_mutex_unlock(g_sslContextMutex);
926 SslEndPoint_t* sslPeer = GetSslPeer(peer);
929 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
930 oc_mutex_unlock(g_sslContextMutex);
931 return &sslPeer->sep;
934 OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
935 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
936 oc_mutex_unlock(g_sslContextMutex);
942 * Deletes cached message.
944 * @param[in] msg message
946 static void DeleteCacheMessage(SslCacheMessage_t * msg)
948 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
949 VERIFY_NON_NULL_VOID(msg, NET_SSL_TAG, "msg");
954 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
957 * Deletes cached message list.
959 * @param[in] cacheList list of cached messages
961 static void DeleteCacheList(u_arraylist_t * cacheList)
963 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
964 VERIFY_NON_NULL_VOID(cacheList, NET_SSL_TAG, "cacheList");
965 uint32_t listIndex = 0;
966 uint32_t listLength = 0;
968 listLength = u_arraylist_length(cacheList);
969 for (listIndex = 0; listIndex < listLength; listIndex++)
971 SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(cacheList, listIndex);
974 DeleteCacheMessage(msg);
977 u_arraylist_free(&cacheList);
979 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
982 * Deletes endpoint with session.
984 * @param[in] tep endpoint with session info
986 static void DeleteSslEndPoint(SslEndPoint_t * tep)
988 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
989 VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "tep");
991 mbedtls_ssl_free(&tep->ssl);
993 mbedtls_ssl_cookie_free(&tep->cookieCtx);
995 DeleteCacheList(tep->cacheList);
997 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1000 * Removes endpoint session from list.
1002 * @param[in] endpoint remote address
1004 static void RemovePeerFromList(CAEndpoint_t * endpoint)
1006 VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1007 VERIFY_NON_NULL_VOID(endpoint, NET_SSL_TAG, "endpoint");
1008 uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
1009 for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
1011 SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
1016 if(0 == strncmp(endpoint->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA)
1017 && (endpoint->port == tep->sep.endpoint.port))
1019 u_arraylist_remove(g_caSslContext->peerList, listIndex);
1020 DeleteSslEndPoint(tep);
1026 * Deletes session list.
1028 static void DeletePeerList()
1030 VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1032 uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
1033 for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
1035 SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
1040 if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1045 ret = mbedtls_ssl_close_notify(&tep->ssl);
1047 while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
1049 DeleteSslEndPoint(tep);
1051 u_arraylist_free(&g_caSslContext->peerList);
1054 CAResult_t CAcloseSslConnection(const CAEndpoint_t *endpoint)
1056 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1057 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
1059 oc_mutex_lock(g_sslContextMutex);
1060 if (NULL == g_caSslContext)
1062 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1063 oc_mutex_unlock(g_sslContextMutex);
1064 return CA_STATUS_FAILED;
1066 SslEndPoint_t * tep = GetSslPeer(endpoint);
1069 OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
1070 oc_mutex_unlock(g_sslContextMutex);
1071 return CA_STATUS_FAILED;
1073 /* No error checking, the connection might be closed already */
1077 ret = mbedtls_ssl_close_notify(&tep->ssl);
1079 while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
1081 RemovePeerFromList(&tep->sep.endpoint);
1082 oc_mutex_unlock(g_sslContextMutex);
1084 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1085 return CA_STATUS_OK;
1088 void CAcloseSslConnectionAll(CATransportAdapter_t transportType)
1090 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1091 oc_mutex_lock(g_sslContextMutex);
1092 if (NULL == g_caSslContext)
1094 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1095 oc_mutex_unlock(g_sslContextMutex);
1099 uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
1100 OIC_LOG_V(DEBUG, NET_SSL_TAG,
1101 "Required transport [%d], peer count [%u]", transportType, listLength);
1102 for (uint32_t i = listLength; i > 0; i--)
1104 SslEndPoint_t *tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList, i - 1);
1109 OIC_LOG_V(DEBUG, NET_SSL_TAG, "SSL Connection [%s:%d], Transport [%d]",
1110 tep->sep.endpoint.addr, tep->sep.endpoint.port, tep->sep.endpoint.adapter);
1112 // check transport matching
1113 if (0 == (tep->sep.endpoint.adapter & transportType))
1115 OIC_LOG(DEBUG, NET_SSL_TAG, "Skip the un-matched transport session");
1119 // TODO: need to check below code after socket close is ensured.
1123 ret = mbedtls_ssl_close_notify(&tep->ssl);
1125 while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);*/
1128 u_arraylist_remove(g_caSslContext->peerList, i - 1);
1129 DeleteSslEndPoint(tep);
1131 oc_mutex_unlock(g_sslContextMutex);
1133 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1137 * Creates session for endpoint.
1139 * @param[in] endpoint remote address
1140 * @param[in] config mbedTLS configuration info
1142 * @return TLS endpoint or NULL
1144 static SslEndPoint_t * NewSslEndPoint(const CAEndpoint_t * endpoint, mbedtls_ssl_config * config)
1146 SslEndPoint_t * tep = NULL;
1147 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1148 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint", NULL);
1149 VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "config", NULL);
1150 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
1152 tep = (SslEndPoint_t *) OICCalloc(1, sizeof (SslEndPoint_t));
1155 OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1159 tep->sep.endpoint = *endpoint;
1160 tep->sep.endpoint.flags = (CATransportFlags_t)(tep->sep.endpoint.flags | CA_SECURE);
1162 if(0 != mbedtls_ssl_setup(&tep->ssl, config))
1164 OIC_LOG(ERROR, NET_SSL_TAG, "Setup failed");
1166 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1170 mbedtls_ssl_set_bio(&tep->ssl, tep, SendCallBack, RecvCallBack, NULL);
1171 if (MBEDTLS_SSL_TRANSPORT_DATAGRAM == config->transport)
1173 mbedtls_ssl_set_timer_cb(&tep->ssl, &tep->timer,
1174 mbedtls_timing_set_delay, mbedtls_timing_get_delay);
1175 if (MBEDTLS_SSL_IS_SERVER == config->endpoint)
1177 if (0 != mbedtls_ssl_cookie_setup(&tep->cookieCtx, mbedtls_ctr_drbg_random,
1178 &g_caSslContext->rnd))
1180 OIC_LOG(ERROR, NET_SSL_TAG, "Cookie setup failed!");
1182 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1185 mbedtls_ssl_conf_dtls_cookies(config, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check,
1187 if (0 != mbedtls_ssl_set_client_transport_id(&tep->ssl,
1188 (const unsigned char *) endpoint->addr, sizeof(endpoint->addr)))
1190 OIC_LOG(ERROR, NET_SSL_TAG, "Transport id setup failed!");
1192 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1197 tep->cacheList = u_arraylist_create();
1198 if (NULL == tep->cacheList)
1200 OIC_LOG(ERROR, NET_SSL_TAG, "cacheList initialization failed!");
1201 mbedtls_ssl_free(&tep->ssl);
1203 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1206 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1210 * Initializes PSK identity.
1212 * @param[out] config client/server config to be updated
1214 * @return 0 on success or -1 on error
1216 static int InitPskIdentity(mbedtls_ssl_config * config)
1218 uint8_t idBuf[UUID_LENGTH] = {0};
1219 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1220 VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "Param config is NULL" , -1);
1222 if (0 > g_getCredentialsCallback(CA_DTLS_PSK_IDENTITY, NULL, 0, idBuf, UUID_LENGTH))
1224 OIC_LOG(ERROR, NET_SSL_TAG, "Identity not found");
1225 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1228 if (0 != mbedtls_ssl_conf_psk(config, idBuf, 0, idBuf, UUID_LENGTH))
1230 OIC_LOG(ERROR, NET_SSL_TAG, "Identity initialization failed!");
1231 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1234 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1237 static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapter)
1240 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1241 VERIFY_NON_NULL_VOID(config, NET_SSL_TAG, "Invaild param");
1242 VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1243 VERIFY_NON_NULL_VOID(g_getCredentialTypesCallback, NET_SSL_TAG, "Param callback is null");
1245 g_getCredentialTypesCallback(g_caSslContext->cipherFlag);
1246 // Retrieve the PSK credential from SRM
1247 if (0 != InitPskIdentity(config))
1249 OIC_LOG(ERROR, NET_SSL_TAG, "PSK identity initialization failed!");
1252 // Retrieve the Cert credential from SRM
1253 if (true == g_caSslContext->cipherFlag[1])
1255 int ret = InitPKIX(adapter);
1258 OIC_LOG(ERROR, NET_SSL_TAG, "Failed to init X.509");
1262 memset(g_cipherSuitesList, 0, sizeof(g_cipherSuitesList));
1263 if (SSL_CIPHER_MAX != g_caSslContext->cipher)
1265 g_cipherSuitesList[index] = tlsCipher[g_caSslContext->cipher][0];
1269 if (true == g_caSslContext->cipherFlag[1])
1271 for (int i = 2; i < SSL_CIPHER_MAX - 2; i++)
1273 g_cipherSuitesList[index] = tlsCipher[i][0];
1277 if (true == g_caSslContext->cipherFlag[0])
1279 g_cipherSuitesList[index] = MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
1283 mbedtls_ssl_conf_ciphersuites(config, g_cipherSuitesList);
1285 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1288 * Initiate TLS handshake with endpoint.
1290 * @param[in] endpoint remote address
1292 * @return TLS endpoint or NULL
1294 static SslEndPoint_t * InitiateTlsHandshake(const CAEndpoint_t *endpoint)
1297 SslEndPoint_t * tep = NULL;
1299 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1300 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , NULL);
1301 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
1303 mbedtls_ssl_config * config = (endpoint->adapter == CA_ADAPTER_IP ||
1304 endpoint->adapter == CA_ADAPTER_GATT_BTLE ?
1305 &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
1306 tep = NewSslEndPoint(endpoint, config);
1309 OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1313 //Load allowed SVR suites from SVR DB
1314 SetupCipher(config, endpoint->adapter);
1316 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Add %s:%d", tep->sep.endpoint.addr, tep->sep.endpoint.port);
1317 ret = u_arraylist_add(g_caSslContext->peerList, (void *) tep);
1320 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1321 DeleteSslEndPoint(tep);
1325 while (MBEDTLS_SSL_HANDSHAKE_OVER > tep->ssl.state)
1327 ret = mbedtls_ssl_handshake_step(&tep->ssl);
1328 if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
1334 OIC_LOG(ERROR, NET_SSL_TAG, "Handshake failed due to socket error");
1335 RemovePeerFromList(&tep->sep.endpoint);
1338 SSL_CHECK_FAIL(tep, ret, "Handshake error", 0, NULL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1340 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1343 #ifdef __WITH_DTLS__
1345 * Stops DTLS retransmission.
1347 static void StopRetransmit()
1351 unregisterTimer(g_caSslContext->timerId);
1352 g_caSslContext->timerId= -1;
1356 void CAdeinitSslAdapter()
1358 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1360 VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "context is NULL");
1361 VERIFY_NON_NULL_VOID(g_sslContextMutex, NET_SSL_TAG, "context mutex is NULL");
1363 //Lock tlsContext mutex
1364 oc_mutex_lock(g_sslContextMutex);
1369 // De-initialize mbedTLS
1370 mbedtls_x509_crt_free(&g_caSslContext->crt);
1371 mbedtls_pk_free(&g_caSslContext->pkey);
1373 mbedtls_ssl_config_free(&g_caSslContext->clientTlsConf);
1374 mbedtls_ssl_config_free(&g_caSslContext->serverTlsConf);
1375 #endif // __WITH_TLS__
1376 #ifdef __WITH_DTLS__
1377 mbedtls_ssl_config_free(&g_caSslContext->clientDtlsConf);
1378 mbedtls_ssl_config_free(&g_caSslContext->serverDtlsConf);
1379 #endif // __WITH_DTLS__
1380 mbedtls_ctr_drbg_free(&g_caSslContext->rnd);
1381 mbedtls_entropy_free(&g_caSslContext->entropy);
1382 #ifdef __WITH_DTLS__
1385 // De-initialize tls Context
1386 OICFree(g_caSslContext);
1387 g_caSslContext = NULL;
1389 // Unlock tlsContext mutex and de-initialize it
1390 oc_mutex_unlock(g_sslContextMutex);
1391 oc_mutex_free(g_sslContextMutex);
1392 g_sslContextMutex = NULL;
1394 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s ", __func__);
1397 static int InitConfig(mbedtls_ssl_config * conf, int transport, int mode)
1399 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1400 VERIFY_NON_NULL_RET(conf, NET_SSL_TAG, "Param conf is NULL" , -1);
1401 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
1402 mbedtls_ssl_config_init(conf);
1403 if (mbedtls_ssl_config_defaults(conf, mode, transport, MBEDTLS_SSL_PRESET_DEFAULT) != 0)
1405 OIC_LOG(ERROR, NET_SSL_TAG, "Config initialization failed!");
1410 * Configure mbedTLS runtime options. Many options are configured at build
1411 * time, see extlibs/mbedtls/config-iotivity.h
1413 mbedtls_ssl_conf_psk_cb(conf, GetPskCredentialsCallback, NULL);
1414 mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, &g_caSslContext->rnd);
1415 mbedtls_ssl_conf_curves(conf, curve[ADAPTER_CURVE_SECP256R1]);
1416 mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1418 /* Set TLS 1.2 as the minimum allowed version. */
1419 mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
1421 #if !defined(NDEBUG) || defined(TB_LOG)
1422 mbedtls_ssl_conf_dbg(conf, DebugSsl, NULL);
1423 #if defined(MBEDTLS_DEBUG_C)
1424 mbedtls_debug_set_threshold(MBED_TLS_DEBUG_LEVEL);
1427 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1430 #ifdef __WITH_DTLS__
1432 * Starts DTLS retransmission.
1434 static int StartRetransmit()
1436 uint32_t listIndex = 0;
1437 uint32_t listLength = 0;
1438 SslEndPoint_t *tep = NULL;
1440 oc_mutex_lock(g_sslContextMutex);
1441 if (NULL == g_caSslContext)
1443 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL. Stop retransmission");
1444 oc_mutex_unlock(g_sslContextMutex);
1448 if (g_caSslContext->timerId != -1)
1450 //clear previous timer
1451 unregisterTimer(g_caSslContext->timerId);
1453 listLength = u_arraylist_length(g_caSslContext->peerList);
1454 for (listIndex = 0; listIndex < listLength; listIndex++)
1456 tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
1458 || (tep->ssl.conf && MBEDTLS_SSL_TRANSPORT_STREAM == tep->ssl.conf->transport)
1459 || MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1463 int ret = mbedtls_ssl_handshake_step(&tep->ssl);
1465 if (MBEDTLS_ERR_SSL_CONN_EOF != ret)
1468 registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, (void *) StartRetransmit);
1470 SSL_CHECK_FAIL(tep, ret, "Retransmission", 1, CA_STATUS_FAILED,
1471 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1476 registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, (void *) StartRetransmit);
1477 oc_mutex_unlock(g_sslContextMutex);
1482 CAResult_t CAinitSslAdapter()
1484 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1485 // Initialize mutex for tlsContext
1486 if (NULL == g_sslContextMutex)
1488 g_sslContextMutex = oc_mutex_new();
1489 VERIFY_NON_NULL_RET(g_sslContextMutex, NET_SSL_TAG, "malloc failed", CA_MEMORY_ALLOC_FAILED);
1493 OIC_LOG(INFO, NET_SSL_TAG, "Done already!");
1494 return CA_STATUS_OK;
1497 // Lock tlsContext mutex and create tlsContext
1498 oc_mutex_lock(g_sslContextMutex);
1499 g_caSslContext = (SslContext_t *)OICCalloc(1, sizeof(SslContext_t));
1501 if (NULL == g_caSslContext)
1503 OIC_LOG(ERROR, NET_SSL_TAG, "Context malloc failed");
1504 oc_mutex_unlock(g_sslContextMutex);
1505 oc_mutex_free(g_sslContextMutex);
1506 g_sslContextMutex = NULL;
1507 return CA_MEMORY_ALLOC_FAILED;
1511 g_caSslContext->peerList = u_arraylist_create();
1513 if(NULL == g_caSslContext->peerList)
1515 OIC_LOG(ERROR, NET_SSL_TAG, "peerList initialization failed!");
1516 OICFree(g_caSslContext);
1517 g_caSslContext = NULL;
1518 oc_mutex_unlock(g_sslContextMutex);
1519 oc_mutex_free(g_sslContextMutex);
1520 g_sslContextMutex = NULL;
1521 return CA_STATUS_FAILED;
1524 /* Initialize TLS library
1526 #if !defined(NDEBUG) || defined(TB_LOG)
1527 #ifdef MBEDTLS_VERSION_C
1528 char version[MBED_TLS_VERSION_LEN];
1529 mbedtls_version_get_string(version);
1530 OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", version);
1532 OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", MBEDTLS_VERSION_STRING);
1538 mbedtls_entropy_init(&g_caSslContext->entropy);
1539 mbedtls_ctr_drbg_init(&g_caSslContext->rnd);
1541 if(0 != mbedtls_ctr_drbg_seed(&g_caSslContext->rnd, mbedtls_entropy_func,
1542 &g_caSslContext->entropy,
1543 (const unsigned char*) PERSONALIZATION_STRING, sizeof(PERSONALIZATION_STRING)))
1545 OIC_LOG(ERROR, NET_SSL_TAG, "Seed initialization failed!");
1546 oc_mutex_unlock(g_sslContextMutex);
1547 CAdeinitSslAdapter();
1548 return CA_STATUS_FAILED;
1550 mbedtls_ctr_drbg_set_prediction_resistance(&g_caSslContext->rnd, MBEDTLS_CTR_DRBG_PR_ON);
1553 if (0 != InitConfig(&g_caSslContext->clientTlsConf,
1554 MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_CLIENT))
1556 OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
1557 oc_mutex_unlock(g_sslContextMutex);
1558 CAdeinitSslAdapter();
1559 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1560 return CA_STATUS_FAILED;
1563 if (0 != InitConfig(&g_caSslContext->serverTlsConf,
1564 MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_SERVER))
1566 OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
1567 oc_mutex_unlock(g_sslContextMutex);
1568 CAdeinitSslAdapter();
1569 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1570 return CA_STATUS_FAILED;
1572 #endif // __WITH_TLS__
1573 #ifdef __WITH_DTLS__
1574 if (0 != InitConfig(&g_caSslContext->clientDtlsConf,
1575 MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_CLIENT))
1577 OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
1578 oc_mutex_unlock(g_sslContextMutex);
1579 CAdeinitSslAdapter();
1580 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1581 return CA_STATUS_FAILED;
1584 if (0 != InitConfig(&g_caSslContext->serverDtlsConf,
1585 MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_SERVER))
1587 OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
1588 oc_mutex_unlock(g_sslContextMutex);
1589 CAdeinitSslAdapter();
1590 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1591 return CA_STATUS_FAILED;
1593 #endif // __WITH_DTLS__
1595 // set default cipher
1596 g_caSslContext->cipher = SSL_CIPHER_MAX;
1599 mbedtls_x509_crt_init(&g_caSslContext->ca);
1600 mbedtls_x509_crt_init(&g_caSslContext->crt);
1601 mbedtls_pk_init(&g_caSslContext->pkey);
1602 mbedtls_x509_crl_init(&g_caSslContext->crl);
1604 #ifdef __WITH_DTLS__
1605 g_caSslContext->timerId = -1;
1608 oc_mutex_unlock(g_sslContextMutex);
1609 #ifdef __WITH_DTLS__
1613 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1614 return CA_STATUS_OK;
1617 SslCacheMessage_t * NewCacheMessage(uint8_t * data, size_t dataLen)
1619 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1620 VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , NULL);
1623 OIC_LOG(ERROR, NET_SSL_TAG, "dataLen is equal to zero");
1624 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1627 SslCacheMessage_t * message = (SslCacheMessage_t *) OICCalloc(1, sizeof(SslCacheMessage_t));
1628 if (NULL == message)
1630 OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
1631 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1635 message->data = (uint8_t *)OICCalloc(dataLen, sizeof(uint8_t));
1636 if (NULL == message->data)
1638 OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
1640 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1643 memcpy(message->data, data, dataLen);
1644 message->len = dataLen;
1645 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1649 /* Send data via TLS connection.
1651 CAResult_t CAencryptSsl(const CAEndpoint_t *endpoint,
1652 void *data, uint32_t dataLen)
1656 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s ", __func__);
1658 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG,"Remote address is NULL", CA_STATUS_INVALID_PARAM);
1659 VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Data is NULL", CA_STATUS_INVALID_PARAM);
1660 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Port %d", endpoint->port);
1664 OIC_LOG_V(ERROR, NET_SSL_TAG, "dataLen is zero [%d]", dataLen);
1665 return CA_STATUS_FAILED;
1668 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data to be encrypted dataLen [%d]", dataLen);
1670 oc_mutex_lock(g_sslContextMutex);
1671 if(NULL == g_caSslContext)
1673 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1674 oc_mutex_unlock(g_sslContextMutex);
1675 return CA_STATUS_FAILED;
1678 SslEndPoint_t * tep = GetSslPeer(endpoint);
1681 tep = InitiateTlsHandshake(endpoint);
1685 OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
1686 oc_mutex_unlock(g_sslContextMutex);
1687 return CA_STATUS_FAILED;
1690 if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1692 unsigned char *dataBuf = (unsigned char *)data;
1697 ret = mbedtls_ssl_write(&tep->ssl, dataBuf, dataLen - written);
1700 if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
1702 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned 0x%x", -ret);
1703 RemovePeerFromList(&tep->sep.endpoint);
1704 oc_mutex_unlock(g_sslContextMutex);
1705 return CA_STATUS_FAILED;
1709 OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
1713 } while (dataLen > written);
1718 SslCacheMessage_t * msg = NewCacheMessage((uint8_t*) data, dataLen);
1719 if (NULL == msg || !u_arraylist_add(tep->cacheList, (void *) msg))
1721 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1722 oc_mutex_unlock(g_sslContextMutex);
1723 return CA_STATUS_FAILED;
1727 oc_mutex_unlock(g_sslContextMutex);
1729 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1730 return CA_STATUS_OK;
1733 * Sends cached messages via TLS connection.
1735 * @param[in] tep remote address with session info
1737 static void SendCacheMessages(SslEndPoint_t * tep)
1739 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1740 VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "Param tep is NULL");
1742 uint32_t listIndex = 0;
1743 uint32_t listLength = 0;
1744 listLength = u_arraylist_length(tep->cacheList);
1745 for (listIndex = 0; listIndex < listLength;)
1748 SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(tep->cacheList, listIndex);
1749 if (NULL != msg && NULL != msg->data && 0 != msg->len)
1751 unsigned char *dataBuf = (unsigned char *)msg->data;
1756 ret = mbedtls_ssl_write(&tep->ssl, dataBuf, msg->len - written);
1759 if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
1761 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned -0x%x", -ret);
1766 OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
1770 } while (msg->len > written);
1772 if (u_arraylist_remove(tep->cacheList, listIndex))
1774 DeleteCacheMessage(msg);
1775 // Reduce list length by 1 as we removed one element.
1780 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_remove failed.");
1786 // Move to the next element
1790 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1793 void CAsetSslHandshakeCallback(CAErrorCallback tlsHandshakeCallback)
1795 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1796 g_sslCallback = tlsHandshakeCallback;
1797 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1800 /* Read data from TLS connection
1802 CAResult_t CAdecryptSsl(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t dataLen)
1805 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1806 VERIFY_NON_NULL_RET(sep, NET_SSL_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
1807 VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , CA_STATUS_INVALID_PARAM);
1809 oc_mutex_lock(g_sslContextMutex);
1810 if (NULL == g_caSslContext)
1812 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1813 oc_mutex_unlock(g_sslContextMutex);
1814 return CA_STATUS_FAILED;
1818 SslEndPoint_t * peer = GetSslPeer(&sep->endpoint);
1821 mbedtls_ssl_config * config = (sep->endpoint.adapter == CA_ADAPTER_IP ||
1822 sep->endpoint.adapter == CA_ADAPTER_GATT_BTLE ?
1823 &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
1824 peer = NewSslEndPoint(&sep->endpoint, config);
1827 OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1828 oc_mutex_unlock(g_sslContextMutex);
1829 return CA_STATUS_FAILED;
1831 //Load allowed TLS suites from SVR DB
1832 SetupCipher(config, sep->endpoint.adapter);
1834 ret = u_arraylist_add(g_caSslContext->peerList, (void *) peer);
1837 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1839 oc_mutex_unlock(g_sslContextMutex);
1840 return CA_STATUS_FAILED;
1844 peer->recBuf.buff = data;
1845 peer->recBuf.len = dataLen;
1846 peer->recBuf.loaded = 0;
1848 while (MBEDTLS_SSL_HANDSHAKE_OVER != peer->ssl.state)
1850 ret = mbedtls_ssl_handshake_step(&peer->ssl);
1851 if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
1856 if (MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED == ret)
1858 OIC_LOG(DEBUG, NET_SSL_TAG, "Hello verification requested");
1859 mbedtls_ssl_session_reset(&peer->ssl);
1860 mbedtls_ssl_set_client_transport_id(&peer->ssl,
1861 (const unsigned char *) sep->endpoint.addr,
1862 sizeof(sep->endpoint.addr));
1863 ret = mbedtls_ssl_handshake_step(&peer->ssl);
1865 uint32_t flags = mbedtls_ssl_get_verify_result(&peer->ssl);
1868 OIC_LOG_BUFFER(ERROR, NET_SSL_TAG, (const uint8_t *) &flags, sizeof(flags));
1869 SSL_CHECK_FAIL(peer, flags, "Cert verification failed", 1,
1870 CA_STATUS_FAILED, GetAlertCode(flags));
1872 SSL_CHECK_FAIL(peer, ret, "Handshake error", 1, CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1873 if (MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC == peer->ssl.state)
1875 memcpy(peer->master, peer->ssl.session_negotiate->master, sizeof(peer->master));
1876 g_caSslContext->selectedCipher = peer->ssl.session_negotiate->ciphersuite;
1878 if (MBEDTLS_SSL_CLIENT_KEY_EXCHANGE == peer->ssl.state)
1880 memcpy(peer->random, peer->ssl.handshake->randbytes, sizeof(peer->random));
1883 if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
1885 SSL_RES(peer, CA_STATUS_OK);
1886 if (MBEDTLS_SSL_IS_CLIENT == peer->ssl.conf->endpoint)
1888 SendCacheMessages(peer);
1891 int selectedCipher = peer->ssl.session->ciphersuite;
1892 OIC_LOG_V(DEBUG, NET_SSL_TAG, "(D)TLS Session is connected via ciphersuite [0x%x]", selectedCipher);
1893 if (MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 != selectedCipher &&
1894 MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 != selectedCipher)
1896 char uuid[UUID_LENGTH * 2 + 5] = {0};
1897 void * uuidPos = NULL;
1898 void * userIdPos = NULL;
1899 const mbedtls_x509_crt * peerCert = mbedtls_ssl_get_peer_cert(&peer->ssl);
1900 ret = (NULL == peerCert ? -1 : 0);
1901 SSL_CHECK_FAIL(peer, ret, "Failed to retrieve cert", 1,
1902 CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_NO_CERT);
1903 uuidPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
1904 UUID_PREFIX, sizeof(UUID_PREFIX) - 1);
1906 if (NULL != uuidPos)
1908 memcpy(uuid, (char*) uuidPos + sizeof(UUID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
1909 OIC_LOG_V(DEBUG, NET_SSL_TAG, "certificate uuid string: %s" , uuid);
1910 ret = (OCConvertStringToUuid(uuid, peer->sep.identity.id)) ? 0 : -1;
1911 SSL_CHECK_FAIL(peer, ret, "Failed to convert subject", 1,
1912 CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
1916 OIC_LOG(WARNING, NET_SSL_TAG, "uuid not found");
1919 userIdPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
1920 USERID_PREFIX, sizeof(USERID_PREFIX) - 1);
1921 if (NULL != userIdPos)
1923 memcpy(uuid, (char*) userIdPos + sizeof(USERID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
1924 ret = (OCConvertStringToUuid(uuid, peer->sep.userId.id)) ? 0 : -1;
1925 SSL_CHECK_FAIL(peer, ret, "Failed to convert subject alt name", 1,
1926 CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
1930 OIC_LOG(WARNING, NET_SSL_TAG, "Subject alternative name not found");
1934 oc_mutex_unlock(g_sslContextMutex);
1935 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1936 return CA_STATUS_OK;
1940 if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
1942 uint8_t decryptBuffer[TLS_MSG_BUF_LEN] = {0};
1945 ret = mbedtls_ssl_read(&peer->ssl, decryptBuffer, TLS_MSG_BUF_LEN);
1946 } while (MBEDTLS_ERR_SSL_WANT_READ == ret);
1948 if (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY == ret ||
1949 // TinyDTLS sends fatal close_notify alert
1950 (MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE == ret &&
1951 MBEDTLS_SSL_ALERT_LEVEL_FATAL == peer->ssl.in_msg[0] &&
1952 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY == peer->ssl.in_msg[1]))
1954 OIC_LOG(INFO, NET_SSL_TAG, "Connection was closed gracefully");
1955 RemovePeerFromList(&peer->sep.endpoint);
1956 oc_mutex_unlock(g_sslContextMutex);
1957 return CA_STATUS_OK;
1962 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_ssl_read returned -0x%x", -ret);
1963 //SSL_RES(peer, CA_STATUS_FAILED);
1964 RemovePeerFromList(&peer->sep.endpoint);
1965 oc_mutex_unlock(g_sslContextMutex);
1966 return CA_STATUS_FAILED;
1970 int adapterIndex = GetAdapterIndex(peer->sep.endpoint.adapter);
1971 if (0 <= adapterIndex && MAX_SUPPORTED_ADAPTERS > adapterIndex)
1973 g_caSslContext->adapterCallbacks[adapterIndex].recvCallback(&peer->sep, decryptBuffer, ret);
1977 OIC_LOG(ERROR, NET_SSL_TAG, "Unsuported adapter");
1978 RemovePeerFromList(&peer->sep.endpoint);
1979 oc_mutex_unlock(g_sslContextMutex);
1980 return CA_STATUS_FAILED;
1985 oc_mutex_unlock(g_sslContextMutex);
1986 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1987 return CA_STATUS_OK;
1990 void CAsetSslAdapterCallbacks(CAPacketReceivedCallback recvCallback,
1991 CAPacketSendCallback sendCallback,
1992 CATransportAdapter_t type)
1994 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1995 VERIFY_NON_NULL_VOID(sendCallback, NET_SSL_TAG, "sendCallback is NULL");
1996 VERIFY_NON_NULL_VOID(recvCallback, NET_SSL_TAG, "recvCallback is NULL");
1997 oc_mutex_lock(g_sslContextMutex);
1998 if (NULL == g_caSslContext)
2000 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2001 oc_mutex_unlock(g_sslContextMutex);
2008 g_caSslContext->adapterCallbacks[0].recvCallback = recvCallback;
2009 g_caSslContext->adapterCallbacks[0].sendCallback = sendCallback;
2011 case CA_ADAPTER_TCP:
2012 g_caSslContext->adapterCallbacks[1].recvCallback = recvCallback;
2013 g_caSslContext->adapterCallbacks[1].sendCallback = sendCallback;
2015 case CA_ADAPTER_GATT_BTLE:
2016 g_caSslContext->adapterCallbacks[2].recvCallback = recvCallback;
2017 g_caSslContext->adapterCallbacks[2].sendCallback = sendCallback;
2020 OIC_LOG_V(ERROR, NET_SSL_TAG, "Unsupported adapter: %d", type);
2023 oc_mutex_unlock(g_sslContextMutex);
2024 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2027 * Gets index of the TLS ciphersuite in the SslCipher_t enum.
2029 * @param[in] cipher TLS chiphersuite code
2031 * @return corresponding enum
2034 static SslCipher_t GetCipherIndex(const uint32_t cipher)
2038 case MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256:
2040 return SSL_RSA_WITH_AES_256_CBC_SHA256;
2042 case MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256:
2044 return SSL_RSA_WITH_AES_128_GCM_SHA256;
2046 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
2048 return SSL_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
2050 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2052 return SSL_ECDHE_ECDSA_WITH_AES_128_CCM_8;
2054 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
2056 return SSL_ECDHE_ECDSA_WITH_AES_128_CCM;
2058 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2060 return SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256;
2062 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
2064 return SSL_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384;
2066 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
2068 return SSL_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384;
2070 case MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
2072 return SSL_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
2074 case MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
2076 return SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256;
2078 case MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256:
2080 return SSL_ECDH_ANON_WITH_AES_128_CBC_SHA256;
2084 return SSL_CIPHER_MAX;
2089 CAResult_t CAsetTlsCipherSuite(const uint32_t cipher)
2091 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2092 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL context is not initialized." , CA_STATUS_NOT_INITIALIZED);
2094 CAResult_t res = CA_STATUS_FAILED;
2095 SslCipher_t index = GetCipherIndex(cipher);
2096 if (SSL_CIPHER_MAX == index)
2098 OIC_LOG(WARNING, NET_SSL_TAG, "Unknown cipher");
2103 CONF_SSL(&g_caSslContext->clientTlsConf, &g_caSslContext->serverTlsConf,
2104 mbedtls_ssl_conf_ciphersuites, tlsCipher[index]);
2106 #ifdef __WITH_DTLS__
2107 CONF_SSL(&g_caSslContext->clientDtlsConf, &g_caSslContext->serverDtlsConf,
2108 mbedtls_ssl_conf_ciphersuites, tlsCipher[index]);
2110 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Selected cipher: 0x%x", cipher);
2112 g_caSslContext->cipher = index;
2114 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2115 return CA_STATUS_OK;
2118 CAResult_t CAinitiateSslHandshake(const CAEndpoint_t *endpoint)
2120 CAResult_t res = CA_STATUS_OK;
2121 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2122 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
2123 oc_mutex_lock(g_sslContextMutex);
2124 if (NULL == InitiateTlsHandshake(endpoint))
2126 OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
2127 res = CA_STATUS_FAILED;
2129 oc_mutex_unlock(g_sslContextMutex);
2130 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2134 * Expands the secret into blocks of data according
2135 * to the algorithm specified in section 5 of RFC 4346
2137 * This function writes upto @p bufLen bytes into the given output buffer @p buf
2139 * @param key secret key.
2140 * @param keyLen secret key length.
2141 * @param label A PRF label.
2142 * @param labelLen Actual length of @p label.
2143 * @param random1 Random seed.
2144 * @param random1Len Actual length of @p random1 (may be zero).
2145 * @param random2 Random seed.
2146 * @param random2Len Actual length of @p random2 (may be zero).
2147 * @param buf Output buffer for generated random data.
2148 * @param bufLen Maximum size of @p buf.
2150 * @return The actual number of bytes written to @p buf or @c -1 on error.
2153 static int pHash (const unsigned char *key, size_t keyLen,
2154 const unsigned char *label, size_t labelLen,
2155 const unsigned char *random1, size_t random1Len,
2156 const unsigned char *random2, size_t random2Len,
2157 unsigned char *buf, size_t bufLen)
2159 unsigned char A[RANDOM_LEN] = {0};
2160 unsigned char tmp[RANDOM_LEN] = {0};
2161 size_t dLen; /* digest length */
2162 size_t len = 0; /* result length */
2164 VERIFY_NON_NULL_RET(key, NET_SSL_TAG, "key is NULL", -1);
2165 VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", -1);
2166 VERIFY_NON_NULL_RET(random1, NET_SSL_TAG, "random1 is NULL", -1);
2167 VERIFY_NON_NULL_RET(random2, NET_SSL_TAG, "random2 is NULL", -1);
2168 VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "buf is NULL", -1);
2170 mbedtls_md_context_t hmacA;
2171 mbedtls_md_context_t hmacP;
2173 mbedtls_md_init(&hmacA);
2174 mbedtls_md_init(&hmacP);
2176 CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacA, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2177 CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacP, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2179 CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen );
2180 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, label, labelLen);
2181 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random1, random1Len);
2182 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random2, random2Len);
2183 CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2187 CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2189 while (len + dLen < bufLen)
2191 CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2192 CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2193 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2194 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2195 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2196 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2198 CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2202 memcpy(buf, tmp, dLen);
2205 CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacA);
2206 CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen);
2207 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, A, dLen);
2208 CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2211 CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2212 CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2213 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2215 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2216 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2217 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2218 CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2220 memcpy(buf, tmp, bufLen - len);
2222 mbedtls_md_free(&hmacA);
2223 mbedtls_md_free(&hmacP);
2225 // exit label required for CHECK_MBEDTLS_RET macro
2227 mbedtls_md_free(&hmacA);
2228 mbedtls_md_free(&hmacP);
2232 CAResult_t CAsslGenerateOwnerPsk(const CAEndpoint_t *endpoint,
2233 const uint8_t* label, const size_t labelLen,
2234 const uint8_t* rsrcServerDeviceId, const size_t rsrcServerDeviceIdLen,
2235 const uint8_t* provServerDeviceId, const size_t provServerDeviceIdLen,
2236 uint8_t* ownerPsk, const size_t ownerPskSize)
2238 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2239 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint is NULL", CA_STATUS_INVALID_PARAM);
2240 VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", CA_STATUS_INVALID_PARAM);
2241 VERIFY_NON_NULL_RET(rsrcServerDeviceId, NET_SSL_TAG, "rsrcId is NULL", CA_STATUS_INVALID_PARAM);
2242 VERIFY_NON_NULL_RET(provServerDeviceId, NET_SSL_TAG, "provId is NULL", CA_STATUS_INVALID_PARAM);
2243 VERIFY_NON_NULL_RET(ownerPsk, NET_SSL_TAG, "ownerPSK is NULL", CA_STATUS_INVALID_PARAM);
2245 oc_mutex_lock(g_sslContextMutex);
2246 if (NULL == g_caSslContext)
2248 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2249 oc_mutex_unlock(g_sslContextMutex);
2250 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2251 return CA_STATUS_FAILED;
2253 SslEndPoint_t * tep = GetSslPeer(endpoint);
2256 OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
2257 oc_mutex_unlock(g_sslContextMutex);
2258 return CA_STATUS_FAILED;
2261 // keyBlockLen set up according to OIC 1.1 Security Specification Section 7.3.2
2265 int keyBlockLen = 0;
2266 if (MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2267 MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2268 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2269 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher)
2271 // 2 * ( 32 + 0 + 16 ) = 96
2272 macKeyLen = SHA256_MAC_KEY_LENGTH;
2273 ivSize = CBC_IV_LENGTH;
2274 keySize = AES128_KEY_LENGTH;
2276 else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM == g_caSslContext->selectedCipher ||
2277 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caSslContext->selectedCipher)
2279 // 2 * ( 0 + 4 + 16 ) = 40
2280 macKeyLen = CCM_MAC_KEY_LENGTH;
2281 ivSize = CCM_IV_LENGTH;
2282 keySize = AES128_KEY_LENGTH;
2284 else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 == g_caSslContext->selectedCipher)
2286 // 2 * ( 32 + 12 + 16 ) = 120
2287 macKeyLen = SHA256_MAC_KEY_LENGTH;
2288 ivSize = GCM_IV_LENGTH;
2289 keySize = AES128_KEY_LENGTH;
2291 else if (MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 == g_caSslContext->selectedCipher)
2293 // 2 * ( 32 + 0 + 32 ) = 128
2294 macKeyLen = SHA256_MAC_KEY_LENGTH;
2295 ivSize = CBC_IV_LENGTH;
2296 keySize = AES256_KEY_LENGTH;
2298 else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 == g_caSslContext->selectedCipher)
2300 // 2 * ( 48 + 0 + 32 ) = 160
2301 macKeyLen = SHA384_MAC_KEY_LENGTH;
2302 ivSize = CBC_IV_LENGTH;
2303 keySize = AES256_KEY_LENGTH;
2305 else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 == g_caSslContext->selectedCipher)
2307 // 2 * ( 48 + 12 + 32 ) = 184
2308 macKeyLen = SHA384_MAC_KEY_LENGTH;
2309 ivSize = GCM_IV_LENGTH;
2310 keySize = AES256_KEY_LENGTH;
2312 else if (MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 == g_caSslContext->selectedCipher)
2314 // 2 * ( 48 + 12 + 32 ) = 184
2315 macKeyLen = SHA256_MAC_KEY_LENGTH;
2316 ivSize = GCM_IV_LENGTH;
2317 keySize = AES128_KEY_LENGTH;
2319 keyBlockLen = 2 * (macKeyLen + keySize + ivSize);
2321 uint8_t * keyblock = (uint8_t *)OICMalloc(keyBlockLen);
2322 if (NULL == keyblock)
2324 OIC_LOG(ERROR, NET_SSL_TAG, "Failed to OICMalloc for keyblock");
2325 oc_mutex_unlock(g_sslContextMutex);
2326 return CA_STATUS_FAILED;
2330 uint8_t lab[] = {0x6b, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70, 0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e};
2331 int ret = pHash(tep->master, sizeof(tep->master), lab, sizeof(lab),
2332 (tep->random) + RANDOM_LEN, RANDOM_LEN, tep->random, RANDOM_LEN,
2333 keyblock, keyBlockLen);
2336 OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
2338 oc_mutex_unlock(g_sslContextMutex);
2339 return CA_STATUS_FAILED;
2342 ret = pHash(keyblock, keyBlockLen, label, labelLen,
2343 rsrcServerDeviceId, rsrcServerDeviceIdLen,
2344 provServerDeviceId, provServerDeviceIdLen,
2345 ownerPsk, ownerPskSize);
2348 OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
2350 oc_mutex_unlock(g_sslContextMutex);
2351 return CA_STATUS_FAILED;
2355 oc_mutex_unlock(g_sslContextMutex);
2357 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2358 return CA_STATUS_OK;