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 ******************************************************************/
21 #define MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE
30 #include "ca_adapter_net_ssl.h"
32 #include "caadapterutils.h"
33 #include "cainterface.h"
34 #include "caipinterface.h"
35 #include "oic_malloc.h"
37 #include "byte_array.h"
43 // headers required for mbed TLS
44 #include "mbedtls/platform.h"
45 #include "mbedtls/ssl.h"
46 #include "mbedtls/entropy.h"
47 #include "mbedtls/ctr_drbg.h"
48 #include "mbedtls/pkcs12.h"
49 #include "mbedtls/ssl_internal.h"
50 #include "mbedtls/net.h"
52 #include "mbedtls/timing.h"
53 #include "mbedtls/ssl_cookie.h"
55 #include "pkix_interface.h"
57 #if !defined(NDEBUG) || defined(TB_LOG)
58 #include "mbedtls/debug.h"
59 #include "mbedtls/version.h"
63 #include <sys/types.h>
71 * @def MBED_TLS_VERSION_LEN
72 * @brief mbedTLS version string length
74 #define MBED_TLS_VERSION_LEN (16)
77 * @brief Seed for initialization RNG
79 #define SEED "IOTIVITY_RND"
82 * @brief uuid prefix in certificate subject field
84 #define UUID_PREFIX "uuid:"
87 * @brief userid prefix in certificate alternative subject name field
89 #define USERID_PREFIX "userid:"
93 * @brief Logging tag for module name
95 #define NET_SSL_TAG "OIC_CA_NET_SSL"
98 * @brief Logging tag for mbedTLS library
100 #define MBED_TLS_TAG "MBED_TLS"
102 * @def MMBED_TLS_DEBUG_LEVEL
103 * @brief Logging level for mbedTLS library
105 #define MBED_TLS_DEBUG_LEVEL (4)
108 * @def TLS_MSG_BUF_LEN
109 * @brief Buffer size for TLS record. A single TLS record may be up to 16384 octets in length
111 #if defined (__TIZENRT__)
112 #define TLS_MSG_BUF_LEN (2048)
114 #define TLS_MSG_BUF_LEN (16384)
119 * @brief PSK keys max length
121 #define PSK_LENGTH (256/8)
123 * @def UUID_LENGTHPSK_LENGTH
124 * @brief Identity max length
126 #define UUID_LENGTH (128/8)
129 * @brief Size of string representation RFC4122 based UUID.
130 * 32 chars for hex data and 4 '-' symbols.
132 #define UUID_STR_SIZE (36)
135 * @def MASTER_SECRET_LEN
136 * @brief TLS master secret length
138 #define MASTER_SECRET_LEN (48)
141 * @brief TLS client and server random bytes length
143 #define RANDOM_LEN (32)
145 * @def SHA384_MAC_KEY_LENGTH
146 * @brief MAC key length for SHA384 cipher suites
148 #define SHA384_MAC_KEY_LENGTH (48)
150 * @def SHA256_MAC_KEY_LENGTH
151 * @brief MAC key length for SHA256 cipher suites
153 #define SHA256_MAC_KEY_LENGTH (32)
155 * @def CCM_MAC_KEY_LENGTH
156 * @brief MAC key length for CCM cipher suites
158 #define CCM_MAC_KEY_LENGTH (0)
160 * @def AES256_KEY_LENGTH
161 * @brief key material length for AES256 cipher suites
163 #define AES256_KEY_LENGTH (32)
165 * @def AES128_KEY_LENGTH
166 * @brief key material length for AES128 cipher suites
168 #define AES128_KEY_LENGTH (16)
171 * @brief length of nonce for GCM cipher suites
173 #define GCM_IV_LENGTH (12)
176 * @brief length of nonce for CCM cipher suites
178 #define CCM_IV_LENGTH (4)
181 * @brief length of nonce for CBC cipher suites
183 #define CBC_IV_LENGTH (0)
186 * @var RETRANSMISSION_TIME
187 * @brief Maximum timeout value (in seconds) to start DTLS retransmission.
189 #define RETRANSMISSION_TIME 1
191 /**@def SSL_CLOSE_NOTIFY(peer, ret)
193 * Notifies of existing \a peer about closing TLS connection.
195 * @param[in] peer remote peer
196 * @param[in] ret used internaly
198 #define SSL_CLOSE_NOTIFY(peer, ret) \
201 (ret) = mbedtls_ssl_close_notify(&(peer)->ssl); \
202 } while (MBEDTLS_ERR_SSL_WANT_WRITE == (ret))
204 /**@def SSL_RES(peer, status)
206 * Sets SSL result for callback.
208 * @param[in] peer remote peer
210 #define SSL_RES(peer, status) \
213 CAErrorInfo_t errorInfo; \
214 errorInfo.result = (status); \
215 g_sslCallback(&(peer)->sep.endpoint, &errorInfo); \
217 /**@def SSL_CHECK_FAIL(peer, ret, str, mutex, error, msg)
219 * Checks handshake result and send alert if needed.
221 * @param[in] peer remote peer
222 * @param[in] ret error code
223 * @param[in] str debug string
224 * @param[in] mutex ca mutex
225 * @param[in] error if code does not equal to -1 returns error code
226 * @param[in] msg allert message
228 #define SSL_CHECK_FAIL(peer, ret, str, mutex, error, msg) \
229 if (0 != (ret) && MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY != (int) (ret) && \
230 MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED != (int) (ret) && \
231 MBEDTLS_ERR_SSL_WANT_READ != (int) (ret) && \
232 MBEDTLS_ERR_SSL_WANT_WRITE != (int) (ret) && \
233 MBEDTLS_ERR_SSL_NON_FATAL != (int) (ret) && \
234 MBEDTLS_SSL_ALERT_MSG_USER_CANCELED != (int) (ret) && \
235 MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION != (int) (ret) && \
236 MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT != (int) (ret) && \
237 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY != (int) (ret) && \
238 MBEDTLS_SSL_ALERT_MSG_NO_CERT != (int) (ret) && \
239 MBEDTLS_SSL_ALERT_MSG_BAD_CERT != (int) (ret) && \
240 MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT != (int) (ret) && \
241 MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED != (int) (ret) && \
242 MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED != (int) (ret) && \
243 MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN != (int) (ret) && \
244 MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK != (int) (ret) && \
245 MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME != (int) (ret) && \
246 MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY != (int) (ret) && \
247 MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL != (int) (ret)) \
249 OIC_LOG_V(ERROR, NET_SSL_TAG, "%s: -0x%x", (str), -(ret)); \
250 if ((int) MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE != (int) (ret) && \
251 (int) MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != (int) (ret)) \
253 mbedtls_ssl_send_alert_message(&(peer)->ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, (msg)); \
255 RemovePeerFromList(&(peer)->sep.endpoint); \
258 oc_mutex_unlock(g_sslContextMutex); \
260 if ((int) MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != (int)(ret)) \
262 SSL_RES((peer), CA_DTLS_AUTHENTICATION_FAILURE); \
264 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__); \
265 if (-1 != (intptr_t)error) \
271 /**@def CONF_SSL(clientConf, serverConf, fn, ...)
273 * Calls \a fn for \a clientConf and \a serverConf.
276 #define CONF_SSL(clientConf, serverConf, fn, ...) do { \
277 fn((clientConf), __VA_ARGS__); \
278 fn((serverConf), __VA_ARGS__); \
281 /** @def CHECK_MBEDTLS_RET(f, ...)
282 * A macro that checks \a f function return code
284 * If function returns error code it goes to error processing.
286 * @param[in] f Function to call
288 #define CHECK_MBEDTLS_RET(f, ...) do { \
289 int ret = (f)(__VA_ARGS__); \
291 OIC_LOG_V(ERROR, NET_SSL_TAG, "%s returned -0x%04x\n", __func__, -(ret)); \
297 SSL_RSA_WITH_AES_256_CBC_SHA256,
298 SSL_RSA_WITH_AES_128_GCM_SHA256,
299 SSL_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
300 SSL_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
301 SSL_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
302 SSL_ECDHE_ECDSA_WITH_AES_128_CCM_8,
303 SSL_ECDHE_ECDSA_WITH_AES_128_CCM,
304 SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
305 SSL_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
306 SSL_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
307 SSL_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
308 SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
309 SSL_ECDH_ANON_WITH_AES_128_CBC_SHA256,
315 ADAPTER_CURVE_SECP256R1,
319 static const int tlsCipher[SSL_CIPHER_MAX][2] =
321 {MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256, 0},
322 {MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, 0},
323 {MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
324 {MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 0},
325 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
326 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, 0},
327 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, 0},
328 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 0},
329 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, 0},
330 {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 0},
331 {MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, 0},
332 {MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 0},
333 {MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256, 0}
336 static int g_cipherSuitesList[SSL_CIPHER_MAX];
338 static int g_ssl_ordered_default_hashes[] = {
339 #if defined(MBEDTLS_SHA256_C)
343 #if defined(MBEDTLS_SHA1_C)
349 mbedtls_ecp_group_id curve[ADAPTER_CURVE_MAX][2] =
351 {MBEDTLS_ECP_DP_SECP256R1, MBEDTLS_ECP_DP_NONE}
354 static PkiInfo_t g_pkiInfo = {{NULL, 0}, {NULL, 0}, {NULL, 0}, {NULL, 0}};
361 static const CrtVerifyAlert_t crtVerifyAlerts[] = {
362 {MBEDTLS_X509_BADCERT_EXPIRED, MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED},
363 {MBEDTLS_X509_BADCERT_REVOKED, MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED},
364 {MBEDTLS_X509_BADCERT_CN_MISMATCH, MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN},
365 {MBEDTLS_X509_BADCERT_NOT_TRUSTED, MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
366 {MBEDTLS_X509_BADCRL_NOT_TRUSTED, MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
367 {MBEDTLS_X509_BADCRL_EXPIRED, MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
368 {MBEDTLS_X509_BADCERT_MISSING, MBEDTLS_SSL_ALERT_MSG_NO_CERT},
369 {MBEDTLS_X509_BADCERT_SKIP_VERIFY, MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
370 {MBEDTLS_X509_BADCERT_OTHER, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR},
371 {MBEDTLS_X509_BADCERT_FUTURE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
372 {MBEDTLS_X509_BADCRL_FUTURE, MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
373 {MBEDTLS_X509_BADCERT_KEY_USAGE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
374 {MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
375 {MBEDTLS_X509_BADCERT_NS_CERT_TYPE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
376 {MBEDTLS_X509_BADCERT_BAD_MD, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
377 {MBEDTLS_X509_BADCERT_BAD_PK, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
378 {MBEDTLS_X509_BADCERT_BAD_KEY, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
379 {MBEDTLS_X509_BADCRL_BAD_MD, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
380 {MBEDTLS_X509_BADCRL_BAD_PK, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
381 {MBEDTLS_X509_BADCRL_BAD_KEY, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
385 static int GetAlertCode(uint32_t flags)
387 const CrtVerifyAlert_t *cur;
389 for (cur = crtVerifyAlerts; cur->alert != 0 ; cur++)
391 if (flags & cur->code)
399 #if !defined(NDEBUG) || defined(TB_LOG)
401 * Pass a message to the OIC logger.
403 * @param[in] ctx opaque context for the callback
404 * @param[in] level debug level
405 * @param[in] file file name
406 * @param[in] line line number
407 * @param[in] str message
409 static void DebugSsl(void *ctx, int level, const char *file, int line, const char *str)
416 OIC_LOG_V(DEBUG, MBED_TLS_TAG, "%s", str);
420 #if defined(_WIN32) || defined (__TIZENRT__)
422 * Finds the first occurrence of the byte string s in byte string l.
425 static void * memmem(const void *l, size_t lLen, const void *s, size_t sLen)
429 const char *cl = (const char *)l;
430 const char *cs = (const char *)s;
432 if (lLen == 0 || sLen == 0)
442 return (void *)memchr(l, (int)*cs, lLen);
445 last = (char *)cl + lLen - sLen;
447 for (cur = (char *)cl; cur <= last; cur++)
449 if (cur[0] == cs[0] && memcmp(cur, cs, sLen) == 0)
458 * structure to holds the information of cache message and address info.
460 typedef ByteArray_t SslCacheMessage_t;
464 * Data structure for holding the send and recv callbacks.
466 typedef struct TlsCallBacks
468 CAPacketReceivedCallback recvCallback; /**< Callback used to send data to upper layer. */
469 CAPacketSendCallback sendCallback; /**< Callback used to send data to socket layer. */
473 * Data structure for holding the mbedTLS interface related info.
475 typedef struct SslContext
477 u_arraylist_t *peerList; /**< peer list which holds the mapping between
478 peer id, it's n/w address and mbedTLS context. */
479 mbedtls_entropy_context entropy;
480 mbedtls_ctr_drbg_context rnd;
482 mbedtls_x509_crt crt;
483 mbedtls_pk_context pkey;
485 mbedtls_ssl_config clientTlsConf;
486 mbedtls_ssl_config serverTlsConf;
487 mbedtls_ssl_config clientDtlsConf;
488 mbedtls_ssl_config serverDtlsConf;
491 SslCallbacks_t adapterCallbacks[MAX_SUPPORTED_ADAPTERS];
492 mbedtls_x509_crl crl;
497 mbedtls_ssl_cookie_ctx cookieCtx;
503 * @var g_caSslContext
504 * @brief global context which holds tls context and cache list information.
506 static SslContext_t * g_caSslContext = NULL;
508 static SslExportKeysCallback_t gTlsExportKeysCallback = NULL;
510 static SslExportKeysCallback_t gDtlsExportKeysCallback = NULL;
513 * @var g_getCredentialsCallback
514 * @brief callback to get TLS credentials (same as for DTLS)
516 static CAgetPskCredentialsHandler g_getCredentialsCallback = NULL;
518 * @var g_getCerdentilTypesCallback
519 * @brief callback to get different credential types from SRM
521 static CAgetCredentialTypesHandler g_getCredentialTypesCallback = NULL;
523 * @var g_getPkixInfoCallback
525 * @brief callback to get X.509-based Public Key Infrastructure
527 static CAgetPkixInfoHandler g_getPkixInfoCallback = NULL;
530 * Callback to inform in case of client's certificate absence
532 static CertificateVerificationCallback_t g_CertificateVerificationCallback = NULL;
535 * @var g_setupPkContextCallback
537 * @brief callback to setup PK context handler for H/W based Public Key Infrastructure
539 static CAsetupPkContextHandler g_setupPkContextCallback = NULL;
542 * @var g_dtlsContextMutex
543 * @brief Mutex to synchronize access to g_caSslContext.
545 static oc_mutex g_sslContextMutex = NULL;
549 * @brief callback to deliver the TLS handshake result
551 static CAErrorCallback g_sslCallback = NULL;
554 * Data structure for PeerCertCallback.
560 } PeerCertCallback_t;
563 * @var g_peerCertCallback
565 * @brief callback to utilize peer certificate information
567 static PeerCertCallback_t g_peerCertCallback = {NULL, NULL};
570 * @var g_decryptBuffer
571 * @brief decrypt buffer which will be used for decryption
573 static uint8_t *g_decryptBuffer = NULL;
576 * Data structure for holding the data to be received.
578 typedef struct SslRecBuf
585 * Data structure for holding the data related to endpoint
588 typedef struct SslEndPoint
590 mbedtls_ssl_context ssl;
591 CASecureEndpoint_t sep;
592 u_arraylist_t * cacheList;
594 uint8_t master[MASTER_SECRET_LEN];
595 uint8_t random[2*RANDOM_LEN];
597 mbedtls_timing_delay_context timer;
598 #endif // __WITH_DTLS__
601 void CAsetPskCredentialsCallback(CAgetPskCredentialsHandler credCallback)
603 // TODO Does this method needs protection of tlsContextMutex?
604 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
605 g_getCredentialsCallback = credCallback;
606 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
609 void CAsetPkixInfoCallback(CAgetPkixInfoHandler infoCallback)
611 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
612 g_getPkixInfoCallback = infoCallback;
613 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
616 void CAsetSetupPkContextCallback(CAsetupPkContextHandler setupPkCtxCallback)
618 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
619 g_setupPkContextCallback = setupPkCtxCallback;
620 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
623 void CAsetCredentialTypesCallback(CAgetCredentialTypesHandler credTypesCallback)
625 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
626 g_getCredentialTypesCallback = credTypesCallback;
627 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
630 void CAsetCertificateVerificationCallback(CertificateVerificationCallback_t certVerifyStatusCallback)
632 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
633 g_CertificateVerificationCallback = certVerifyStatusCallback;
634 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
637 void CAunsetCertificateVerificationCallback()
639 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
640 g_CertificateVerificationCallback = NULL;
641 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
644 static int GetAdapterIndex(CATransportAdapter_t adapter)
652 case CA_ADAPTER_GATT_BTLE:
655 OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
662 * @param[in] tep TLS endpoint
663 * @param[in] data message
664 * @param[in] dataLen message length
666 * @return message length or -1 on error.
668 static int SendCallBack(void * tep, const unsigned char * data, size_t dataLen)
670 OIC_LOG_V(INFO, NET_SSL_TAG, "In %s", __func__);
671 VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "secure endpoint is NULL", -1);
672 VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", -1);
673 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
674 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data len: %zu", dataLen);
675 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Adapter: %u", ((SslEndPoint_t * )tep)->sep.endpoint.adapter);
677 int adapterIndex = GetAdapterIndex(((SslEndPoint_t * )tep)->sep.endpoint.adapter);
678 if (0 <= adapterIndex && MAX_SUPPORTED_ADAPTERS > adapterIndex)
680 CAPacketSendCallback sendCallback = g_caSslContext->adapterCallbacks[adapterIndex].sendCallback;
681 sentLen = sendCallback(&(((SslEndPoint_t * )tep)->sep.endpoint), (const void *) data, dataLen);
684 OIC_LOG_V(ERROR, NET_SSL_TAG, "sendCallback() is Failed(%zd)", sentLen);
687 else if ((size_t)sentLen != dataLen)
689 OIC_LOG_V(DEBUG, NET_SSL_TAG,
690 "Packet was partially sent - total/sent/remained bytes : %zd/%zu/%zu",
691 sentLen, dataLen, (dataLen - sentLen));
696 OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
700 OIC_LOG_V(INFO, NET_SSL_TAG, "Out %s", __func__);
706 * @param[in] tep TLS endpoint
707 * @param[in] data message
708 * @param[in] dataLen message length
710 * @return read length
712 static int RecvCallBack(void * tep, unsigned char * data, size_t dataLen)
714 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
715 VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "endpoint is NULL", 0);
716 VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", 0);
718 SslRecBuf_t *recBuf = &((SslEndPoint_t *)tep)->recBuf;
719 size_t retLen = (recBuf->len > recBuf->loaded ? recBuf->len - recBuf->loaded : 0);
720 retLen = (retLen < dataLen ? retLen : dataLen);
722 memcpy(data, recBuf->buff + recBuf->loaded, retLen);
723 recBuf->loaded += retLen;
725 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
729 static int CASslExportKeysHandler(void *p_expkey,
730 const unsigned char *ms,
731 const unsigned char *kb,
736 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
738 if (NULL == g_caSslContext)
740 OIC_LOG(ERROR, NET_SSL_TAG, "SSL Context is not initialized.");
741 return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
743 if (NULL == p_expkey)
745 OIC_LOG(ERROR, NET_SSL_TAG, "Can not find the protocol information from 'p_expkey'.");
746 return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
749 CASslEkcbProtocol_t* protocol = (CASslEkcbProtocol_t*)p_expkey;
751 if (gTlsExportKeysCallback && CA_SSL_EKCB_TLS == (*protocol))
753 OIC_LOG(DEBUG, NET_SSL_TAG, "Invoking TLS export key callback.");
754 gTlsExportKeysCallback(ms, kb, maclen, keylen, ivlen);
756 else if (gDtlsExportKeysCallback && CA_SSL_EKCB_DTLS == (*protocol))
758 OIC_LOG(DEBUG, NET_SSL_TAG, "Invoking DTLS export key callback.");
759 gDtlsExportKeysCallback(ms, kb, maclen, keylen, ivlen);
763 OIC_LOG(ERROR, NET_SSL_TAG, "Failed to Invoke (D)TLS export key callback.");
764 return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
767 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
771 CAResult_t CASetSslExportKeysCallback(SslExportKeysCallback_t exportKeysCb,
772 CASslEkcbProtocol_t protocol, CASslEkcbRole_t role)
774 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
775 mbedtls_ssl_config* sslConf = NULL;
776 static CASslEkcbProtocol_t protocolCtx = CA_SSL_EKCB_TLS;
778 if (CA_SSL_EKCB_TLS != protocol && CA_SSL_EKCB_DTLS != protocol)
780 OIC_LOG(ERROR, NET_SSL_TAG, "Invaild protocol.");
781 return CA_STATUS_INVALID_PARAM;
783 if (CA_SSL_EKCB_CLIENT != role && CA_SSL_EKCB_SERVER != role)
785 OIC_LOG(ERROR, NET_SSL_TAG, "Invaild role.");
786 return CA_STATUS_INVALID_PARAM;
789 OIC_LOG_V(DEBUG, NET_SSL_TAG, "TLS Export Key Callback Type : [%s] [%s]",
790 (CA_SSL_EKCB_TLS == protocol ? "TLS" : "DTLS"),
791 (CA_SSL_EKCB_CLIENT == role ? "Client" : "Server"));
793 oc_mutex_lock(g_sslContextMutex);
794 if (NULL == g_caSslContext)
796 OIC_LOG(ERROR, NET_SSL_TAG, "SSL Context is not initialized.");
797 oc_mutex_unlock(g_sslContextMutex);
798 return CA_STATUS_NOT_INITIALIZED;
801 if (CA_SSL_EKCB_TLS == protocol)
803 gTlsExportKeysCallback = exportKeysCb;
804 if (CA_SSL_EKCB_CLIENT == role)
806 sslConf = &g_caSslContext->clientTlsConf;
810 sslConf = &g_caSslContext->serverTlsConf;
815 gDtlsExportKeysCallback = exportKeysCb;
816 if (CA_SSL_EKCB_CLIENT == role)
818 sslConf = &g_caSslContext->clientDtlsConf;
822 sslConf = &g_caSslContext->serverDtlsConf;
825 protocolCtx = protocol;
827 if (NULL == exportKeysCb)
829 mbedtls_ssl_conf_export_keys_cb(sslConf, NULL, NULL);
830 OIC_LOG(DEBUG, NET_SSL_TAG, "Export key callback unregistered.");
834 mbedtls_ssl_conf_export_keys_cb(sslConf, CASslExportKeysHandler, (void*)(&protocolCtx));
835 OIC_LOG(DEBUG, NET_SSL_TAG, "Export key callback registered.");
837 oc_mutex_unlock(g_sslContextMutex);
839 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
845 * Parse chain of X.509 certificates.
847 * @param[out] crt container for X.509 certificates
848 * @param[in] data buffer with X.509 certificates. Certificates may be in either in PEM
849 or DER format in a jumble, delimiting symbols does not matter.
850 * @param[in] bufLen buffer length
851 * @param[in] errNum number certificates that failed to parse
853 * @return number of successfully parsed certificates or -1 on error
855 static int ParseChain(mbedtls_x509_crt * crt, unsigned char * buf, size_t bufLen, int * errNum)
857 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
858 VERIFY_NON_NULL_RET(crt, NET_SSL_TAG, "Param crt is NULL" , -1);
859 VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "Param buf is NULL" , -1);
861 char pemCertHeader[] = {
862 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52,
863 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
865 char pemCertFooter[] = {
866 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49,
867 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
869 size_t pemCertHeaderLen = sizeof(pemCertHeader);
870 size_t pemCertFooterLen = sizeof(pemCertFooter);
873 unsigned char * tmp = NULL;
881 if (buf[pos] == 0x30 && buf[pos + 1] == 0x82)
883 tmp = (unsigned char *)buf + pos + 1;
884 CHECK_MBEDTLS_RET(mbedtls_asn1_get_len, &tmp, buf + bufLen, &len);
885 if (pos + len < bufLen)
887 ret = mbedtls_x509_crt_parse_der(crt, buf + pos, len + 4);
895 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse_der returned -0x%04x\n", -(ret));
900 else if ((buf + pos + pemCertHeaderLen < buf + bufLen) &&
901 (0 == memcmp(buf + pos, pemCertHeader, pemCertHeaderLen)))
903 void * endPos = NULL;
904 endPos = memmem(&(buf[pos]), bufLen - pos, pemCertFooter, pemCertFooterLen);
907 OIC_LOG(ERROR, NET_SSL_TAG, "Error: end of PEM certificate not found.");
908 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
911 len = (char*)endPos - ((char*)buf + pos) + pemCertFooterLen;
912 if (pos + len + 1 <= bufLen)
914 char con = buf[pos + len];
915 buf[pos + len] = 0x00;
916 ret = mbedtls_x509_crt_parse(crt, buf + pos, len + 1);
924 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse returned -0x%04x\n", -(ret));
926 buf[pos + len] = con;
930 unsigned char * lastCert = (unsigned char *)OICMalloc((len + 1) * sizeof(unsigned char));
931 if (lastCert == NULL)
935 memcpy(lastCert, buf + pos, len);
936 lastCert[len] = 0x00;
937 ret = mbedtls_x509_crt_parse(crt, lastCert, len + 1);
945 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse returned -0x%04x\n", -(ret));
956 OIC_LOG_V(INFO, NET_SSL_TAG, "%s successfully parsed %d certificates", __func__, count);
957 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
964 static int VerifyCertificateCallback(void *p_vrfy, mbedtls_x509_crt *crt, int depth,
968 char buf[1024] = {0};
970 if (0 != *flags) // Invalid Cerificate
973 ret = mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", *flags);
976 OIC_LOG_V(ERROR, NET_SSL_TAG, "%s(%d)", buf, *flags);
981 if (NULL == g_peerCertCallback.cb)
983 OIC_LOG(DEBUG, NET_SSL_TAG, "NOT SET g_peerCertCallback");
989 * depth = 0 : Own Cert.
990 * depth = 1 : Sub CA Cert.
991 * depth = 2 : Root CA Cert.
993 OIC_LOG_V(INFO, NET_SSL_TAG, "Depth : %d", depth);
995 mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt);
996 OIC_LOG_V(DEBUG, NET_SSL_TAG, "crt : %s", buf);
998 return g_peerCertCallback.cb(g_peerCertCallback.ctx, crt, depth);
1001 CAResult_t CAsetPeerCertCallback(void *ctx, PeerCertCallback peerCertCallback)
1003 #ifndef __WITH_DTLS__
1005 UNUSED(peerCertCallback);
1006 OIC_LOG(ERROR, NET_SSL_TAG, "Not Supported");
1007 return CA_NOT_SUPPORTED;
1010 if (peerCertCallback)
1012 OIC_LOG(DEBUG, NET_SSL_TAG, "SET peerCertCallback");
1013 g_peerCertCallback.cb = peerCertCallback;
1014 g_peerCertCallback.ctx = ctx;
1018 OIC_LOG(DEBUG, NET_SSL_TAG, "UNSET peerCertCallback");
1019 g_peerCertCallback.cb = NULL;
1020 g_peerCertCallback.ctx = NULL;
1022 return CA_STATUS_OK;
1025 //Loads PKIX related information from SRM
1026 static int InitPKIX(CATransportAdapter_t adapter)
1028 OIC_LOG_V(INFO, NET_SSL_TAG, "In %s", __func__);
1029 VERIFY_NON_NULL_RET(g_getPkixInfoCallback, NET_SSL_TAG, "PKIX info callback is NULL", -1);
1030 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
1032 mbedtls_x509_crt_free(&g_caSslContext->ca);
1033 mbedtls_x509_crt_free(&g_caSslContext->crt);
1034 mbedtls_pk_free(&g_caSslContext->pkey);
1035 mbedtls_x509_crl_free(&g_caSslContext->crl);
1037 mbedtls_x509_crt_init(&g_caSslContext->ca);
1038 mbedtls_x509_crt_init(&g_caSslContext->crt);
1039 mbedtls_pk_init(&g_caSslContext->pkey);
1040 mbedtls_x509_crl_init(&g_caSslContext->crl);
1042 mbedtls_ssl_config * serverConf = (adapter == CA_ADAPTER_IP ||
1043 adapter == CA_ADAPTER_GATT_BTLE ?
1044 &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
1045 mbedtls_ssl_config * clientConf = (adapter == CA_ADAPTER_IP ||
1046 adapter == CA_ADAPTER_GATT_BTLE ?
1047 &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
1049 #ifdef __WITH_DTLS__
1051 * Conf. is initialized in CAinitSslAdapter()
1053 mbedtls_ssl_conf_verify(&g_caSslContext->clientDtlsConf, VerifyCertificateCallback, NULL);
1056 // load pk key, cert, trust chain and crl
1057 if (g_getPkixInfoCallback)
1059 OIC_LOG(INFO, NET_SSL_TAG, "g_getPkixInfoCallback will be invoked");
1060 g_getPkixInfoCallback(&g_pkiInfo);
1063 // parse own certficate (optional)
1066 int count = ParseChain(&g_caSslContext->crt, g_pkiInfo.crt.data, g_pkiInfo.crt.len, &errNum);
1069 OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate chain parsing error");
1074 OIC_LOG_V(WARNING, NET_SSL_TAG, "Own certificate chain parsing error: %d certs failed to parse", errNum);
1078 // parse private key if hw is not supported (optional)
1079 if(NULL == g_setupPkContextCallback)
1081 OIC_LOG(INFO, NET_SSL_TAG, "g_setupPkContextCallback is NULL");
1082 ret = mbedtls_pk_parse_key(&g_caSslContext->pkey, g_pkiInfo.key.data, g_pkiInfo.key.len,
1087 OIC_LOG(INFO, NET_SSL_TAG, "g_setupPkContextCallback will be invoked");
1088 // setup hw pk context (optional)
1089 ret = g_setupPkContextCallback(&g_caSslContext->pkey);
1092 // setup public parameter
1093 mbedtls_pk_type_t ktype = mbedtls_pk_get_type(&g_caSslContext->pkey);
1094 if (MBEDTLS_PK_ECKEY == ktype || MBEDTLS_PK_ECKEY_DH == ktype
1095 || MBEDTLS_PK_ECDSA == ktype)
1097 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Copy ecp public param from cert, keytype [%d]", ktype);
1098 mbedtls_ecp_keypair *eckey = (mbedtls_ecp_keypair*)g_caSslContext->crt.pk.pk_ctx;
1099 mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context*)g_caSslContext->pkey.pk_ctx;
1102 ret = mbedtls_ecdsa_from_keypair(ecdsa, eckey);
1105 OIC_LOG_V(ERROR, NET_SSL_TAG, "Fail to copy public param [0x%x]", ret);
1110 OIC_LOG_V(WARNING, NET_SSL_TAG, "key-ctx(%p), cert-ctx(%p)", ecdsa, eckey);
1116 OIC_LOG_V(INFO, NET_SSL_TAG, "loaded key is not one of eckey type [%d]", ktype);
1121 OIC_LOG_V(ERROR, NET_SSL_TAG, "Fail to call g_setupPkContextCallback [%d]", ret);
1126 OIC_LOG(WARNING, NET_SSL_TAG, "Key parsing error");
1130 ret = mbedtls_ssl_conf_own_cert(serverConf, &g_caSslContext->crt, &g_caSslContext->pkey);
1133 OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate parsing error");
1136 ret = mbedtls_ssl_conf_own_cert(clientConf, &g_caSslContext->crt, &g_caSslContext->pkey);
1139 OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate configuration error");
1144 count = ParseChain(&g_caSslContext->ca, g_pkiInfo.ca.data, g_pkiInfo.ca.len, &errNum);
1147 OIC_LOG(WARNING, NET_SSL_TAG, "CA chain in svr db was not parsed");
1148 OIC_LOG(WARNING, NET_SSL_TAG, " but if working as server, chain not required");
1149 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1154 OIC_LOG_V(WARNING, NET_SSL_TAG, "CA chain parsing warning: %d certs failed to parse", errNum);
1157 ret = mbedtls_x509_crl_parse_der(&g_caSslContext->crl, g_pkiInfo.crl.data, g_pkiInfo.crl.len);
1160 OIC_LOG(WARNING, NET_SSL_TAG, "CRL in svr db was not parsed");
1161 CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain, &g_caSslContext->ca, NULL);
1165 CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain,
1166 &g_caSslContext->ca, &g_caSslContext->crl);
1169 OIC_LOG_V(INFO, NET_SSL_TAG, "Out %s", __func__);
1176 * @param[in] notUsed opaque context
1177 * @param[in] ssl mbedTLS context
1178 * @param[in] desc identity
1179 * @param[in] descLen identity length
1181 * @return 0 on success any other return value will result in a denied PSK identity
1183 static int GetPskCredentialsCallback(void * notUsed, mbedtls_ssl_context * ssl,
1184 const unsigned char * desc, size_t descLen)
1186 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1187 VERIFY_NON_NULL_RET(g_getCredentialsCallback, NET_SSL_TAG, "Credential callback s NULL", -1);
1188 VERIFY_NON_NULL_RET(ssl, NET_SSL_TAG, "ssl pointer is NULL", -1);
1189 VERIFY_NON_NULL_RET(desc, NET_SSL_TAG, "desc pointer is NULL", -1);
1190 if (descLen > CA_MAX_ENDPOINT_IDENTITY_LEN)
1192 OIC_LOG(ERROR, NET_SSL_TAG, "desc too long!");
1196 uint8_t keyBuf[PSK_LENGTH] = {0};
1198 // Retrieve the credentials blob from security module
1199 int ret = g_getCredentialsCallback(CA_DTLS_PSK_KEY, desc, descLen, keyBuf, PSK_LENGTH);
1202 memcpy(((SslEndPoint_t *) ssl)->sep.identity.id, desc, descLen);
1203 ((SslEndPoint_t *) ssl)->sep.identity.id_length = descLen;
1204 OIC_LOG(DEBUG, NET_SSL_TAG, "PSK:");
1205 OIC_LOG_BUFFER(DEBUG, NET_SSL_TAG, keyBuf, ret);
1207 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1208 return(mbedtls_ssl_set_hs_psk(ssl, keyBuf, ret));
1210 OIC_LOG_V(WARNING, NET_SSL_TAG, "Out %s", __func__);
1215 * Gets session corresponding for endpoint.
1217 * @param[in] peer remote address
1219 * @return TLS session or NULL
1221 static SslEndPoint_t *GetSslPeer(const CAEndpoint_t *peer)
1223 uint32_t listIndex = 0;
1224 uint32_t listLength = 0;
1225 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1226 VERIFY_NON_NULL_RET(peer, NET_SSL_TAG, "TLS peer is NULL", NULL);
1227 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
1229 SslEndPoint_t *tep = NULL;
1230 listLength = u_arraylist_length(g_caSslContext->peerList);
1231 for (listIndex = 0; listIndex < listLength; listIndex++)
1233 tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
1239 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Compare [%s:%d] and [%s:%d] for %d adapter",
1240 peer->addr, peer->port, tep->sep.endpoint.addr, tep->sep.endpoint.port,
1243 if((peer->adapter == tep->sep.endpoint.adapter)
1244 && (0 == strncmp(peer->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA))
1245 && (peer->port == tep->sep.endpoint.port || CA_ADAPTER_GATT_BTLE == peer->adapter))
1247 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Found Peer:[%s:%d] for %d adapter",
1248 peer->addr, peer->port, peer->adapter);
1249 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1253 OIC_LOG_V(INFO, NET_SSL_TAG, "Peer not found:[%s:%d] for %d adapter",
1254 peer->addr, peer->port, peer->adapter);
1255 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1259 bool CAIsExistSslPeer(const CAEndpoint_t *peer)
1261 oc_mutex_lock(g_sslContextMutex);
1262 if (NULL == g_caSslContext)
1264 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1265 oc_mutex_unlock(g_sslContextMutex);
1269 if (GetSslPeer(peer))
1271 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Exist Peer");
1272 oc_mutex_unlock(g_sslContextMutex);
1277 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Not Exist Peer");
1278 oc_mutex_unlock(g_sslContextMutex);
1284 * Gets session corresponding for endpoint.
1286 * @param[in] peer remote address
1288 * @return TLS session or NULL
1290 static SslEndPoint_t *GetSslPeerUsingUuid(const uint8_t *identity, size_t idLength)
1292 uint32_t listIndex = 0;
1293 uint32_t listLength = 0;
1294 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1295 VERIFY_NON_NULL_RET(identity, NET_SSL_TAG, "Param identity is NULL", NULL);
1296 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
1298 OIC_LOG(INFO, NET_SSL_TAG, "[Target UUID]");
1299 OIC_LOG_BUFFER(INFO, NET_SSL_TAG, identity, idLength);
1301 SslEndPoint_t *tep = NULL;
1302 listLength = u_arraylist_length(g_caSslContext->peerList);
1303 for (listIndex = 0; listIndex < listLength; listIndex++)
1305 tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
1311 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Compare UUID for [%s:%d]",
1312 tep->sep.endpoint.addr, tep->sep.endpoint.port);
1314 if ((tep->sep.identity.id_length == idLength)
1315 && (0 == memcmp(identity, tep->sep.identity.id, idLength)))
1317 OIC_LOG_V(INFO, NET_SSL_TAG, "Found matched UUID in [%s:%d]",
1318 tep->sep.endpoint.addr, tep->sep.endpoint.port);
1319 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1323 OIC_LOG(INFO, NET_SSL_TAG, "Peer not found");
1324 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1329 #ifdef MULTIPLE_OWNER
1331 * Gets CA secure endpoint info corresponding for endpoint.
1333 * @param[in] peer remote address
1335 * @return CASecureEndpoint or NULL
1337 const CASecureEndpoint_t *GetCASecureEndpointData(const CAEndpoint_t* peer)
1339 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1341 // TODO: Added as workaround, need to debug
1342 oc_mutex_unlock(g_sslContextMutex);
1344 oc_mutex_lock(g_sslContextMutex);
1345 if (NULL == g_caSslContext)
1347 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1348 oc_mutex_unlock(g_sslContextMutex);
1352 SslEndPoint_t* sslPeer = GetSslPeer(peer);
1355 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1356 oc_mutex_unlock(g_sslContextMutex);
1357 return &sslPeer->sep;
1360 OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
1361 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1362 oc_mutex_unlock(g_sslContextMutex);
1367 CAResult_t SetCASecureEndpointUuid(const CAEndpoint_t *peer, const char *uuid)
1369 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1370 VERIFY_NON_NULL(peer, NET_SSL_TAG, "peer");
1371 VERIFY_NON_NULL(peer, NET_SSL_TAG, "uuid");
1373 oc_mutex_lock(g_sslContextMutex);
1374 SslEndPoint_t *sslPeer = GetSslPeer(peer);
1375 if (NULL == sslPeer)
1377 OIC_LOG(ERROR, NET_SSL_TAG, "Peer not found");
1378 oc_mutex_unlock(g_sslContextMutex);
1379 return CA_STATUS_FAILED;
1382 OCRandomUuidResult ret = OCConvertStringToUuid(uuid, sslPeer->sep.identity.id);
1383 oc_mutex_unlock(g_sslContextMutex);
1385 if (RAND_UUID_OK != ret)
1387 OIC_LOG(ERROR, NET_SSL_TAG, "Failed to convert uuid");
1388 return CA_STATUS_FAILED;
1391 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1393 return CA_STATUS_OK;
1397 * Deletes cached message.
1399 * @param[in] msg message
1401 static void DeleteCacheMessage(SslCacheMessage_t * msg)
1403 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1404 VERIFY_NON_NULL_VOID(msg, NET_SSL_TAG, "msg");
1409 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1412 * Deletes cached message list.
1414 * @param[in] cacheList list of cached messages
1416 static void DeleteCacheList(u_arraylist_t * cacheList)
1418 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1419 VERIFY_NON_NULL_VOID(cacheList, NET_SSL_TAG, "cacheList");
1420 uint32_t listIndex = 0;
1421 uint32_t listLength = 0;
1423 listLength = u_arraylist_length(cacheList);
1424 for (listIndex = 0; listIndex < listLength; listIndex++)
1426 SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(cacheList, listIndex);
1429 DeleteCacheMessage(msg);
1432 u_arraylist_free(&cacheList);
1434 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1437 * Deletes endpoint with session.
1439 * @param[in] tep endpoint with session info
1441 static void DeleteSslEndPoint(SslEndPoint_t * tep)
1443 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1444 VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "tep");
1446 mbedtls_ssl_free(&tep->ssl);
1447 DeleteCacheList(tep->cacheList);
1449 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1452 * Removes endpoint session from list.
1454 * @param[in] endpoint remote address
1456 static void RemovePeerFromList(const CAEndpoint_t * endpoint)
1458 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1459 VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1460 VERIFY_NON_NULL_VOID(endpoint, NET_SSL_TAG, "endpoint");
1461 uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
1462 for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
1464 SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
1469 if(0 == strncmp(endpoint->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA)
1470 && (endpoint->port == tep->sep.endpoint.port || CA_ADAPTER_GATT_BTLE == endpoint->adapter))
1472 u_arraylist_remove(g_caSslContext->peerList, listIndex);
1473 OIC_LOG_V(INFO, NET_SSL_TAG, "Remove Peer:[%s:%d] for %d adapter",
1474 endpoint->addr, endpoint->port, endpoint->adapter);
1475 DeleteSslEndPoint(tep);
1476 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1480 OIC_LOG_V(INFO, NET_SSL_TAG, "Peer not found:[%s:%d] for %d adapter",
1481 endpoint->addr, endpoint->port, endpoint->adapter);
1482 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1485 * Deletes session list.
1487 static void DeletePeerList()
1489 OIC_LOG_V(DEBUG, NET_SSL_TAG, "%s", __func__);
1490 VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1492 uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
1493 for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
1495 SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
1500 if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1505 ret = mbedtls_ssl_close_notify(&tep->ssl);
1507 while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
1509 DeleteSslEndPoint(tep);
1511 u_arraylist_free(&g_caSslContext->peerList);
1514 CAResult_t CAcloseSslConnection(const CAEndpoint_t *endpoint)
1516 OIC_LOG_V(INFO, NET_SSL_TAG, "In %s", __func__);
1517 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
1519 oc_mutex_lock(g_sslContextMutex);
1520 if (NULL == g_caSslContext)
1522 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1523 oc_mutex_unlock(g_sslContextMutex);
1524 return CA_STATUS_FAILED;
1526 SslEndPoint_t * tep = GetSslPeer(endpoint);
1529 OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
1530 oc_mutex_unlock(g_sslContextMutex);
1531 return CA_STATUS_FAILED;
1533 /* No error checking, the connection might be closed already */
1537 ret = mbedtls_ssl_close_notify(&tep->ssl);
1539 while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
1541 RemovePeerFromList(&tep->sep.endpoint);
1542 oc_mutex_unlock(g_sslContextMutex);
1544 OIC_LOG_V(INFO, NET_SSL_TAG, "Out %s", __func__);
1545 return CA_STATUS_OK;
1549 CAResult_t CAcloseSslConnectionFreeEndpoint(CAEndpoint_t *endpoint)
1551 OIC_LOG_V(INFO, NET_SSL_TAG, "In %s", __func__);
1552 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
1554 CAResult_t ret = CAcloseSslConnection(endpoint);
1557 OIC_LOG_V(INFO, NET_SSL_TAG, "Out %s", __func__);
1562 CAResult_t CAcloseSslConnectionUsingUuid(const uint8_t *identity, size_t idLength)
1564 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1565 VERIFY_NON_NULL_RET(identity, NET_SSL_TAG, "Param identity is NULL" , CA_STATUS_INVALID_PARAM);
1567 oc_mutex_lock(g_sslContextMutex);
1568 if (NULL == g_caSslContext)
1570 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1571 oc_mutex_unlock(g_sslContextMutex);
1572 return CA_STATUS_FAILED;
1575 SslEndPoint_t* tep = GetSslPeerUsingUuid(identity, idLength);
1578 OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
1579 oc_mutex_unlock(g_sslContextMutex);
1580 return CA_STATUS_FAILED;
1583 /* No error checking, the connection might be closed already */
1587 ret = mbedtls_ssl_close_notify(&tep->ssl);
1589 while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
1591 RemovePeerFromList(&tep->sep.endpoint);
1592 oc_mutex_unlock(g_sslContextMutex);
1594 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1595 return CA_STATUS_OK;
1598 void CAcloseSslConnectionAll(CATransportAdapter_t transportType)
1600 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1601 oc_mutex_lock(g_sslContextMutex);
1602 if (NULL == g_caSslContext)
1604 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1605 oc_mutex_unlock(g_sslContextMutex);
1609 uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
1610 OIC_LOG_V(INFO, NET_SSL_TAG,
1611 "Required transport [%d], peer count [%d]", transportType, listLength);
1612 for (uint32_t i = listLength; i > 0; i--)
1614 SslEndPoint_t *tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList, i - 1);
1619 OIC_LOG_V(INFO, NET_SSL_TAG, "SSL Connection [%s:%d], Transport [%d]",
1620 tep->sep.endpoint.addr, tep->sep.endpoint.port, tep->sep.endpoint.adapter);
1622 // check transport matching
1623 if (0 == (tep->sep.endpoint.adapter & transportType))
1625 OIC_LOG(DEBUG, NET_SSL_TAG, "Skip the un-matched transport session");
1629 // TODO: need to check below code after socket close is ensured.
1633 ret = mbedtls_ssl_close_notify(&tep->ssl);
1635 while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);*/
1638 u_arraylist_remove(g_caSslContext->peerList, i - 1);
1639 DeleteSslEndPoint(tep);
1641 oc_mutex_unlock(g_sslContextMutex);
1643 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1647 * Creates session for endpoint.
1649 * @param[in] endpoint remote address
1650 * @param[in] config mbedTLS configuration info
1652 * @return TLS endpoint or NULL
1654 static SslEndPoint_t * NewSslEndPoint(const CAEndpoint_t * endpoint, mbedtls_ssl_config * config)
1656 SslEndPoint_t * tep = NULL;
1657 OIC_LOG_V(INFO, NET_SSL_TAG, "In %s", __func__);
1658 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint", NULL);
1659 VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "config", NULL);
1660 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
1662 tep = (SslEndPoint_t *) OICCalloc(1, sizeof (SslEndPoint_t));
1665 OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1669 tep->sep.endpoint = *endpoint;
1670 tep->sep.endpoint.flags = (CATransportFlags_t)(tep->sep.endpoint.flags | CA_SECURE);
1672 if(0 != mbedtls_ssl_setup(&tep->ssl, config))
1674 OIC_LOG(ERROR, NET_SSL_TAG, "Setup failed");
1676 OIC_LOG_V(INFO, NET_SSL_TAG, "Out %s", __func__);
1680 mbedtls_ssl_set_bio(&tep->ssl, tep, SendCallBack, RecvCallBack, NULL);
1681 if (MBEDTLS_SSL_TRANSPORT_DATAGRAM == config->transport)
1683 mbedtls_ssl_set_timer_cb(&tep->ssl, &tep->timer,
1684 mbedtls_timing_set_delay, mbedtls_timing_get_delay);
1685 if (MBEDTLS_SSL_IS_SERVER == config->endpoint)
1687 if (0 != mbedtls_ssl_set_client_transport_id(&tep->ssl,
1688 (const unsigned char *) endpoint->addr, sizeof(endpoint->addr)))
1690 OIC_LOG(ERROR, NET_SSL_TAG, "Transport id setup failed!");
1691 mbedtls_ssl_free(&tep->ssl);
1693 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1698 tep->cacheList = u_arraylist_create();
1699 if (NULL == tep->cacheList)
1701 OIC_LOG(ERROR, NET_SSL_TAG, "cacheList initialization failed!");
1702 mbedtls_ssl_free(&tep->ssl);
1704 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1707 OIC_LOG_V(INFO, NET_SSL_TAG, "New [%s role] endpoint added [%s:%d]",
1708 (MBEDTLS_SSL_IS_SERVER==config->endpoint ? "server" : "client"),
1709 endpoint->addr, endpoint->port);
1710 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1714 * Initializes PSK identity.
1716 * @param[out] config client/server config to be updated
1718 * @return 0 on success or -1 on error
1720 static int InitPskIdentity(mbedtls_ssl_config * config)
1722 uint8_t keyBuf[PSK_LENGTH] = {0};
1723 uint8_t idBuf[UUID_LENGTH] = {0};
1724 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1725 VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "Param config is NULL" , -1);
1727 //Retrieve PSK identity from SVR DB
1728 if (0 > g_getCredentialsCallback(CA_DTLS_PSK_IDENTITY, NULL, 0, idBuf, UUID_LENGTH))
1730 OIC_LOG(ERROR, NET_SSL_TAG, "Identity not found");
1731 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1734 //Store PSK ideneity in mbedtls_ssl_config
1735 if (0 != mbedtls_ssl_conf_psk(config, keyBuf, PSK_LENGTH, idBuf, UUID_LENGTH))
1737 OIC_LOG(ERROR, NET_SSL_TAG, "Identity initialization failed!");
1738 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1741 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1744 static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapter)
1747 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1748 VERIFY_NON_NULL_VOID(config, NET_SSL_TAG, "Invaild param");
1749 VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1750 VERIFY_NON_NULL_VOID(g_getCredentialTypesCallback, NET_SSL_TAG, "Param callback is null");
1752 //Resetting cipherFlag
1753 g_caSslContext->cipherFlag[0] = false;
1754 g_caSslContext->cipherFlag[1] = false;
1756 g_getCredentialTypesCallback(g_caSslContext->cipherFlag);
1757 // Retrieve the PSK credential from SRM
1758 if (0 != InitPskIdentity(config))
1760 OIC_LOG(ERROR, NET_SSL_TAG, "PSK identity initialization failed!");
1763 // Retrieve the Cert credential from SRM
1764 if (true == g_caSslContext->cipherFlag[1])
1766 int ret = InitPKIX(adapter);
1769 OIC_LOG(ERROR, NET_SSL_TAG, "Failed to init X.509");
1773 memset(g_cipherSuitesList, 0, sizeof(g_cipherSuitesList));
1775 if (SSL_CIPHER_MAX < g_caSslContext->cipher)
1777 OIC_LOG(ERROR, NET_SSL_TAG, "Maximum ciphersuite index exceeded");
1780 // Add the preferred ciphersuite first
1781 if (SSL_CIPHER_MAX != g_caSslContext->cipher)
1783 g_cipherSuitesList[index] = tlsCipher[g_caSslContext->cipher][0];
1784 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Preferred ciphersuite added");
1788 // Add PSK ciphersuite
1789 if (true == g_caSslContext->cipherFlag[0] &&
1790 MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 != tlsCipher[g_caSslContext->cipher][0])
1792 g_cipherSuitesList[index] = MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
1793 OIC_LOG(DEBUG, NET_SSL_TAG, "PSK ciphersuite added");
1797 // Add all certificate ciphersuites
1798 if (true == g_caSslContext->cipherFlag[1])
1800 for (unsigned int i = 0; i < SSL_CIPHER_MAX - 1; i++)
1802 if (MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 != tlsCipher[i][0] &&
1803 i != g_caSslContext->cipher)
1805 g_cipherSuitesList[index] = tlsCipher[i][0];
1810 if (MBEDTLS_SSL_IS_SERVER == config->endpoint)
1812 mbedtls_ssl_conf_authmode(config, MBEDTLS_SSL_VERIFY_OPTIONAL);
1816 OIC_LOG(INFO, NET_SSL_TAG, "Supported ciphersuites:");
1817 for (int i = 0; i < index; i++)
1819 OIC_LOG_V(INFO, NET_SSL_TAG, "Ciphersuite %04x", g_cipherSuitesList[i]);
1822 mbedtls_ssl_conf_ciphersuites(config, g_cipherSuitesList);
1824 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1827 * Initiate TLS handshake with endpoint.
1829 * @param[in] endpoint remote address
1831 * @return TLS endpoint or NULL
1833 static SslEndPoint_t * InitiateTlsHandshake(const CAEndpoint_t *endpoint)
1836 SslEndPoint_t * tep = NULL;
1838 OIC_LOG_V(INFO, NET_SSL_TAG, "In %s", __func__);
1839 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , NULL);
1840 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
1842 //Remove previous peer info from peer list.
1843 RemovePeerFromList(endpoint);
1845 mbedtls_ssl_config * config = (endpoint->adapter == CA_ADAPTER_IP ||
1846 endpoint->adapter == CA_ADAPTER_GATT_BTLE ?
1847 &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
1848 tep = NewSslEndPoint(endpoint, config);
1851 OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1855 //Load allowed SVR suites from SVR DB
1856 SetupCipher(config, endpoint->adapter);
1858 ret = u_arraylist_add(g_caSslContext->peerList, (void *) tep);
1861 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1862 DeleteSslEndPoint(tep);
1866 while (MBEDTLS_SSL_HANDSHAKE_OVER > tep->ssl.state)
1868 ret = mbedtls_ssl_handshake_step(&tep->ssl);
1869 if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
1875 OIC_LOG(ERROR, NET_SSL_TAG, "Handshake failed due to socket error");
1876 RemovePeerFromList(&tep->sep.endpoint);
1879 SSL_CHECK_FAIL(tep, ret, "Handshake error", 0, NULL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1881 OIC_LOG_V(INFO, NET_SSL_TAG, "Out %s", __func__);
1884 #ifdef __WITH_DTLS__
1886 * Stops DTLS retransmission.
1888 static void StopRetransmit()
1892 unregisterTimer(g_caSslContext->timerId);
1893 g_caSslContext->timerId= -1;
1897 void CAdeinitSslAdapter()
1899 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1901 VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "context is NULL");
1902 VERIFY_NON_NULL_VOID(g_sslContextMutex, NET_SSL_TAG, "context mutex is NULL");
1904 //Lock tlsContext mutex
1905 oc_mutex_lock(g_sslContextMutex);
1910 // De-initialize mbedTLS
1911 mbedtls_x509_crt_free(&g_caSslContext->ca);
1912 mbedtls_x509_crt_free(&g_caSslContext->crt);
1913 mbedtls_pk_free(&g_caSslContext->pkey);
1914 mbedtls_x509_crl_free(&g_caSslContext->crl);
1916 mbedtls_ssl_config_free(&g_caSslContext->clientTlsConf);
1917 mbedtls_ssl_config_free(&g_caSslContext->serverTlsConf);
1918 #endif // __WITH_TLS__
1919 #ifdef __WITH_DTLS__
1920 mbedtls_ssl_config_free(&g_caSslContext->clientDtlsConf);
1921 mbedtls_ssl_config_free(&g_caSslContext->serverDtlsConf);
1922 mbedtls_ssl_cookie_free(&g_caSslContext->cookieCtx);
1923 #endif // __WITH_DTLS__
1924 mbedtls_ctr_drbg_free(&g_caSslContext->rnd);
1925 mbedtls_entropy_free(&g_caSslContext->entropy);
1926 #ifdef __WITH_DTLS__
1929 // De-initialize tls Context
1930 OICFree(g_caSslContext);
1931 g_caSslContext = NULL;
1933 // Delete decrypt buffer
1934 if (g_decryptBuffer)
1936 OICFree(g_decryptBuffer);
1937 g_decryptBuffer = NULL;
1940 // Unlock tlsContext mutex and de-initialize it
1941 oc_mutex_unlock(g_sslContextMutex);
1942 oc_mutex_free(g_sslContextMutex);
1943 g_sslContextMutex = NULL;
1945 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s ", __func__);
1948 static int InitConfig(mbedtls_ssl_config * conf, int transport, int mode)
1950 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1951 VERIFY_NON_NULL_RET(conf, NET_SSL_TAG, "Param conf is NULL" , -1);
1952 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
1953 mbedtls_ssl_config_init(conf);
1954 if (mbedtls_ssl_config_defaults(conf, mode, transport, MBEDTLS_SSL_PRESET_DEFAULT) != 0)
1956 OIC_LOG(ERROR, NET_SSL_TAG, "Config initialization failed!");
1960 mbedtls_ssl_conf_psk_cb(conf, GetPskCredentialsCallback, NULL);
1961 mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, &g_caSslContext->rnd);
1962 mbedtls_ssl_conf_curves(conf, curve[ADAPTER_CURVE_SECP256R1]);
1963 mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
1964 mbedtls_ssl_conf_renegotiation(conf, MBEDTLS_SSL_RENEGOTIATION_DISABLED);
1965 mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1966 mbedtls_ssl_conf_sig_hashes(conf, g_ssl_ordered_default_hashes);
1968 #ifdef __WITH_DTLS__
1969 if (MBEDTLS_SSL_TRANSPORT_DATAGRAM == transport &&
1970 MBEDTLS_SSL_IS_SERVER == mode)
1972 mbedtls_ssl_conf_dtls_cookies(conf, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check,
1973 &g_caSslContext->cookieCtx);
1975 #endif // __WITH_DTLS__
1977 #if !defined(NDEBUG) || defined(TB_LOG)
1978 mbedtls_ssl_conf_dbg(conf, DebugSsl, NULL);
1979 mbedtls_debug_set_threshold(MBED_TLS_DEBUG_LEVEL);
1981 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1984 #ifdef __WITH_DTLS__
1986 * Starts DTLS retransmission.
1988 static int StartRetransmit()
1990 uint32_t listIndex = 0;
1991 uint32_t listLength = 0;
1992 SslEndPoint_t *tep = NULL;
1994 oc_mutex_lock(g_sslContextMutex);
1995 if (NULL == g_caSslContext)
1997 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL. Stop retransmission");
1998 oc_mutex_unlock(g_sslContextMutex);
2001 if (g_caSslContext->timerId != -1)
2003 //clear previous timer
2004 unregisterTimer(g_caSslContext->timerId);
2006 listLength = u_arraylist_length(g_caSslContext->peerList);
2008 for (listIndex = 0; listIndex < listLength; listIndex++)
2010 tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
2012 || (tep->ssl.conf && MBEDTLS_SSL_TRANSPORT_STREAM == tep->ssl.conf->transport)
2013 || MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
2017 OIC_LOG_V(INFO, NET_SSL_TAG, "peer #%d", (int) listIndex);
2019 int ret = mbedtls_ssl_handshake_step(&tep->ssl);
2021 if (MBEDTLS_ERR_SSL_CONN_EOF != ret)
2024 registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, (void *) StartRetransmit);
2026 SSL_CHECK_FAIL(tep, ret, "Retransmission", 1, CA_STATUS_FAILED,
2027 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
2032 registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, (void *) StartRetransmit);
2033 oc_mutex_unlock(g_sslContextMutex);
2039 CAResult_t CAinitSslAdapter()
2041 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2042 // Initialize mutex for tlsContext
2043 if (NULL == g_sslContextMutex)
2045 g_sslContextMutex = oc_mutex_new();
2046 VERIFY_NON_NULL_RET(g_sslContextMutex, NET_SSL_TAG, "malloc failed", CA_MEMORY_ALLOC_FAILED);
2050 OIC_LOG(INFO, NET_SSL_TAG, "Done already!");
2051 return CA_STATUS_OK;
2054 // Lock tlsContext mutex and create tlsContext
2055 oc_mutex_lock(g_sslContextMutex);
2056 g_caSslContext = (SslContext_t *)OICCalloc(1, sizeof(SslContext_t));
2058 if (NULL == g_caSslContext)
2060 OIC_LOG(ERROR, NET_SSL_TAG, "Context malloc failed");
2061 oc_mutex_unlock(g_sslContextMutex);
2062 oc_mutex_free(g_sslContextMutex);
2063 g_sslContextMutex = NULL;
2064 return CA_MEMORY_ALLOC_FAILED;
2068 g_caSslContext->peerList = u_arraylist_create();
2070 if(NULL == g_caSslContext->peerList)
2072 OIC_LOG(ERROR, NET_SSL_TAG, "peerList initialization failed!");
2073 OICFree(g_caSslContext);
2074 g_caSslContext = NULL;
2075 oc_mutex_unlock(g_sslContextMutex);
2076 oc_mutex_free(g_sslContextMutex);
2077 g_sslContextMutex = NULL;
2078 return CA_STATUS_FAILED;
2081 /* Initialize TLS library
2083 #if !defined(NDEBUG) || defined(TB_LOG)
2084 char version[MBED_TLS_VERSION_LEN];
2085 mbedtls_version_get_string(version);
2086 OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", version);
2091 mbedtls_entropy_init(&g_caSslContext->entropy);
2092 mbedtls_ctr_drbg_init(&g_caSslContext->rnd);
2095 unsigned char seed[sizeof(SEED)] = {0};
2097 urandomFd = open("/dev/urandom", O_RDONLY);
2100 OIC_LOG(ERROR, NET_SSL_TAG, "Fails open /dev/urandom!");
2101 oc_mutex_unlock(g_sslContextMutex);
2102 CAdeinitSslAdapter();
2103 return CA_STATUS_FAILED;
2105 if(0 > read(urandomFd, seed, sizeof(seed)))
2107 OIC_LOG(ERROR, NET_SSL_TAG, "Fails read from /dev/urandom!");
2109 oc_mutex_unlock(g_sslContextMutex);
2110 CAdeinitSslAdapter();
2111 return CA_STATUS_FAILED;
2116 unsigned char * seed = (unsigned char*) SEED;
2118 if(0 != mbedtls_ctr_drbg_seed(&g_caSslContext->rnd, mbedtls_entropy_func,
2119 &g_caSslContext->entropy, seed, sizeof(SEED)))
2121 OIC_LOG(ERROR, NET_SSL_TAG, "Seed initialization failed!");
2122 oc_mutex_unlock(g_sslContextMutex);
2123 CAdeinitSslAdapter();
2124 return CA_STATUS_FAILED;
2126 mbedtls_ctr_drbg_set_prediction_resistance(&g_caSslContext->rnd, MBEDTLS_CTR_DRBG_PR_OFF);
2129 if (0 != InitConfig(&g_caSslContext->clientTlsConf,
2130 MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_CLIENT))
2132 OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
2133 oc_mutex_unlock(g_sslContextMutex);
2134 CAdeinitSslAdapter();
2135 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2136 return CA_STATUS_FAILED;
2139 if (0 != InitConfig(&g_caSslContext->serverTlsConf,
2140 MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_SERVER))
2142 OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
2143 oc_mutex_unlock(g_sslContextMutex);
2144 CAdeinitSslAdapter();
2145 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2146 return CA_STATUS_FAILED;
2148 #endif // __WITH_TLS__
2149 #ifdef __WITH_DTLS__
2150 mbedtls_ssl_cookie_init(&g_caSslContext->cookieCtx);
2151 if (0 != mbedtls_ssl_cookie_setup(&g_caSslContext->cookieCtx, mbedtls_ctr_drbg_random,
2152 &g_caSslContext->rnd))
2154 OIC_LOG(ERROR, NET_SSL_TAG, "Cookie setup failed!");
2155 oc_mutex_unlock(g_sslContextMutex);
2156 CAdeinitSslAdapter();
2157 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2158 return CA_STATUS_FAILED;
2161 if (0 != InitConfig(&g_caSslContext->clientDtlsConf,
2162 MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_CLIENT))
2164 OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
2165 oc_mutex_unlock(g_sslContextMutex);
2166 CAdeinitSslAdapter();
2167 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2168 return CA_STATUS_FAILED;
2171 if (0 != InitConfig(&g_caSslContext->serverDtlsConf,
2172 MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_SERVER))
2174 OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
2175 oc_mutex_unlock(g_sslContextMutex);
2176 CAdeinitSslAdapter();
2177 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2178 return CA_STATUS_FAILED;
2180 #endif // __WITH_DTLS__
2182 // set default cipher
2183 g_caSslContext->cipher = SSL_CIPHER_MAX;
2186 mbedtls_x509_crt_init(&g_caSslContext->ca);
2187 mbedtls_x509_crt_init(&g_caSslContext->crt);
2188 mbedtls_pk_init(&g_caSslContext->pkey);
2189 mbedtls_x509_crl_init(&g_caSslContext->crl);
2191 #ifdef __WITH_DTLS__
2192 g_caSslContext->timerId = -1;
2195 // create decrypt buffer
2196 g_decryptBuffer = (uint8_t *)OICCalloc(1, TLS_MSG_BUF_LEN);
2197 if (NULL == g_decryptBuffer)
2199 OIC_LOG(ERROR, NET_SSL_TAG, "Decrypt buffer malloc failed");
2200 oc_mutex_unlock(g_sslContextMutex);
2201 CAdeinitSslAdapter();
2202 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2203 return CA_MEMORY_ALLOC_FAILED;
2206 oc_mutex_unlock(g_sslContextMutex);
2207 #ifdef __WITH_DTLS__
2211 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2212 return CA_STATUS_OK;
2215 SslCacheMessage_t * NewCacheMessage(uint8_t * data, size_t dataLen)
2217 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2218 VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , NULL);
2221 OIC_LOG(ERROR, NET_SSL_TAG, "dataLen is equal to zero");
2222 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2225 SslCacheMessage_t * message = (SslCacheMessage_t *) OICCalloc(1, sizeof(SslCacheMessage_t));
2226 if (NULL == message)
2228 OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
2229 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2233 message->data = (uint8_t *)OICCalloc(dataLen, sizeof(uint8_t));
2234 if (NULL == message->data)
2236 OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
2238 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2241 memcpy(message->data, data, dataLen);
2242 message->len = dataLen;
2243 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2247 /* Send data via TLS connection.
2249 CAResult_t CAencryptSsl(const CAEndpoint_t *endpoint,
2250 void *data, uint32_t dataLen)
2254 OIC_LOG_V(INFO, NET_SSL_TAG, "In %s ", __func__);
2256 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG,"Remote address is NULL", CA_STATUS_INVALID_PARAM);
2257 VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Data is NULL", CA_STATUS_INVALID_PARAM);
2258 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Port %d", endpoint->port);
2262 OIC_LOG_V(ERROR, NET_SSL_TAG, "dataLen is zero [%d]", dataLen);
2263 return CA_STATUS_FAILED;
2266 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data to be encrypted dataLen [%d]", dataLen);
2268 oc_mutex_lock(g_sslContextMutex);
2269 if(NULL == g_caSslContext)
2271 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2272 oc_mutex_unlock(g_sslContextMutex);
2273 return CA_STATUS_FAILED;
2276 SslEndPoint_t * tep = GetSslPeer(endpoint);
2279 tep = InitiateTlsHandshake(endpoint);
2283 OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
2284 oc_mutex_unlock(g_sslContextMutex);
2285 return CA_STATUS_FAILED;
2288 if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
2290 OIC_LOG(INFO, NET_SSL_TAG, "(MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)");
2292 unsigned char *dataBuf = (unsigned char *)data;
2297 ret = mbedtls_ssl_write(&tep->ssl, dataBuf, dataLen - written);
2300 if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
2302 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned 0x%x", -ret);
2303 RemovePeerFromList(&tep->sep.endpoint);
2304 oc_mutex_unlock(g_sslContextMutex);
2305 return CA_STATUS_FAILED;
2309 OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
2313 } while (dataLen > written);
2318 SslCacheMessage_t * msg = NewCacheMessage((uint8_t*) data, dataLen);
2319 if (NULL == msg || !u_arraylist_add(tep->cacheList, (void *) msg))
2321 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
2322 oc_mutex_unlock(g_sslContextMutex);
2323 return CA_STATUS_FAILED;
2327 oc_mutex_unlock(g_sslContextMutex);
2329 OIC_LOG_V(INFO, NET_SSL_TAG, "Out %s", __func__);
2330 return CA_STATUS_OK;
2333 * Sends cached messages via TLS connection.
2335 * @param[in] tep remote address with session info
2337 static void SendCacheMessages(SslEndPoint_t * tep)
2339 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2340 VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "Param tep is NULL");
2342 uint32_t listIndex = 0;
2343 uint32_t listLength = 0;
2344 listLength = u_arraylist_length(tep->cacheList);
2345 for (listIndex = 0; listIndex < listLength;)
2348 SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(tep->cacheList, listIndex);
2349 if (NULL != msg && NULL != msg->data && 0 != msg->len)
2351 unsigned char *dataBuf = (unsigned char *)msg->data;
2356 ret = mbedtls_ssl_write(&tep->ssl, dataBuf, msg->len - written);
2359 if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
2361 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned -0x%x", -ret);
2366 OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
2370 } while (msg->len > written);
2372 if (u_arraylist_remove(tep->cacheList, listIndex))
2374 DeleteCacheMessage(msg);
2375 // Reduce list length by 1 as we removed one element.
2380 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_remove failed.");
2386 // Move to the next element
2390 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2393 void CAsetSslHandshakeCallback(CAErrorCallback tlsHandshakeCallback)
2395 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2396 g_sslCallback = tlsHandshakeCallback;
2397 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2401 * Check RFC4122 based UUID
2403 * @param uuidString string representation of UUID
2404 * @return true for success, otherwise false
2406 static bool CheckUuidFormat(const char uuidString[UUID_STR_SIZE])
2408 // Indexes of '-' symbols in string representation of UUID
2409 static const int dash_idxs[4] = {8,13,18,23};
2411 VERIFY_NON_NULL_RET(uuidString, NET_SSL_TAG, "uuidString is NULL" , false);
2413 // Check for '-' symbols
2414 for (int i = 0; i < 4; i++)
2416 if (uuidString[dash_idxs[i]] != '-')
2422 for (int i = 0; i < UUID_STR_SIZE; i++)
2425 if (i == dash_idxs[0] || i == dash_idxs[1] || i == dash_idxs[2] || i == dash_idxs[3])
2430 if ((uuidString[i] >= 'a' && uuidString[i] <= 'f')
2431 || (uuidString[i] >= 'A' && uuidString[i] <= 'F')
2432 || (uuidString[i] >= '0' && uuidString[i] <= '9') )
2444 * FindUuid function finds the first entry of RFC4122 based UUID
2446 * @param data pointer to unformatted data
2447 * @param size data size
2449 * @return pointer to string representation of the found UUID if success, otherwise NULL
2451 static const char* FindUuid(const char* data, size_t size)
2453 const char* result = NULL;
2455 VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL" , NULL);
2456 if (size < UUID_STR_SIZE)
2458 OIC_LOG(ERROR, NET_SSL_TAG, "Buffer size is too small");
2462 const char* currentPtr = data;
2463 int currentSize = size;
2465 && (currentPtr = (const char*)memchr((const void*)++currentPtr, '-', currentSize - 1))
2466 && ((currentSize = (size - (currentPtr - data))) >= (UUID_STR_SIZE - 8)))
2468 if (currentPtr - data >= 8 && CheckUuidFormat(currentPtr - 8))
2470 result = currentPtr - 8;
2477 /* Read data from TLS connection
2479 CAResult_t CAdecryptSsl(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t dataLen)
2482 OIC_LOG_V(INFO, NET_SSL_TAG, "In %s", __func__);
2483 VERIFY_NON_NULL_RET(sep, NET_SSL_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
2484 VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , CA_STATUS_INVALID_PARAM);
2488 OIC_LOG(ERROR, NET_SSL_TAG, "dataLen is zero");
2489 return CA_STATUS_FAILED;
2492 oc_mutex_lock(g_sslContextMutex);
2493 if (NULL == g_caSslContext)
2495 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2496 oc_mutex_unlock(g_sslContextMutex);
2497 return CA_STATUS_FAILED;
2500 SslEndPoint_t * peer = GetSslPeer(&sep->endpoint);
2503 mbedtls_ssl_config * config = (sep->endpoint.adapter == CA_ADAPTER_IP ||
2504 sep->endpoint.adapter == CA_ADAPTER_GATT_BTLE ?
2505 &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
2506 peer = NewSslEndPoint(&sep->endpoint, config);
2509 OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
2510 oc_mutex_unlock(g_sslContextMutex);
2511 return CA_STATUS_FAILED;
2513 //Load allowed TLS suites from SVR DB
2514 SetupCipher(config, sep->endpoint.adapter);
2516 ret = u_arraylist_add(g_caSslContext->peerList, (void *) peer);
2519 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
2521 oc_mutex_unlock(g_sslContextMutex);
2522 return CA_STATUS_FAILED;
2526 peer->recBuf.buff = data;
2527 peer->recBuf.len = dataLen;
2528 peer->recBuf.loaded = 0;
2530 while (MBEDTLS_SSL_HANDSHAKE_OVER != peer->ssl.state)
2532 ret = mbedtls_ssl_handshake_step(&peer->ssl);
2533 if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
2538 if (MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED == ret)
2540 OIC_LOG(DEBUG, NET_SSL_TAG, "Hello verification requested");
2541 mbedtls_ssl_session_reset(&peer->ssl);
2542 mbedtls_ssl_set_client_transport_id(&peer->ssl,
2543 (const unsigned char *) sep->endpoint.addr,
2544 sizeof(sep->endpoint.addr));
2545 ret = mbedtls_ssl_handshake_step(&peer->ssl);
2547 uint32_t flags = mbedtls_ssl_get_verify_result(&peer->ssl);
2549 ((MBEDTLS_SSL_IS_CLIENT == peer->ssl.conf->endpoint) ||
2550 (MBEDTLS_SSL_IS_SERVER == peer->ssl.conf->endpoint && MBEDTLS_X509_BADCERT_MISSING != flags)))
2552 OIC_LOG_BUFFER(ERROR, NET_SSL_TAG, (const uint8_t *) &flags, sizeof(flags));
2553 SSL_CHECK_FAIL(peer, flags, "Cert verification failed", 1,
2554 CA_STATUS_FAILED, GetAlertCode(flags));
2556 SSL_CHECK_FAIL(peer, ret, "Handshake error", 1, CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
2557 if (MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC == peer->ssl.state)
2559 memcpy(peer->master, peer->ssl.session_negotiate->master, sizeof(peer->master));
2560 g_caSslContext->selectedCipher = peer->ssl.session_negotiate->ciphersuite;
2562 if (MBEDTLS_SSL_CLIENT_KEY_EXCHANGE == peer->ssl.state)
2564 memcpy(peer->random, peer->ssl.handshake->randbytes, sizeof(peer->random));
2567 if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
2569 SSL_RES(peer, CA_STATUS_OK);
2570 if (MBEDTLS_SSL_IS_CLIENT == peer->ssl.conf->endpoint)
2572 SendCacheMessages(peer);
2575 int selectedCipher = peer->ssl.session->ciphersuite;
2576 OIC_LOG_V(DEBUG, NET_SSL_TAG, "(D)TLS Session is connected via ciphersuite [0x%x]", selectedCipher);
2577 if (MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 != selectedCipher &&
2578 MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 != selectedCipher)
2580 const mbedtls_x509_crt * peerCert = mbedtls_ssl_get_peer_cert(&peer->ssl);
2581 ret = (NULL == peerCert ? -1 : 0);
2582 if (g_CertificateVerificationCallback)
2584 uint32_t flags = mbedtls_ssl_get_verify_result(&peer->ssl);
2587 g_CertificateVerificationCallback(CA_CERTIFICATE_VERIFY_SUCCESS_MUTUAL);
2589 else if (MBEDTLS_X509_BADCERT_MISSING == flags)
2591 g_CertificateVerificationCallback(CA_CERTIFICATE_VERIFY_NO_CERT);
2595 g_CertificateVerificationCallback(CA_CERTIFICATE_VERIFY_FAILED);
2598 //SSL_CHECK_FAIL(peer, ret, "Failed to retrieve cert", 1,
2599 // CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_NO_CERT);
2602 const char* uuidptr = FindUuid((const char*)peerCert->subject_raw.p, peerCert->subject_raw.len);
2605 char uuid[UUID_STR_SIZE + 1] = {0};
2606 strncpy(uuid, uuidptr, UUID_STR_SIZE);
2607 uuid[UUID_STR_SIZE] = '\0';
2608 OIC_LOG_V(DEBUG, NET_SSL_TAG, "certificate uuid string: %s" , uuid);
2609 ret = OCConvertStringToUuid(uuid, peer->sep.identity.id);
2610 SSL_CHECK_FAIL(peer, ret, "Failed to convert subject", 1,
2611 CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
2615 OIC_LOG(WARNING, NET_SSL_TAG, "uuid not found");
2620 if (MBEDTLS_SSL_IS_CLIENT == peer->ssl.conf->endpoint)
2622 SendCacheMessages(peer);
2624 mbedtls_ssl_config * config = (sep->endpoint.adapter == CA_ADAPTER_IP ||
2625 sep->endpoint.adapter == CA_ADAPTER_GATT_BTLE ?
2626 &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
2628 mbedtls_ssl_conf_authmode(config, MBEDTLS_SSL_VERIFY_REQUIRED);
2630 oc_mutex_unlock(g_sslContextMutex);
2631 OIC_LOG_V(INFO, NET_SSL_TAG, "Out %s", __func__);
2632 return CA_STATUS_OK;
2636 if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
2638 OIC_LOG(INFO, NET_SSL_TAG, "(MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)");
2640 // flag to read again remained data
2641 bool read_more = false;
2644 if (NULL == g_decryptBuffer)
2646 OIC_LOG(ERROR, NET_SSL_TAG, "decrypt buffer is NULL");
2647 oc_mutex_unlock(g_sslContextMutex);
2648 return CA_STATUS_FAILED;
2650 memset(g_decryptBuffer, 0, TLS_MSG_BUF_LEN);
2655 ret = mbedtls_ssl_read(&peer->ssl, g_decryptBuffer, TLS_MSG_BUF_LEN);
2656 } while (MBEDTLS_ERR_SSL_WANT_READ == ret);
2658 if (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY == ret ||
2659 // TinyDTLS sends fatal close_notify alert
2660 (MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE == ret &&
2661 MBEDTLS_SSL_ALERT_LEVEL_FATAL == peer->ssl.in_msg[0] &&
2662 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY == peer->ssl.in_msg[1]))
2664 OIC_LOG(INFO, NET_SSL_TAG, "Connection was closed gracefully");
2665 RemovePeerFromList(&peer->sep.endpoint);
2666 oc_mutex_unlock(g_sslContextMutex);
2667 return CA_STATUS_OK;
2672 OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_ssl_read returned -0x%x", -ret);
2673 //SSL_RES(peer, CA_STATUS_FAILED);
2674 RemovePeerFromList(&peer->sep.endpoint);
2675 oc_mutex_unlock(g_sslContextMutex);
2676 return CA_STATUS_FAILED;
2680 int adapterIndex = GetAdapterIndex(peer->sep.endpoint.adapter);
2681 if (0 <= adapterIndex && MAX_SUPPORTED_ADAPTERS > adapterIndex)
2684 res = g_caSslContext->adapterCallbacks[adapterIndex].recvCallback(&peer->sep,
2685 g_decryptBuffer, ret);
2686 if (CA_STATUS_OK != res)
2688 OIC_LOG(ERROR, NET_SSL_TAG, "recvCallback is failed");
2689 RemovePeerFromList(&peer->sep.endpoint);
2690 oc_mutex_unlock(g_sslContextMutex);
2691 return CA_STATUS_FAILED;
2694 // check if decrypted data is remained in stream transport
2695 size_t remained = mbedtls_ssl_get_bytes_avail(&peer->ssl);
2697 MBEDTLS_SSL_TRANSPORT_STREAM == peer->ssl.conf->transport)
2699 OIC_LOG_V(DEBUG, NET_SSL_TAG, "need to read %zu bytes more", remained);
2705 OIC_LOG(ERROR, NET_SSL_TAG, "Unsuported adapter");
2706 RemovePeerFromList(&peer->sep.endpoint);
2707 oc_mutex_unlock(g_sslContextMutex);
2708 return CA_STATUS_FAILED;
2711 } while (read_more);
2714 oc_mutex_unlock(g_sslContextMutex);
2715 OIC_LOG_V(INFO, NET_SSL_TAG, "Out %s", __func__);
2716 return CA_STATUS_OK;
2719 void CAsetSslAdapterCallbacks(CAPacketReceivedCallback recvCallback,
2720 CAPacketSendCallback sendCallback,
2721 CATransportAdapter_t type)
2723 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2724 VERIFY_NON_NULL_VOID(sendCallback, NET_SSL_TAG, "sendCallback is NULL");
2725 VERIFY_NON_NULL_VOID(recvCallback, NET_SSL_TAG, "recvCallback is NULL");
2726 oc_mutex_lock(g_sslContextMutex);
2727 if (NULL == g_caSslContext)
2729 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2730 oc_mutex_unlock(g_sslContextMutex);
2737 g_caSslContext->adapterCallbacks[0].recvCallback = recvCallback;
2738 g_caSslContext->adapterCallbacks[0].sendCallback = sendCallback;
2740 case CA_ADAPTER_TCP:
2741 g_caSslContext->adapterCallbacks[1].recvCallback = recvCallback;
2742 g_caSslContext->adapterCallbacks[1].sendCallback = sendCallback;
2744 case CA_ADAPTER_GATT_BTLE:
2745 g_caSslContext->adapterCallbacks[2].recvCallback = recvCallback;
2746 g_caSslContext->adapterCallbacks[2].sendCallback = sendCallback;
2749 OIC_LOG_V(ERROR, NET_SSL_TAG, "Unsupported adapter: %d", type);
2752 oc_mutex_unlock(g_sslContextMutex);
2753 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2756 * Gets index of the TLS ciphersuite in the SslCipher_t enum.
2758 * @param[in] cipher TLS chiphersuite code
2760 * @return corresponding enum
2763 static SslCipher_t GetCipherIndex(const uint32_t cipher)
2767 case MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256:
2769 return SSL_RSA_WITH_AES_256_CBC_SHA256;
2771 case MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256:
2773 return SSL_RSA_WITH_AES_128_GCM_SHA256;
2775 case MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
2777 return SSL_ECDHE_RSA_WITH_AES_128_GCM_SHA256;
2779 case MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
2781 return SSL_ECDHE_RSA_WITH_AES_256_GCM_SHA384;
2783 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
2785 return SSL_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
2787 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2789 return SSL_ECDHE_ECDSA_WITH_AES_128_CCM_8;
2791 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
2793 return SSL_ECDHE_ECDSA_WITH_AES_128_CCM;
2795 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2797 return SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256;
2799 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
2801 return SSL_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384;
2803 case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
2805 return SSL_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384;
2807 case MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
2809 return SSL_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
2811 case MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
2813 return SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256;
2815 case MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256:
2817 return SSL_ECDH_ANON_WITH_AES_128_CBC_SHA256;
2821 return SSL_CIPHER_MAX;
2826 CAResult_t CAsetTlsCipherSuite(const uint32_t cipher)
2828 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2829 VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL context is not initialized." , CA_STATUS_NOT_INITIALIZED);
2831 SslCipher_t index = GetCipherIndex(cipher);
2832 if (SSL_CIPHER_MAX == index)
2834 OIC_LOG(WARNING, NET_SSL_TAG, "Unknown cipher");
2839 CONF_SSL(&g_caSslContext->clientTlsConf, &g_caSslContext->serverTlsConf,
2840 mbedtls_ssl_conf_ciphersuites, tlsCipher[index]);
2842 #ifdef __WITH_DTLS__
2843 CONF_SSL(&g_caSslContext->clientDtlsConf, &g_caSslContext->serverDtlsConf,
2844 mbedtls_ssl_conf_ciphersuites, tlsCipher[index]);
2846 OIC_LOG_V(INFO, NET_SSL_TAG, "Selected cipher: 0x%x", cipher);
2848 g_caSslContext->cipher = index;
2850 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2851 return CA_STATUS_OK;
2854 CAResult_t CAinitiateSslHandshake(const CAEndpoint_t *endpoint)
2856 CAResult_t res = CA_STATUS_OK;
2857 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2858 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
2859 oc_mutex_lock(g_sslContextMutex);
2860 if (NULL == InitiateTlsHandshake(endpoint))
2862 OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
2863 res = CA_STATUS_FAILED;
2865 oc_mutex_unlock(g_sslContextMutex);
2866 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2870 * Expands the secret into blocks of data according
2871 * to the algorithm specified in section 5 of RFC 4346
2873 * This function writes upto @p bufLen bytes into the given output buffer @p buf
2875 * @param key secret key.
2876 * @param keyLen secret key length.
2877 * @param label A PRF label.
2878 * @param labelLen Actual length of @p label.
2879 * @param random1 Random seed.
2880 * @param random1Len Actual length of @p random1 (may be zero).
2881 * @param random2 Random seed.
2882 * @param random2Len Actual length of @p random2 (may be zero).
2883 * @param buf Output buffer for generated random data.
2884 * @param bufLen Maximum size of @p buf.
2886 * @return The actual number of bytes written to @p buf or @c -1 on error.
2889 static int pHash (const unsigned char *key, size_t keyLen,
2890 const unsigned char *label, size_t labelLen,
2891 const unsigned char *random1, size_t random1Len,
2892 const unsigned char *random2, size_t random2Len,
2893 unsigned char *buf, size_t bufLen)
2895 unsigned char A[RANDOM_LEN] = {0};
2896 unsigned char tmp[RANDOM_LEN] = {0};
2897 size_t dLen; /* digest length */
2898 size_t len = 0; /* result length */
2900 VERIFY_NON_NULL_RET(key, NET_SSL_TAG, "key is NULL", -1);
2901 VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", -1);
2902 VERIFY_NON_NULL_RET(random1, NET_SSL_TAG, "random1 is NULL", -1);
2903 VERIFY_NON_NULL_RET(random2, NET_SSL_TAG, "random2 is NULL", -1);
2904 VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "buf is NULL", -1);
2906 mbedtls_md_context_t hmacA;
2907 mbedtls_md_context_t hmacP;
2909 mbedtls_md_init(&hmacA);
2910 mbedtls_md_init(&hmacP);
2912 CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacA, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2913 CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacP, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2915 CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen );
2916 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, label, labelLen);
2917 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random1, random1Len);
2918 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random2, random2Len);
2919 CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2923 CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2925 while (len + dLen < bufLen)
2927 CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2928 CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2929 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2930 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2931 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2932 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2934 CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2938 memcpy(buf, tmp, dLen);
2941 CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacA);
2942 CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen);
2943 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, A, dLen);
2944 CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2947 CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2948 CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2949 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2951 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2952 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2953 CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2954 CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2956 memcpy(buf, tmp, bufLen - len);
2958 mbedtls_md_free(&hmacA);
2959 mbedtls_md_free(&hmacP);
2963 mbedtls_md_free(&hmacA);
2964 mbedtls_md_free(&hmacP);
2968 CAResult_t CAsslGenerateOwnerPsk(const CAEndpoint_t *endpoint,
2969 const uint8_t* label, const size_t labelLen,
2970 const uint8_t* rsrcServerDeviceId, const size_t rsrcServerDeviceIdLen,
2971 const uint8_t* provServerDeviceId, const size_t provServerDeviceIdLen,
2972 uint8_t* ownerPsk, const size_t ownerPskSize)
2974 OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2975 VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint is NULL", CA_STATUS_INVALID_PARAM);
2976 VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", CA_STATUS_INVALID_PARAM);
2977 VERIFY_NON_NULL_RET(rsrcServerDeviceId, NET_SSL_TAG, "rsrcId is NULL", CA_STATUS_INVALID_PARAM);
2978 VERIFY_NON_NULL_RET(provServerDeviceId, NET_SSL_TAG, "provId is NULL", CA_STATUS_INVALID_PARAM);
2979 VERIFY_NON_NULL_RET(ownerPsk, NET_SSL_TAG, "ownerPSK is NULL", CA_STATUS_INVALID_PARAM);
2981 oc_mutex_lock(g_sslContextMutex);
2982 if (NULL == g_caSslContext)
2984 OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2985 oc_mutex_unlock(g_sslContextMutex);
2986 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2987 return CA_STATUS_FAILED;
2989 SslEndPoint_t * tep = GetSslPeer(endpoint);
2992 OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
2993 oc_mutex_unlock(g_sslContextMutex);
2994 return CA_STATUS_FAILED;
2997 // keyBlockLen set up according to OIC 1.1 Security Specification Section 7.3.2
3001 int keyBlockLen = 0;
3002 if (MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
3003 MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
3004 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
3005 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher)
3007 // 2 * ( 32 + 0 + 16 ) = 96
3008 macKeyLen = SHA256_MAC_KEY_LENGTH;
3009 ivSize = CBC_IV_LENGTH;
3010 keySize = AES128_KEY_LENGTH;
3012 else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM == g_caSslContext->selectedCipher ||
3013 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caSslContext->selectedCipher)
3015 // 2 * ( 0 + 4 + 16 ) = 40
3016 macKeyLen = CCM_MAC_KEY_LENGTH;
3017 ivSize = CCM_IV_LENGTH;
3018 keySize = AES128_KEY_LENGTH;
3020 else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 == g_caSslContext->selectedCipher)
3022 // 2 * ( 32 + 12 + 16 ) = 120
3023 macKeyLen = SHA256_MAC_KEY_LENGTH;
3024 ivSize = GCM_IV_LENGTH;
3025 keySize = AES128_KEY_LENGTH;
3027 else if (MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 == g_caSslContext->selectedCipher)
3029 // 2 * ( 32 + 0 + 32 ) = 128
3030 macKeyLen = SHA256_MAC_KEY_LENGTH;
3031 ivSize = CBC_IV_LENGTH;
3032 keySize = AES256_KEY_LENGTH;
3034 else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 == g_caSslContext->selectedCipher)
3036 // 2 * ( 48 + 0 + 32 ) = 160
3037 macKeyLen = SHA384_MAC_KEY_LENGTH;
3038 ivSize = CBC_IV_LENGTH;
3039 keySize = AES256_KEY_LENGTH;
3041 else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 == g_caSslContext->selectedCipher)
3043 // 2 * ( 48 + 12 + 32 ) = 184
3044 macKeyLen = SHA384_MAC_KEY_LENGTH;
3045 ivSize = GCM_IV_LENGTH;
3046 keySize = AES256_KEY_LENGTH;
3048 else if (MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 == g_caSslContext->selectedCipher)
3050 // 2 * ( 48 + 12 + 32 ) = 184
3051 macKeyLen = SHA256_MAC_KEY_LENGTH;
3052 ivSize = GCM_IV_LENGTH;
3053 keySize = AES128_KEY_LENGTH;
3055 keyBlockLen = 2 * (macKeyLen + keySize + ivSize);
3057 uint8_t * keyblock = (uint8_t *)OICMalloc(keyBlockLen);
3058 if (NULL == keyblock)
3060 OIC_LOG(ERROR, NET_SSL_TAG, "Failed to OICMalloc for keyblock");
3061 oc_mutex_unlock(g_sslContextMutex);
3062 return CA_STATUS_FAILED;
3066 uint8_t lab[] = {0x6b, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70, 0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e};
3067 int ret = pHash(tep->master, sizeof(tep->master), lab, sizeof(lab),
3068 (tep->random) + RANDOM_LEN, RANDOM_LEN, tep->random, RANDOM_LEN,
3069 keyblock, keyBlockLen);
3072 OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
3074 oc_mutex_unlock(g_sslContextMutex);
3075 return CA_STATUS_FAILED;
3078 ret = pHash(keyblock, keyBlockLen, label, labelLen,
3079 rsrcServerDeviceId, rsrcServerDeviceIdLen,
3080 provServerDeviceId, provServerDeviceIdLen,
3081 ownerPsk, ownerPskSize);
3084 OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
3086 oc_mutex_unlock(g_sslContextMutex);
3087 return CA_STATUS_FAILED;
3091 oc_mutex_unlock(g_sslContextMutex);
3093 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
3094 return CA_STATUS_OK;