dd28412460897a1c88c3613283fab5d02935166f
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / adapter_util / ca_adapter_net_ssl.c
1 /******************************************************************
2  *
3  * Copyright 2016 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  ******************************************************************/
20
21
22 #include "iotivity_config.h"
23
24 #define _GNU_SOURCE
25
26 #include <stddef.h>
27 #include <stdbool.h>
28 #include <assert.h>
29 #include "ca_adapter_net_ssl.h"
30 #include "cacommon.h"
31 #include "caipinterface.h"
32 #include "oic_malloc.h"
33 #include "ocrandom.h"
34 #include "byte_array.h"
35 #include "octhread.h"
36 #include "timer.h"
37
38 // headers required for mbed TLS
39 #include "mbedtls/platform.h"
40 #include "mbedtls/ssl.h"
41 #include "mbedtls/entropy.h"
42 #include "mbedtls/ctr_drbg.h"
43 #include "mbedtls/pkcs12.h"
44 #include "mbedtls/ssl_internal.h"
45 #include "mbedtls/net_sockets.h"
46 #include "mbedtls/oid.h"
47 #ifdef __WITH_DTLS__
48 #include "mbedtls/timing.h"
49 #include "mbedtls/ssl_cookie.h"
50 #endif
51
52 #if !defined(NDEBUG) || defined(TB_LOG)
53 #include "mbedtls/debug.h"
54 #include "mbedtls/version.h"
55 #endif
56
57 #ifdef HAVE_SYS_TYPES_H
58 #include <sys/types.h>
59 #endif
60 #ifdef HAVE_SYS_STAT_H
61 #include <sys/stat.h>
62 #endif
63 #ifdef HAVE_FCNTL_H
64 #include <fcntl.h>
65 #endif
66 #ifdef HAVE_UNISTD_H
67 #include <unistd.h>
68 #endif
69
70
71 /**
72  * @def MBED_TLS_VERSION_LEN
73  * @brief mbedTLS version string length
74  */
75 #define MBED_TLS_VERSION_LEN (16)
76  /**
77  * @def PERSONALIZATION_STRING
78  * @brief Personalization string for the mbedtls RNG
79  */
80 #define PERSONALIZATION_STRING "IOTIVITY_RND"
81 /**
82  * @def USERID_PREFIX
83  * @brief userid prefix in certificate alternative subject name field
84  */
85 #define USERID_PREFIX "userid:"
86
87 /**
88  * @def NET_SSL_TAG
89  * @brief Logging tag for module name
90  */
91 #define NET_SSL_TAG "OIC_CA_NET_SSL"
92 /**
93  * @def MBED_TLS_TAG
94  * @brief Logging tag for mbedTLS library
95  */
96 #define MBED_TLS_TAG "MBED_TLS"
97 /**
98  * @def MMBED_TLS_DEBUG_LEVEL
99  * @brief Logging level for mbedTLS library
100  */
101 #define MBED_TLS_DEBUG_LEVEL (4)
102
103 /**
104  * @def TLS_MSG_BUF_LEN
105  * @brief Buffer size for TLS record. A single TLS record may be up to 16384 octets in length
106  */
107
108 #define TLS_MSG_BUF_LEN (16384)
109 /**
110  * @def PSK_LENGTH
111  * @brief PSK keys max length
112  */
113 #define PSK_LENGTH (256/8)
114 /**
115  * @def UUID_LENGTHPSK_LENGTH
116  * @brief Identity max length
117  */
118 #define UUID_LENGTH (128/8)
119 /**
120  * @def MASTER_SECRET_LEN
121  * @brief TLS master secret length
122  */
123 #define MASTER_SECRET_LEN (48)
124 /**
125  * @def RANDOM_LEN
126  * @brief TLS client and server random bytes length
127  */
128 #define RANDOM_LEN (32)
129 /**
130  * @def SHA384_MAC_KEY_LENGTH
131  * @brief MAC key length for SHA384 cipher suites
132  */
133 #define SHA384_MAC_KEY_LENGTH (48)
134 /**
135  * @def SHA256_MAC_KEY_LENGTH
136  * @brief MAC key length for SHA256 cipher suites
137  */
138 #define SHA256_MAC_KEY_LENGTH (32)
139 /**
140  * @def CCM_MAC_KEY_LENGTH
141  * @brief MAC key length for CCM cipher suites
142  */
143 #define CCM_MAC_KEY_LENGTH (0)
144 /**
145  * @def AES256_KEY_LENGTH
146  * @brief key material length for AES256 cipher suites
147  */
148 #define AES256_KEY_LENGTH (32)
149 /**
150  * @def AES128_KEY_LENGTH
151  * @brief key material length for AES128 cipher suites
152  */
153 #define AES128_KEY_LENGTH (16)
154 /**
155  * @def GCM_IV_LENGTH
156  * @brief length of nonce for GCM cipher suites
157  */
158 #define GCM_IV_LENGTH (12)
159 /**
160  * @def CCM_IV_LENGTH
161  * @brief length of nonce for CCM cipher suites
162  */
163 #define CCM_IV_LENGTH (4)
164 /**
165  * @def CBC_IV_LENGTH
166  * @brief length of nonce for CBC cipher suites
167  */
168 #define CBC_IV_LENGTH (0)
169
170 /**
171  * @var RETRANSMISSION_TIME
172  * @brief Maximum timeout value (in seconds) to start DTLS retransmission.
173  */
174 #define RETRANSMISSION_TIME 1
175
176 /**@def SSL_CLOSE_NOTIFY(peer, ret)
177  *
178  * Notifies of existing \a peer about closing TLS connection.
179  *
180  * @param[in] peer remote peer
181  * @param[in] ret used internaly
182  */
183 #define SSL_CLOSE_NOTIFY(peer, ret)                                                                \
184 do                                                                                                 \
185 {                                                                                                  \
186     (ret) = mbedtls_ssl_close_notify(&(peer)->ssl);                                                \
187 } while (MBEDTLS_ERR_SSL_WANT_WRITE == (ret))
188
189 /**@def SSL_RES(peer, status)
190  *
191  * Sets SSL result for callback.
192  *
193  * @param[in] peer remote peer
194  */
195 #define SSL_RES(peer, status)                                                                      \
196 if (g_sslCallback)                                                                                 \
197 {                                                                                                  \
198     CAErrorInfo_t errorInfo;                                                                       \
199     errorInfo.result = (status);                                                                   \
200     g_sslCallback(&(peer)->sep.endpoint, &errorInfo);                                              \
201 }
202
203 /**@def CONF_SSL(clientConf, serverConf, fn, ...)
204  *
205  * Calls \a fn for \a clientConf and \a serverConf.
206  *
207  */
208 #define CONF_SSL(clientConf, serverConf, fn, ...) do {                                             \
209 fn((clientConf), __VA_ARGS__);                                                                     \
210 fn((serverConf), __VA_ARGS__);                                                                     \
211 } while (0)
212
213 /** @def CHECK_MBEDTLS_RET(f, ...)
214  * A macro that checks \a f function return code
215  *
216  * If function returns error code it goes to error processing.
217  *
218  * **IMPORTANT:** Any time CHECK_MBEDTLS_RET is used an `exit:` goto label must
219  *                be present to handle error processing.
220  *
221  * @param[in] f  Function to call
222  */
223 #define CHECK_MBEDTLS_RET(f, ...) do {                                                             \
224 int ret = (f)(__VA_ARGS__);                                                                        \
225 if (0 != ret) {                                                                                    \
226     OIC_LOG_V(ERROR, NET_SSL_TAG, "%s returned -0x%04x\n", __func__, -(ret));                      \
227     goto exit;                                                                                     \
228 } } while (0)
229
230 typedef enum
231 {
232     SSL_RSA_WITH_AES_256_CBC_SHA256,
233     SSL_RSA_WITH_AES_128_GCM_SHA256,
234     SSL_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
235     SSL_ECDHE_ECDSA_WITH_AES_128_CCM_8,
236     SSL_ECDHE_ECDSA_WITH_AES_128_CCM,
237     SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
238     SSL_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
239     SSL_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
240     SSL_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
241     SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
242     SSL_ECDH_ANON_WITH_AES_128_CBC_SHA256,
243     SSL_CIPHER_MAX
244 } SslCipher_t;
245
246 typedef enum
247 {
248     ADAPTER_CURVE_SECP256R1,
249     ADAPTER_CURVE_MAX
250 } AdapterCurve_t;
251
252 static const int tlsCipher[SSL_CIPHER_MAX][2] =
253 {
254     {MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256, 0},
255     {MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, 0},
256     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
257     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, 0},
258     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, 0},
259     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 0},
260     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, 0},
261     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 0},
262     {MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, 0},
263     {MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 0},
264     {MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256, 0}
265 };
266
267 static int g_cipherSuitesList[SSL_CIPHER_MAX];
268
269 mbedtls_ecp_group_id curve[ADAPTER_CURVE_MAX][2] =
270 {
271     {MBEDTLS_ECP_DP_SECP256R1, MBEDTLS_ECP_DP_NONE}
272 };
273
274 static PkiInfo_t g_pkiInfo = {{NULL, 0}, {NULL, 0}, {NULL, 0}, {NULL, 0}};
275
276 typedef struct  {
277     int code;
278     int alert;
279 } CrtVerifyAlert_t;
280
281 static const CrtVerifyAlert_t crtVerifyAlerts[] = {
282     {MBEDTLS_X509_BADCERT_EXPIRED,       MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED},
283     {MBEDTLS_X509_BADCERT_REVOKED,       MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED},
284     {MBEDTLS_X509_BADCERT_CN_MISMATCH,   MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN},
285     {MBEDTLS_X509_BADCERT_NOT_TRUSTED,   MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
286     {MBEDTLS_X509_BADCRL_NOT_TRUSTED,    MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
287     {MBEDTLS_X509_BADCRL_EXPIRED,        MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
288     {MBEDTLS_X509_BADCERT_MISSING,       MBEDTLS_SSL_ALERT_MSG_NO_CERT},
289     {MBEDTLS_X509_BADCERT_SKIP_VERIFY,   MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
290     {MBEDTLS_X509_BADCERT_OTHER,         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR},
291     {MBEDTLS_X509_BADCERT_FUTURE,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
292     {MBEDTLS_X509_BADCRL_FUTURE,         MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
293     {MBEDTLS_X509_BADCERT_KEY_USAGE,     MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
294     {MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
295     {MBEDTLS_X509_BADCERT_NS_CERT_TYPE,  MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
296     {MBEDTLS_X509_BADCERT_BAD_MD,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
297     {MBEDTLS_X509_BADCERT_BAD_PK,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
298     {MBEDTLS_X509_BADCERT_BAD_KEY,       MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
299     {MBEDTLS_X509_BADCRL_BAD_MD,         MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
300     {MBEDTLS_X509_BADCRL_BAD_PK,         MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
301     {MBEDTLS_X509_BADCRL_BAD_KEY,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
302     {0, 0}
303 };
304
305 static int GetAlertCode(uint32_t flags)
306 {
307     const CrtVerifyAlert_t *cur;
308
309     for (cur = crtVerifyAlerts; cur->alert != 0 ; cur++)
310     {
311         if (flags & cur->code)
312         {
313             return cur->alert;
314         }
315     }
316     return 0;
317 }
318
319 #if !defined(NDEBUG) || defined(TB_LOG)
320 /**
321  * Pass a message to the OIC logger.
322  *
323  * @param[in] ctx  opaque context for the callback
324  * @param[in] level  debug level
325  * @param[in] file  file name
326  * @param[in] line  line number
327  * @param[in] str  message
328  */
329 static void DebugSsl(void *ctx, int level, const char *file, int line, const char *str)
330 {
331     ((void) level);
332     ((void) file);
333     ((void) line);
334     ((void) ctx);
335
336     char * temp = (char*) str;
337     size_t len = strlen(temp);
338     if (1 <= len && temp[len - 1] == '\n')
339     {
340         temp[len - 1] = '\0';
341     }
342
343     OIC_LOG_V(DEBUG, MBED_TLS_TAG, "%s", str);
344 }
345 #endif
346
347 /**
348  * structure to holds the information of cache message and address info.
349  */
350 typedef ByteArray_t SslCacheMessage_t;
351
352
353 /**
354  * Data structure for holding the send and recv callbacks.
355  */
356 typedef struct TlsCallBacks
357 {
358     CAPacketReceivedCallback recvCallback;  /**< Callback used to send data to upper layer. */
359     CAPacketSendCallback sendCallback;      /**< Callback used to send data to socket layer. */
360 } SslCallbacks_t;
361
362 /**
363  * Data structure for holding the mbedTLS interface related info.
364  */
365 typedef struct SslContext
366 {
367     u_arraylist_t *peerList;         /**< peer list which holds the mapping between
368                                               peer id, it's n/w address and mbedTLS context. */
369     mbedtls_entropy_context entropy;
370     mbedtls_ctr_drbg_context rnd;
371     mbedtls_x509_crt ca;
372     mbedtls_x509_crt crt;
373     mbedtls_pk_context pkey;
374
375     mbedtls_ssl_config clientTlsConf;
376     mbedtls_ssl_config serverTlsConf;
377     mbedtls_ssl_config clientDtlsConf;
378     mbedtls_ssl_config serverDtlsConf;
379
380     SslCipher_t cipher;
381     SslCallbacks_t adapterCallbacks[MAX_SUPPORTED_ADAPTERS];
382     mbedtls_x509_crl crl;
383     bool cipherFlag[2];
384     int selectedCipher;
385
386 #ifdef __WITH_DTLS__
387     mbedtls_ssl_cookie_ctx cookieCtx;
388     int timerId;
389 #endif
390
391 } SslContext_t;
392
393 /**
394  * @var g_caSslContext
395  * @brief global context which holds tls context and cache list information.
396  */
397 static SslContext_t * g_caSslContext = NULL;
398
399 /**
400  * @var g_getCredentialsCallback
401  * @brief callback to get TLS credentials (same as for DTLS)
402  */
403 static CAgetPskCredentialsHandler g_getCredentialsCallback = NULL;
404 /**
405  * @var g_getCerdentilTypesCallback
406  * @brief callback to get different credential types from SRM
407  */
408 static CAgetCredentialTypesHandler g_getCredentialTypesCallback = NULL;
409 /**
410  * @var g_getPkixInfoCallback
411  *
412  * @brief callback to get X.509-based Public Key Infrastructure
413  */
414 static CAgetPkixInfoHandler g_getPkixInfoCallback = NULL;
415
416 /**
417  * @var g_dtlsContextMutex
418  * @brief Mutex to synchronize access to g_caSslContext.
419  */
420 static oc_mutex g_sslContextMutex = NULL;
421
422 /**
423  * @var g_sslCallback
424  * @brief callback to deliver the TLS handshake result
425  */
426 static CAErrorCallback g_sslCallback = NULL;
427
428 /**
429  * Data structure for holding the data to be received.
430  */
431 typedef struct SslRecBuf
432 {
433     uint8_t * buff;
434     size_t len;
435     size_t loaded;
436 } SslRecBuf_t;
437 /**
438  * Data structure for holding the data related to endpoint
439  * and TLS session.
440  */
441 typedef struct SslEndPoint
442 {
443     mbedtls_ssl_context ssl;
444     CASecureEndpoint_t sep;
445     u_arraylist_t * cacheList;
446     SslRecBuf_t recBuf;
447     uint8_t master[MASTER_SECRET_LEN];
448     uint8_t random[2*RANDOM_LEN];
449 #ifdef __WITH_DTLS__
450     mbedtls_timing_delay_context timer;
451 #endif // __WITH_DTLS__
452 } SslEndPoint_t;
453
454 void CAsetPskCredentialsCallback(CAgetPskCredentialsHandler credCallback)
455 {
456     // TODO Does this method needs protection of tlsContextMutex?
457     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
458     g_getCredentialsCallback = credCallback;
459     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
460 }
461
462 void CAsetPkixInfoCallback(CAgetPkixInfoHandler infoCallback)
463 {
464     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
465     g_getPkixInfoCallback = infoCallback;
466     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
467 }
468 void CAsetCredentialTypesCallback(CAgetCredentialTypesHandler credTypesCallback)
469 {
470     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
471     g_getCredentialTypesCallback = credTypesCallback;
472     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
473 }
474
475 static int GetAdapterIndex(CATransportAdapter_t adapter)
476 {
477     switch (adapter)
478     {
479         case CA_ADAPTER_IP:
480             return 0;
481         case CA_ADAPTER_TCP:
482             return 1;
483         case CA_ADAPTER_GATT_BTLE:
484             return 2;
485         default:
486             OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
487             return -1;
488     }
489 }
490 /**
491  * Write callback.
492  *
493  * @param[in]  tep    TLS endpoint
494  * @param[in]  data    message
495  * @param[in]  dataLen    message length
496  *
497  * @return  message length or -1 on error.
498  */
499 static int SendCallBack(void * tep, const unsigned char * data, size_t dataLen)
500 {
501     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
502     VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "secure endpoint is NULL", -1);
503     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", -1);
504     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
505     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data len: %" PRIuPTR, dataLen);
506     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Adapter: %u", ((SslEndPoint_t * )tep)->sep.endpoint.adapter);
507     ssize_t sentLen = 0;
508     int adapterIndex = GetAdapterIndex(((SslEndPoint_t * )tep)->sep.endpoint.adapter);
509     if (0 <= adapterIndex && MAX_SUPPORTED_ADAPTERS > adapterIndex)
510     {
511         size_t dataToSend = (dataLen > INT_MAX) ? INT_MAX : dataLen;
512         CAPacketSendCallback sendCallback = g_caSslContext->adapterCallbacks[adapterIndex].sendCallback;
513         sentLen = sendCallback(&(((SslEndPoint_t * )tep)->sep.endpoint), (const void *) data, dataToSend);
514         if (sentLen != dataLen)
515         {
516             OIC_LOG_V(DEBUG, NET_SSL_TAG,
517                       "Packet was partially sent - sent/total/remained bytes : %d/%" PRIuPTR "/%" PRIuPTR,
518                       sentLen, dataLen, (dataLen - sentLen));
519         }
520     }
521     else
522     {
523         OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
524         return -1;
525     }
526
527     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
528     return (int)sentLen;
529 }
530 /**
531  * Read callback.
532  *
533  * @param[in]  tep    TLS endpoint
534  * @param[in]  data    message
535  * @param[in]  dataLen    message length
536  *
537  * @return  read length
538  */
539 static int RecvCallBack(void * tep, unsigned char * data, size_t dataLen)
540 {
541     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
542     VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "endpoint is NULL", 0);
543     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", 0);
544
545     SslRecBuf_t *recBuf = &((SslEndPoint_t *)tep)->recBuf;
546     size_t retLen = ((recBuf->len > recBuf->loaded) ? (recBuf->len - recBuf->loaded) : 0);
547     retLen = (retLen < dataLen) ? retLen : dataLen;
548
549     if (retLen > INT_MAX)
550     {
551         return 0;
552     }
553
554     memcpy(data, recBuf->buff + recBuf->loaded, retLen);
555     recBuf->loaded += retLen;
556
557     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
558     return (int)retLen;
559 }
560
561 /**
562  * Parse chain of X.509 certificates.
563  *
564  * @param[out] crt     container for X.509 certificates
565  * @param[in]  data    buffer with X.509 certificates. Certificates may be in either in PEM
566                        or DER format in a jumble, delimiting symbols does not matter.
567  * @param[in]  bufLen  buffer length
568  * @param[in]  errNum  number certificates that failed to parse
569  *
570  * @return  number of successfully parsed certificates or -1 on error
571  */
572 static size_t ParseChain(mbedtls_x509_crt * crt, unsigned char * buf, size_t bufLen, int * errNum)
573 {
574     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
575     VERIFY_NON_NULL_RET(crt, NET_SSL_TAG, "Param crt is NULL" , -1);
576     VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "Param buf is NULL" , -1);
577
578     char pemCertHeader[] = {
579         0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52,
580         0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
581     };
582     char pemCertFooter[] = {
583         0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49,
584         0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
585     };
586     size_t pemCertHeaderLen = sizeof(pemCertHeader);
587     size_t pemCertFooterLen = sizeof(pemCertFooter);
588
589     size_t len = 0;
590     unsigned char * tmp = NULL;
591     size_t count = 0;
592     int ret = 0;
593     size_t pos = 0;
594
595     *errNum = 0;
596     while (pos < bufLen)
597     {
598         if (buf[pos] == 0x30 && buf[pos + 1] == 0x82)
599         {
600             tmp = (unsigned char *)buf + pos + 1;
601             CHECK_MBEDTLS_RET(mbedtls_asn1_get_len, &tmp, buf + bufLen, &len);
602             if (pos + len < bufLen)
603             {
604                 ret = mbedtls_x509_crt_parse_der(crt, buf + pos, len + 4);
605                 if (0 == ret)
606                 {
607                     count++;
608                 }
609                 else
610                 {
611                     (*errNum)++;
612                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse_der returned -0x%04x\n", -(ret));
613                 }
614             }
615             pos += len + 4;
616         }
617         else if ((buf + pos + pemCertHeaderLen < buf + bufLen) &&
618                  (0 == memcmp(buf + pos, pemCertHeader, pemCertHeaderLen)))
619         {
620             void * endPos = NULL;
621             endPos = memmem(&(buf[pos]), bufLen - pos, pemCertFooter, pemCertFooterLen);
622             if (NULL == endPos)
623             {
624                 OIC_LOG(ERROR, NET_SSL_TAG, "Error: end of PEM certificate not found.");
625                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
626                 return -1;
627             }
628             len = (char*)endPos - ((char*)buf + pos) + pemCertFooterLen;
629             if (pos + len + 1 <= bufLen)
630             {
631                 char con = buf[pos + len];
632                 buf[pos + len] = 0x00;
633                 ret = mbedtls_x509_crt_parse(crt, buf + pos, len + 1);
634                 if (0 == ret)
635                 {
636                     count++;
637                 }
638                 else
639                 {
640                     (*errNum)++;
641                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse returned -0x%04x\n", -(ret));
642                 }
643                 buf[pos + len] = con;
644             }
645             else
646             {
647                 unsigned char * lastCert = (unsigned char *)OICMalloc((len + 1) * sizeof(unsigned char));
648                 memcpy(lastCert, buf + pos, len);
649                 lastCert[len] = 0x00;
650                 ret = mbedtls_x509_crt_parse(crt, lastCert, len + 1);
651                 if (0 == ret)
652                 {
653                     count++;
654                 }
655                 else
656                 {
657                     (*errNum)++;
658                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse returned -0x%04x\n", -(ret));
659                 }
660                 OICFree(lastCert);
661             }
662             pos += len;
663         }
664         else
665         {
666             pos++;
667         }
668     }
669     OIC_LOG_V(DEBUG, NET_SSL_TAG, "%s successfully parsed %d certificates", __func__, count);
670     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
671     return count;
672
673 exit:
674     return -1;
675 }
676
677 //Loads PKIX related information from SRM
678 static int InitPKIX(CATransportAdapter_t adapter)
679 {
680     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
681     VERIFY_NON_NULL_RET(g_getPkixInfoCallback, NET_SSL_TAG, "PKIX info callback is NULL", -1);
682     // load pk key, cert, trust chain and crl
683     if (g_getPkixInfoCallback)
684     {
685         g_getPkixInfoCallback(&g_pkiInfo);
686     }
687
688     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
689
690     mbedtls_x509_crt_free(&g_caSslContext->ca);
691     mbedtls_x509_crt_free(&g_caSslContext->crt);
692     mbedtls_pk_free(&g_caSslContext->pkey);
693     mbedtls_x509_crl_free(&g_caSslContext->crl);
694
695     mbedtls_x509_crt_init(&g_caSslContext->ca);
696     mbedtls_x509_crt_init(&g_caSslContext->crt);
697     mbedtls_pk_init(&g_caSslContext->pkey);
698     mbedtls_x509_crl_init(&g_caSslContext->crl);
699
700     mbedtls_ssl_config * serverConf = (adapter == CA_ADAPTER_IP ||
701                                    adapter == CA_ADAPTER_GATT_BTLE ?
702                                    &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
703     mbedtls_ssl_config * clientConf = (adapter == CA_ADAPTER_IP ||
704                                    adapter == CA_ADAPTER_GATT_BTLE ?
705                                    &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
706     // optional
707     int ret;
708     int errNum;
709     size_t count = ParseChain(&g_caSslContext->crt, g_pkiInfo.crt.data, g_pkiInfo.crt.len, &errNum);
710     if (0 >= count)
711     {
712         OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate chain parsing error");
713         goto required;
714     }
715     if (0 != errNum)
716     {
717         OIC_LOG_V(WARNING, NET_SSL_TAG, "Own certificate chain parsing error: %d certs failed to parse", errNum);
718         goto required;
719     }
720     ret =  mbedtls_pk_parse_key(&g_caSslContext->pkey, g_pkiInfo.key.data, g_pkiInfo.key.len,
721                                                                                NULL, 0);
722     if (0 != ret)
723     {
724         OIC_LOG(WARNING, NET_SSL_TAG, "Key parsing error");
725         goto required;
726     }
727
728     ret = mbedtls_ssl_conf_own_cert(serverConf, &g_caSslContext->crt, &g_caSslContext->pkey);
729     if (0 != ret)
730     {
731         OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate parsing error");
732         goto required;
733     }
734     ret = mbedtls_ssl_conf_own_cert(clientConf, &g_caSslContext->crt, &g_caSslContext->pkey);
735     if(0 != ret)
736     {
737         OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate configuration error");
738         goto required;
739     }
740
741     required:
742     count = ParseChain(&g_caSslContext->ca, g_pkiInfo.ca.data, g_pkiInfo.ca.len, &errNum);
743     if(0 >= count)
744     {
745         OIC_LOG(ERROR, NET_SSL_TAG, "CA chain parsing error");
746         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
747         return -1;
748     }
749     if(0 != errNum)
750     {
751         OIC_LOG_V(WARNING, NET_SSL_TAG, "CA chain parsing warning: %d certs failed to parse", errNum);
752     }
753
754     ret = mbedtls_x509_crl_parse_der(&g_caSslContext->crl, g_pkiInfo.crl.data, g_pkiInfo.crl.len);
755     if(0 != ret)
756     {
757         OIC_LOG(WARNING, NET_SSL_TAG, "CRL parsing error");
758         CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain, &g_caSslContext->ca, NULL);
759     }
760     else
761     {
762         CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain,
763                  &g_caSslContext->ca, &g_caSslContext->crl);
764     }
765
766     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
767     return 0;
768 }
769
770 /*
771  * PSK callback.
772  *
773  * @param[in]  notUsed     opaque context
774  * @param[in]  ssl    mbedTLS context
775  * @param[in]  desc    identity
776  * @param[in]  descLen    identity length
777  *
778  * @return  0 on success any other return value will result in a denied PSK identity
779  */
780 static int GetPskCredentialsCallback(void * notUsed, mbedtls_ssl_context * ssl,
781                                      const unsigned char * desc, size_t descLen)
782 {
783     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
784     VERIFY_NON_NULL_RET(g_getCredentialsCallback, NET_SSL_TAG, "Credential callback s NULL", -1);
785     VERIFY_NON_NULL_RET(ssl, NET_SSL_TAG, "ssl pointer is NULL", -1);
786     VERIFY_NON_NULL_RET(desc, NET_SSL_TAG, "desc pointer is NULL", -1);
787     VERIFY_TRUE_RET((descLen <= CA_MAX_ENDPOINT_IDENTITY_LEN), NET_SSL_TAG,
788                     "desc too long!", -1);
789
790     (void) notUsed;
791     uint8_t keyBuf[PSK_LENGTH] = {0};
792
793     // Retrieve the credentials blob from security module
794     int ret = g_getCredentialsCallback(CA_DTLS_PSK_KEY, desc, descLen, keyBuf, PSK_LENGTH);
795     if (ret > 0)
796     {
797         memcpy(((SslEndPoint_t *) ssl)->sep.identity.id, desc, descLen);
798         ((SslEndPoint_t *) ssl)->sep.identity.id_length = (uint16_t)descLen;
799         OIC_LOG(DEBUG, NET_SSL_TAG, "PSK:");
800         OIC_LOG_BUFFER(DEBUG, NET_SSL_TAG, keyBuf, ret);
801
802         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
803         return(mbedtls_ssl_set_hs_psk(ssl, keyBuf, ret));
804     }
805     OIC_LOG_V(WARNING, NET_SSL_TAG, "Out %s", __func__);
806     return -1;
807 }
808 /**
809  * Gets session corresponding for endpoint.
810  *
811  * @param[in]  peer    remote address
812  *
813  * @return  TLS session or NULL
814  */
815 static SslEndPoint_t *GetSslPeer(const CAEndpoint_t *peer)
816 {
817     size_t listIndex = 0;
818     size_t listLength = 0;
819     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
820     VERIFY_NON_NULL_RET(peer, NET_SSL_TAG, "TLS peer is NULL", NULL);
821     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
822
823     SslEndPoint_t *tep = NULL;
824     listLength = u_arraylist_length(g_caSslContext->peerList);
825     for (listIndex = 0; listIndex < listLength; listIndex++)
826     {
827         tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
828         if (NULL == tep)
829         {
830             continue;
831         }
832
833         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Compare [%s:%d] and [%s:%d] for %d adapter",
834                   peer->addr, peer->port, tep->sep.endpoint.addr, tep->sep.endpoint.port,
835                   peer->adapter);
836
837         if((peer->adapter == tep->sep.endpoint.adapter)
838                 && (0 == strncmp(peer->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA))
839                 && (peer->port == tep->sep.endpoint.port || CA_ADAPTER_GATT_BTLE == peer->adapter))
840         {
841             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
842             return tep;
843         }
844     }
845     OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
846     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
847     return NULL;
848 }
849
850 /**
851  * Gets a copy of CA secure endpoint info corresponding for endpoint.
852  *
853  * @param[in]  peer    remote address
854  * @param[out] sep     copy of secure endpoint data
855  *
856  * @return  CA_STATUS_OK on success; other error code on failure
857  */
858 CAResult_t GetCASecureEndpointData(const CAEndpoint_t* peer, CASecureEndpoint_t* sep)
859 {
860     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
861
862     oc_mutex_lock(g_sslContextMutex);
863     if (NULL == g_caSslContext)
864     {
865         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
866         oc_mutex_unlock(g_sslContextMutex);
867         return CA_STATUS_NOT_INITIALIZED;
868     }
869
870     SslEndPoint_t* sslPeer = GetSslPeer(peer);
871     if(sslPeer)
872     {
873         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
874         memcpy(sep, &sslPeer->sep, sizeof(sslPeer->sep));
875         oc_mutex_unlock(g_sslContextMutex);
876         return CA_STATUS_OK;
877     }
878
879     OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
880     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
881     oc_mutex_unlock(g_sslContextMutex);
882     return CA_STATUS_INVALID_PARAM;
883 }
884
885 /**
886  * Adds a bit to the attributes field of a secure endpoint.
887  *
888  * @param[in]  peer         remote address
889  * @param[in]  newAttribute bit to be added to the attributes field
890  *
891  * @return  true if the secure endpoint has been found, false otherwise.
892  */
893 bool SetCASecureEndpointAttribute(const CAEndpoint_t* peer, uint32_t newAttribute)
894 {
895     bool result = false;
896
897     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s(peer = %s:%u, attribute = %#x)", __func__,
898         peer->addr, (uint32_t)peer->port, newAttribute);
899
900     // Acquiring g_sslContextMutex recursively here is not supported, so assert
901     // that the caller already owns this mutex. IOT-1876 tracks a possible
902     // refactoring of the code that is using g_sslContextMutex, to address these
903     // API quirks.
904     oc_mutex_assert_owner(g_sslContextMutex, true);
905
906     if (NULL == g_caSslContext)
907     {
908         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
909     }
910     else
911     {
912         SslEndPoint_t* sslPeer = GetSslPeer(peer);
913
914         if (!sslPeer)
915         {
916             OIC_LOG(ERROR, NET_SSL_TAG, "SSL peer not found");
917         }
918         else
919         {
920             sslPeer->sep.attributes |= newAttribute;
921             result = true;
922         }
923     }
924
925     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s -> %s", __func__, result ? "success" : "failed");
926     return result;
927 }
928
929 /**
930  * Gets the attributes field of a secure endpoint.
931  *
932  * @param[in]  peer          remote address
933  * @param[out] allAttributes all the attributes bits for that remote address
934  *
935  * @return  true if the secure endpoint has been found, false otherwise.
936  */
937 bool GetCASecureEndpointAttributes(const CAEndpoint_t* peer, uint32_t* allAttributes)
938 {
939     bool result = false;
940
941     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s(peer = %s:%u)", __func__,
942         peer->addr, (uint32_t)peer->port);
943
944     oc_mutex_lock(g_sslContextMutex);
945
946     if (NULL == g_caSslContext)
947     {
948         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
949     }
950     else
951     {
952         SslEndPoint_t* sslPeer = GetSslPeer(peer);
953
954         if (!sslPeer)
955         {
956             OIC_LOG(ERROR, NET_SSL_TAG, "SSL peer not found");
957         }
958         else
959         {
960             *allAttributes = sslPeer->sep.attributes;
961             result = true;
962         }
963     }
964
965     oc_mutex_unlock(g_sslContextMutex);
966
967     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s -> %s, attributes = %#x", __func__,
968         result ? "success" : "failed", result ? *allAttributes : 0);
969     return result;
970 }
971
972 /**
973  * Deletes cached message.
974  *
975  * @param[in]  msg    message
976  */
977 static void DeleteCacheMessage(SslCacheMessage_t * msg)
978 {
979     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
980     VERIFY_NON_NULL_VOID(msg, NET_SSL_TAG, "msg");
981
982     OICFree(msg->data);
983     OICFree(msg);
984
985     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
986 }
987 /**
988  * Deletes cached message list.
989  *
990  * @param[in] cacheList  list of cached messages
991  */
992 static void DeleteCacheList(u_arraylist_t * cacheList)
993 {
994     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
995     VERIFY_NON_NULL_VOID(cacheList, NET_SSL_TAG, "cacheList");
996     size_t listIndex = 0;
997     size_t listLength = 0;
998
999     listLength = u_arraylist_length(cacheList);
1000     for (listIndex = 0; listIndex < listLength; listIndex++)
1001     {
1002         SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(cacheList, listIndex);
1003         if (NULL != msg)
1004         {
1005             DeleteCacheMessage(msg);
1006         }
1007     }
1008     u_arraylist_free(&cacheList);
1009
1010     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1011 }
1012 /**
1013  * Deletes endpoint with session.
1014  *
1015  * @param[in]  tep    endpoint with session info
1016  */
1017 static void DeleteSslEndPoint(SslEndPoint_t * tep)
1018 {
1019     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1020     VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "tep");
1021
1022     mbedtls_ssl_free(&tep->ssl);
1023     DeleteCacheList(tep->cacheList);
1024     OICFree(tep);
1025     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1026 }
1027 /**
1028  * Removes endpoint session from list.
1029  *
1030  * @param[in]  endpoint    remote address
1031  */
1032 static void RemovePeerFromList(CAEndpoint_t * endpoint)
1033 {
1034     VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1035     VERIFY_NON_NULL_VOID(endpoint, NET_SSL_TAG, "endpoint");
1036     size_t listLength = u_arraylist_length(g_caSslContext->peerList);
1037     for (size_t listIndex = 0; listIndex < listLength; listIndex++)
1038     {
1039         SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList, listIndex);
1040         if (NULL == tep)
1041         {
1042             continue;
1043         }
1044         if(0 == strncmp(endpoint->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA)
1045                 && (endpoint->port == tep->sep.endpoint.port))
1046         {
1047             u_arraylist_remove(g_caSslContext->peerList, listIndex);
1048             DeleteSslEndPoint(tep);
1049             return;
1050         }
1051     }
1052 }
1053
1054  /**
1055   * Checks handshake result. Removes peer from list and sends alert
1056   * if handshake failed.
1057   *
1058   * @param[in] peer Remote peer's endpoint.
1059   * @param[in] ret  Error code.
1060   * @param[in] str  Debug string.
1061   * @param[in] msg  Alert message.
1062   *
1063   * @return - "true" if the SSL handshake was successful.
1064   *         - "false" otherwise.
1065   */
1066 static bool checkSslOperation(SslEndPoint_t*  peer,
1067                               int ret,
1068                               const char* str,
1069                               unsigned char msg)
1070 {
1071     if ((0 != ret) &&
1072         (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY != ret) &&
1073         (MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED != ret) &&
1074         (MBEDTLS_ERR_SSL_WANT_READ != ret) &&
1075         (MBEDTLS_ERR_SSL_WANT_WRITE != ret) &&
1076         (MBEDTLS_ERR_SSL_NON_FATAL != ret) &&
1077         (MBEDTLS_SSL_ALERT_MSG_USER_CANCELED != ret) &&
1078         (MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION != ret) &&
1079         (MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT != ret) &&
1080         (MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY != ret) &&
1081         (MBEDTLS_SSL_ALERT_MSG_NO_CERT != ret) &&
1082         (MBEDTLS_SSL_ALERT_MSG_BAD_CERT != ret) &&
1083         (MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT != ret) &&
1084         (MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED != ret) &&
1085         (MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED != ret) &&
1086         (MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN != ret) &&
1087         (MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK != ret) &&
1088         (MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME != ret) &&
1089         (MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY != ret) &&
1090         (MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL != ret))
1091     {
1092         OIC_LOG_V(ERROR, NET_SSL_TAG, "%s: -0x%x", (str), -ret);
1093         if ((MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE != ret) &&
1094             (MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != ret))
1095         {
1096             mbedtls_ssl_send_alert_message(&(peer)->ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, (msg));
1097         }
1098
1099         if (MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != ret)
1100         {
1101             SSL_RES((peer), CA_DTLS_AUTHENTICATION_FAILURE);
1102         }
1103
1104         RemovePeerFromList(&(peer)->sep.endpoint);
1105         return false;
1106     }
1107
1108     return true;
1109 }
1110
1111 /**
1112  * Deletes session list.
1113  */
1114 static void DeletePeerList()
1115 {
1116     VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1117
1118     size_t listLength = u_arraylist_length(g_caSslContext->peerList);
1119     for (size_t listIndex = 0; listIndex < listLength; listIndex++)
1120     {
1121         SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList, listIndex);
1122         if (NULL == tep)
1123         {
1124             continue;
1125         }
1126         if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1127         {
1128             int ret = 0;
1129             do
1130             {
1131                 ret = mbedtls_ssl_close_notify(&tep->ssl);
1132             }
1133             while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
1134         }
1135         DeleteSslEndPoint(tep);
1136     }
1137     u_arraylist_free(&g_caSslContext->peerList);
1138 }
1139
1140 CAResult_t CAcloseSslConnection(const CAEndpoint_t *endpoint)
1141 {
1142     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1143     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
1144
1145     oc_mutex_lock(g_sslContextMutex);
1146     if (NULL == g_caSslContext)
1147     {
1148         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1149         oc_mutex_unlock(g_sslContextMutex);
1150         return CA_STATUS_FAILED;
1151     }
1152     SslEndPoint_t * tep = GetSslPeer(endpoint);
1153     if (NULL == tep)
1154     {
1155         OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
1156         oc_mutex_unlock(g_sslContextMutex);
1157         return CA_STATUS_FAILED;
1158     }
1159     /* No error checking, the connection might be closed already */
1160     int ret = 0;
1161     do
1162     {
1163         ret = mbedtls_ssl_close_notify(&tep->ssl);
1164     }
1165     while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
1166
1167     RemovePeerFromList(&tep->sep.endpoint);
1168     oc_mutex_unlock(g_sslContextMutex);
1169
1170     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1171     return CA_STATUS_OK;
1172 }
1173
1174 void CAcloseSslConnectionAll(CATransportAdapter_t transportType)
1175 {
1176     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1177     oc_mutex_lock(g_sslContextMutex);
1178     if (NULL == g_caSslContext)
1179     {
1180         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1181         oc_mutex_unlock(g_sslContextMutex);
1182         return;
1183     }
1184
1185     size_t listLength = u_arraylist_length(g_caSslContext->peerList);
1186     OIC_LOG_V(DEBUG, NET_SSL_TAG,
1187             "Required transport [%d], peer count [%" PRIuPTR "]", transportType, listLength);
1188     for (size_t i = listLength; i > 0; i--)
1189     {
1190         SslEndPoint_t *tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList, i - 1);
1191         if (NULL == tep)
1192         {
1193             continue;
1194         }
1195         OIC_LOG_V(DEBUG, NET_SSL_TAG, "SSL Connection [%s:%d], Transport [%d]",
1196                   tep->sep.endpoint.addr, tep->sep.endpoint.port, tep->sep.endpoint.adapter);
1197
1198         // check transport matching
1199         if (0 == (tep->sep.endpoint.adapter & transportType))
1200         {
1201             OIC_LOG(DEBUG, NET_SSL_TAG, "Skip the un-matched transport session");
1202             continue;
1203         }
1204
1205         // TODO: need to check below code after socket close is ensured.
1206         /*int ret = 0;
1207         do
1208         {
1209             ret = mbedtls_ssl_close_notify(&tep->ssl);
1210         }
1211         while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);*/
1212
1213         // delete from list
1214         u_arraylist_remove(g_caSslContext->peerList, i - 1);
1215         DeleteSslEndPoint(tep);
1216     }
1217     oc_mutex_unlock(g_sslContextMutex);
1218
1219     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1220     return;
1221 }
1222 /**
1223  * Creates session for endpoint.
1224  *
1225  * @param[in]  endpoint    remote address
1226  * @param[in]  config    mbedTLS configuration info
1227  *
1228  * @return  TLS endpoint or NULL
1229  */
1230 static SslEndPoint_t * NewSslEndPoint(const CAEndpoint_t * endpoint, mbedtls_ssl_config * config)
1231 {
1232     SslEndPoint_t * tep = NULL;
1233     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1234     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint", NULL);
1235     VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "config", NULL);
1236     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
1237
1238     tep = (SslEndPoint_t *) OICCalloc(1, sizeof (SslEndPoint_t));
1239     if (NULL == tep)
1240     {
1241         OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1242         return NULL;
1243     }
1244
1245     tep->sep.endpoint = *endpoint;
1246     tep->sep.endpoint.flags = (CATransportFlags_t)(tep->sep.endpoint.flags | CA_SECURE);
1247
1248     if(0 != mbedtls_ssl_setup(&tep->ssl, config))
1249     {
1250         OIC_LOG(ERROR, NET_SSL_TAG, "Setup failed");
1251         OICFree(tep);
1252         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1253         return NULL;
1254     }
1255
1256     mbedtls_ssl_set_bio(&tep->ssl, tep, SendCallBack, RecvCallBack, NULL);
1257     if (MBEDTLS_SSL_TRANSPORT_DATAGRAM == config->transport)
1258     {
1259         mbedtls_ssl_set_timer_cb(&tep->ssl, &tep->timer,
1260                                   mbedtls_timing_set_delay, mbedtls_timing_get_delay);
1261         if (MBEDTLS_SSL_IS_SERVER == config->endpoint)
1262         {
1263             if (0 != mbedtls_ssl_set_client_transport_id(&tep->ssl,
1264                                     (const unsigned char *) endpoint->addr, sizeof(endpoint->addr)))
1265             {
1266                 OIC_LOG(ERROR, NET_SSL_TAG, "Transport id setup failed!");
1267                 mbedtls_ssl_free(&tep->ssl);
1268                 OICFree(tep);
1269                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1270                 return NULL;
1271             }
1272         }
1273     }
1274     tep->cacheList = u_arraylist_create();
1275     if (NULL == tep->cacheList)
1276     {
1277         OIC_LOG(ERROR, NET_SSL_TAG, "cacheList initialization failed!");
1278         mbedtls_ssl_free(&tep->ssl);
1279         OICFree(tep);
1280         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1281         return NULL;
1282     }
1283     OIC_LOG_V(DEBUG, NET_SSL_TAG, "New [%s role] endpoint added [%s:%d]",
1284             (MBEDTLS_SSL_IS_SERVER==config->endpoint ? "server" : "client"),
1285             endpoint->addr, endpoint->port);
1286     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1287     return tep;
1288 }
1289 /**
1290  * Initializes PSK identity.
1291  *
1292  * @param[out]  config    client/server config to be updated
1293  *
1294  * @return  0 on success or -1 on error
1295  */
1296 static int InitPskIdentity(mbedtls_ssl_config * config)
1297 {
1298     uint8_t idBuf[UUID_LENGTH] = {0};
1299     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1300     VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "Param config is NULL" , -1);
1301
1302     if (0 > g_getCredentialsCallback(CA_DTLS_PSK_IDENTITY, NULL, 0, idBuf, UUID_LENGTH))
1303     {
1304         OIC_LOG(ERROR, NET_SSL_TAG, "Identity not found");
1305         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1306         return -1;
1307     }
1308     if (0 != mbedtls_ssl_conf_psk(config, idBuf, 0, idBuf, UUID_LENGTH))
1309     {
1310         OIC_LOG(ERROR, NET_SSL_TAG, "Identity initialization failed!");
1311         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1312         return -1;
1313     }
1314     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1315     return 0;
1316 }
1317 static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapter)
1318 {
1319     int index = 0;
1320     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1321
1322     VERIFY_NON_NULL_VOID(config, NET_SSL_TAG, "Invaild param");
1323     VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1324     VERIFY_NON_NULL_VOID(g_getCredentialTypesCallback, NET_SSL_TAG, "Param callback is null");
1325
1326     //Resetting cipherFlag
1327     g_caSslContext->cipherFlag[0] = false;
1328     g_caSslContext->cipherFlag[1] = false;
1329
1330     if (NULL == g_getCredentialTypesCallback)
1331     {
1332         OIC_LOG(ERROR, NET_SSL_TAG, "Param callback is null");
1333         return;
1334     }
1335
1336     g_getCredentialTypesCallback(g_caSslContext->cipherFlag);
1337     // Retrieve the PSK credential from SRM
1338     if (true == g_caSslContext->cipherFlag[0] && 0 != InitPskIdentity(config))
1339     {
1340         OIC_LOG(ERROR, NET_SSL_TAG, "PSK identity initialization failed!");
1341     }
1342
1343     // Retrieve the Cert credential from SRM
1344     if (true == g_caSslContext->cipherFlag[1])
1345     {
1346         int ret = InitPKIX(adapter);
1347         if (0 != ret)
1348         {
1349             OIC_LOG(ERROR, NET_SSL_TAG, "Failed to init X.509");
1350         }
1351     }
1352
1353     memset(g_cipherSuitesList, 0, sizeof(g_cipherSuitesList));
1354
1355     // Add the preferred ciphersuite first
1356     if (SSL_CIPHER_MAX != g_caSslContext->cipher)
1357     {
1358         g_cipherSuitesList[index] = tlsCipher[g_caSslContext->cipher][0];
1359         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Preferred ciphersuite added");
1360         index++;
1361     }
1362
1363     // Add PSK ciphersuite
1364     if (true == g_caSslContext->cipherFlag[0] &&
1365                 MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 != tlsCipher[g_caSslContext->cipher][0])
1366     {
1367        g_cipherSuitesList[index] = MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
1368        OIC_LOG(DEBUG, NET_SSL_TAG, "PSK ciphersuite added");
1369        index++;
1370     }
1371
1372     // Add all certificate ciphersuites
1373     if (true == g_caSslContext->cipherFlag[1])
1374     {
1375         for (int i = 0; i < SSL_CIPHER_MAX - 1; i++)
1376         {
1377             if (MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 != tlsCipher[i][0] &&
1378                     i != g_caSslContext->cipher)
1379             {
1380                 g_cipherSuitesList[index] = tlsCipher[i][0];
1381                 index ++;
1382             }
1383         }
1384     }
1385
1386     OIC_LOG(DEBUG, NET_SSL_TAG, "Supported ciphersuites:");
1387     for (int i = 0; i < index; i++)
1388     {
1389         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Ciphersuite %04x", g_cipherSuitesList[i]);
1390     }
1391
1392     mbedtls_ssl_conf_ciphersuites(config, g_cipherSuitesList);
1393
1394     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1395 }
1396 /**
1397  * Initiate TLS handshake with endpoint.
1398  *
1399  * @param[in]  endpoint    remote address
1400  *
1401  * @return  TLS endpoint or NULL
1402  */
1403 static SslEndPoint_t * InitiateTlsHandshake(const CAEndpoint_t *endpoint)
1404 {
1405     int ret = 0;
1406     SslEndPoint_t * tep = NULL;
1407
1408     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1409     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , NULL);
1410     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
1411
1412     mbedtls_ssl_config * config = (endpoint->adapter == CA_ADAPTER_IP ||
1413                                    endpoint->adapter == CA_ADAPTER_GATT_BTLE ?
1414                                    &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
1415     tep = NewSslEndPoint(endpoint, config);
1416     if (NULL == tep)
1417     {
1418         OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1419         return NULL;
1420     }
1421
1422     //Load allowed SVR suites from SVR DB
1423     SetupCipher(config, endpoint->adapter);
1424
1425     ret = u_arraylist_add(g_caSslContext->peerList, (void *) tep);
1426     if (!ret)
1427     {
1428         OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1429         DeleteSslEndPoint(tep);
1430         return NULL;
1431     }
1432
1433     while (MBEDTLS_SSL_HANDSHAKE_OVER > tep->ssl.state)
1434     {
1435         ret = mbedtls_ssl_handshake_step(&tep->ssl);
1436         if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
1437         {
1438             break;
1439         }
1440         else if (-1 == ret)
1441         {
1442             OIC_LOG(ERROR, NET_SSL_TAG, "Handshake failed due to socket error");
1443             RemovePeerFromList(&tep->sep.endpoint);
1444             return NULL;
1445         }
1446         if (!checkSslOperation(tep,
1447                                ret,
1448                                "Handshake error",
1449                                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE))
1450         {
1451             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1452             DeleteSslEndPoint(tep);
1453             return NULL;
1454         }
1455     }
1456     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1457     return tep;
1458 }
1459 #ifdef __WITH_DTLS__
1460 /**
1461  * Stops DTLS retransmission.
1462  */
1463 static void StopRetransmit()
1464 {
1465     if (g_caSslContext)
1466     {
1467         unregisterTimer(g_caSslContext->timerId);
1468         g_caSslContext->timerId= -1;
1469     }
1470 }
1471 #endif
1472 void CAdeinitSslAdapter()
1473 {
1474     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1475
1476     VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "context is NULL");
1477     VERIFY_NON_NULL_VOID(g_sslContextMutex, NET_SSL_TAG, "context mutex is NULL");
1478
1479     //Lock tlsContext mutex
1480     oc_mutex_lock(g_sslContextMutex);
1481
1482     // Clear all lists
1483     DeletePeerList();
1484
1485     // De-initialize mbedTLS
1486     mbedtls_x509_crt_free(&g_caSslContext->crt);
1487     mbedtls_pk_free(&g_caSslContext->pkey);
1488 #ifdef __WITH_TLS__
1489     mbedtls_ssl_config_free(&g_caSslContext->clientTlsConf);
1490     mbedtls_ssl_config_free(&g_caSslContext->serverTlsConf);
1491 #endif // __WITH_TLS__
1492 #ifdef __WITH_DTLS__
1493     mbedtls_ssl_config_free(&g_caSslContext->clientDtlsConf);
1494     mbedtls_ssl_config_free(&g_caSslContext->serverDtlsConf);
1495     mbedtls_ssl_cookie_free(&g_caSslContext->cookieCtx);
1496 #endif // __WITH_DTLS__
1497     mbedtls_ctr_drbg_free(&g_caSslContext->rnd);
1498     mbedtls_entropy_free(&g_caSslContext->entropy);
1499 #ifdef __WITH_DTLS__
1500     StopRetransmit();
1501 #endif
1502     // De-initialize tls Context
1503     OICFree(g_caSslContext);
1504     g_caSslContext = NULL;
1505
1506     // Unlock tlsContext mutex and de-initialize it
1507     oc_mutex_unlock(g_sslContextMutex);
1508     oc_mutex_free(g_sslContextMutex);
1509     g_sslContextMutex = NULL;
1510
1511     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s ", __func__);
1512 }
1513
1514 static int InitConfig(mbedtls_ssl_config * conf, int transport, int mode)
1515 {
1516     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1517     VERIFY_NON_NULL_RET(conf, NET_SSL_TAG, "Param conf is NULL" , -1);
1518     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
1519     mbedtls_ssl_config_init(conf);
1520     if (mbedtls_ssl_config_defaults(conf, mode, transport, MBEDTLS_SSL_PRESET_DEFAULT) != 0)
1521     {
1522         OIC_LOG(ERROR, NET_SSL_TAG, "Config initialization failed!");
1523         return -1;
1524     }
1525
1526     /*
1527      * Configure mbedTLS runtime options. Many options are configured at build
1528      * time, see extlibs/mbedtls/config-iotivity.h
1529      */
1530     mbedtls_ssl_conf_psk_cb(conf, GetPskCredentialsCallback, NULL);
1531     mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, &g_caSslContext->rnd);
1532     mbedtls_ssl_conf_curves(conf, curve[ADAPTER_CURVE_SECP256R1]);
1533     mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1534
1535 #ifdef __WITH_DTLS__
1536     if (MBEDTLS_SSL_TRANSPORT_DATAGRAM == transport &&
1537             MBEDTLS_SSL_IS_SERVER == mode)
1538     {
1539         mbedtls_ssl_conf_dtls_cookies(conf, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check,
1540                                       &g_caSslContext->cookieCtx);
1541     }
1542 #endif // __WITH_DTLS__
1543
1544     /* Set TLS 1.2 as the minimum allowed version. */
1545     mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
1546
1547 #if !defined(NDEBUG) || defined(TB_LOG)
1548     mbedtls_ssl_conf_dbg(conf, DebugSsl, NULL);
1549 #if defined(MBEDTLS_DEBUG_C)
1550     mbedtls_debug_set_threshold(MBED_TLS_DEBUG_LEVEL);
1551 #endif
1552 #endif
1553     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1554     return 0;
1555 }
1556 #ifdef __WITH_DTLS__
1557 /**
1558  * Starts DTLS retransmission.
1559  */
1560 static void StartRetransmit()
1561 {
1562     size_t listIndex = 0;
1563     size_t listLength = 0;
1564     SslEndPoint_t *tep = NULL;
1565
1566     oc_mutex_lock(g_sslContextMutex);
1567     if (NULL == g_caSslContext)
1568     {
1569         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL. Stop retransmission");
1570         oc_mutex_unlock(g_sslContextMutex);
1571         return;
1572     }
1573
1574     if (g_caSslContext->timerId != -1)
1575     {
1576         //clear previous timer
1577         unregisterTimer(g_caSslContext->timerId);
1578
1579         listLength = u_arraylist_length(g_caSslContext->peerList);
1580         for (listIndex = 0; listIndex < listLength; listIndex++)
1581         {
1582             tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
1583             if (NULL == tep
1584                 || (tep->ssl.conf && MBEDTLS_SSL_TRANSPORT_STREAM == tep->ssl.conf->transport)
1585                 || MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1586             {
1587                 continue;
1588             }
1589             int ret = mbedtls_ssl_handshake_step(&tep->ssl);
1590
1591             if (MBEDTLS_ERR_SSL_CONN_EOF != ret)
1592             {
1593                 //start new timer
1594                 registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, StartRetransmit);
1595                 //unlock & return
1596                 if (!checkSslOperation(tep,
1597                                        ret,
1598                                        "Retransmission",
1599                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE))
1600                 {
1601                     oc_mutex_unlock(g_sslContextMutex);
1602                     return;
1603                 }
1604             }
1605         }
1606     }
1607     //start new timer
1608     registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, StartRetransmit);
1609     oc_mutex_unlock(g_sslContextMutex);
1610 }
1611 #endif
1612
1613 CAResult_t CAinitSslAdapter()
1614 {
1615     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1616     // Initialize mutex for tlsContext
1617     if (NULL == g_sslContextMutex)
1618     {
1619         g_sslContextMutex = oc_mutex_new();
1620         VERIFY_NON_NULL_RET(g_sslContextMutex, NET_SSL_TAG, "malloc failed", CA_MEMORY_ALLOC_FAILED);
1621     }
1622     else
1623     {
1624         OIC_LOG(INFO, NET_SSL_TAG, "Done already!");
1625         return CA_STATUS_OK;
1626     }
1627
1628     // Lock tlsContext mutex and create tlsContext
1629     oc_mutex_lock(g_sslContextMutex);
1630     g_caSslContext = (SslContext_t *)OICCalloc(1, sizeof(SslContext_t));
1631
1632     if (NULL == g_caSslContext)
1633     {
1634         OIC_LOG(ERROR, NET_SSL_TAG, "Context malloc failed");
1635         oc_mutex_unlock(g_sslContextMutex);
1636         oc_mutex_free(g_sslContextMutex);
1637         g_sslContextMutex = NULL;
1638         return CA_MEMORY_ALLOC_FAILED;
1639     }
1640
1641     // Create peer list
1642     g_caSslContext->peerList = u_arraylist_create();
1643
1644     if(NULL == g_caSslContext->peerList)
1645     {
1646         OIC_LOG(ERROR, NET_SSL_TAG, "peerList initialization failed!");
1647         OICFree(g_caSslContext);
1648         g_caSslContext = NULL;
1649         oc_mutex_unlock(g_sslContextMutex);
1650         oc_mutex_free(g_sslContextMutex);
1651         g_sslContextMutex = NULL;
1652         return CA_STATUS_FAILED;
1653     }
1654
1655     /* Initialize TLS library
1656      */
1657 #if !defined(NDEBUG) || defined(TB_LOG)
1658 #ifdef MBEDTLS_VERSION_C
1659     char version[MBED_TLS_VERSION_LEN];
1660     mbedtls_version_get_string(version);
1661     OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", version);
1662 #else
1663     OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", MBEDTLS_VERSION_STRING);
1664 #endif
1665 #endif
1666
1667     /* Entropy settings
1668      */
1669     mbedtls_entropy_init(&g_caSslContext->entropy);
1670     mbedtls_ctr_drbg_init(&g_caSslContext->rnd);
1671
1672     if(0 != mbedtls_ctr_drbg_seed(&g_caSslContext->rnd, mbedtls_entropy_func,
1673                                   &g_caSslContext->entropy,
1674                                   (const unsigned char*) PERSONALIZATION_STRING, sizeof(PERSONALIZATION_STRING)))
1675     {
1676         OIC_LOG(ERROR, NET_SSL_TAG, "Seed initialization failed!");
1677         oc_mutex_unlock(g_sslContextMutex);
1678         CAdeinitSslAdapter();
1679         return CA_STATUS_FAILED;
1680     }
1681     mbedtls_ctr_drbg_set_prediction_resistance(&g_caSslContext->rnd, MBEDTLS_CTR_DRBG_PR_ON);
1682
1683 #ifdef __WITH_TLS__
1684     if (0 != InitConfig(&g_caSslContext->clientTlsConf,
1685                         MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_CLIENT))
1686     {
1687         OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
1688         oc_mutex_unlock(g_sslContextMutex);
1689         CAdeinitSslAdapter();
1690         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1691         return CA_STATUS_FAILED;
1692     }
1693
1694     if (0 != InitConfig(&g_caSslContext->serverTlsConf,
1695                         MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_SERVER))
1696     {
1697         OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
1698         oc_mutex_unlock(g_sslContextMutex);
1699         CAdeinitSslAdapter();
1700         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1701         return CA_STATUS_FAILED;
1702     }
1703 #endif // __WITH_TLS__
1704 #ifdef __WITH_DTLS__
1705     mbedtls_ssl_cookie_init(&g_caSslContext->cookieCtx);
1706     if (0 != mbedtls_ssl_cookie_setup(&g_caSslContext->cookieCtx, mbedtls_ctr_drbg_random,
1707                                       &g_caSslContext->rnd))
1708     {
1709         OIC_LOG(ERROR, NET_SSL_TAG, "Cookie setup failed!");
1710         oc_mutex_unlock(g_sslContextMutex);
1711         CAdeinitSslAdapter();
1712         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1713         return CA_STATUS_FAILED;
1714     }
1715
1716     if (0 != InitConfig(&g_caSslContext->clientDtlsConf,
1717                         MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_CLIENT))
1718     {
1719         OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
1720         oc_mutex_unlock(g_sslContextMutex);
1721         CAdeinitSslAdapter();
1722         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1723         return CA_STATUS_FAILED;
1724     }
1725
1726     if (0 != InitConfig(&g_caSslContext->serverDtlsConf,
1727                         MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_SERVER))
1728     {
1729         OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
1730         oc_mutex_unlock(g_sslContextMutex);
1731         CAdeinitSslAdapter();
1732         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1733         return CA_STATUS_FAILED;
1734     }
1735 #endif // __WITH_DTLS__
1736
1737     // set default cipher
1738     g_caSslContext->cipher = SSL_CIPHER_MAX;
1739
1740     // init X.509
1741     mbedtls_x509_crt_init(&g_caSslContext->ca);
1742     mbedtls_x509_crt_init(&g_caSslContext->crt);
1743     mbedtls_pk_init(&g_caSslContext->pkey);
1744     mbedtls_x509_crl_init(&g_caSslContext->crl);
1745
1746 #ifdef __WITH_DTLS__
1747     g_caSslContext->timerId = -1;
1748 #endif
1749
1750    oc_mutex_unlock(g_sslContextMutex);
1751 #ifdef __WITH_DTLS__
1752     StartRetransmit();
1753 #endif
1754
1755     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1756     return CA_STATUS_OK;
1757 }
1758
1759 SslCacheMessage_t *  NewCacheMessage(uint8_t * data, size_t dataLen)
1760 {
1761     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1762     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , NULL);
1763     if (0 == dataLen)
1764     {
1765         OIC_LOG(ERROR, NET_SSL_TAG, "dataLen is equal to zero");
1766         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1767         return NULL;
1768     }
1769     SslCacheMessage_t * message = (SslCacheMessage_t *) OICCalloc(1, sizeof(SslCacheMessage_t));
1770     if (NULL == message)
1771     {
1772         OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
1773         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1774         return NULL;
1775     }
1776
1777     message->data = (uint8_t *)OICCalloc(dataLen, sizeof(uint8_t));
1778     if (NULL == message->data)
1779     {
1780         OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
1781         OICFree(message);
1782         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1783         return NULL;
1784     }
1785     memcpy(message->data, data, dataLen);
1786     message->len = dataLen;
1787     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1788     return message;
1789 }
1790
1791 /* Send data via TLS connection.
1792  */
1793 CAResult_t CAencryptSsl(const CAEndpoint_t *endpoint,
1794                         void *data, size_t dataLen)
1795 {
1796     int ret = 0;
1797
1798     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s ", __func__);
1799
1800     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG,"Remote address is NULL", CA_STATUS_INVALID_PARAM);
1801     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Data is NULL", CA_STATUS_INVALID_PARAM);
1802     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Port %d", endpoint->port);
1803
1804     if (0 == dataLen)
1805     {
1806         OIC_LOG_V(ERROR, NET_SSL_TAG, "dataLen is zero [%" PRIuPTR "]", dataLen);
1807         return CA_STATUS_FAILED;
1808     }
1809
1810     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data to be encrypted dataLen [%" PRIuPTR "]", dataLen);
1811
1812     oc_mutex_lock(g_sslContextMutex);
1813     if(NULL == g_caSslContext)
1814     {
1815         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1816         oc_mutex_unlock(g_sslContextMutex);
1817         return CA_STATUS_FAILED;
1818     }
1819
1820     SslEndPoint_t * tep = GetSslPeer(endpoint);
1821     if (NULL == tep)
1822     {
1823         tep = InitiateTlsHandshake(endpoint);
1824     }
1825     if (NULL == tep)
1826     {
1827         OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
1828         oc_mutex_unlock(g_sslContextMutex);
1829         return CA_STATUS_FAILED;
1830     }
1831
1832     if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1833     {
1834         unsigned char *dataBuf = (unsigned char *)data;
1835         size_t written = 0;
1836
1837         do
1838         {
1839             ret = mbedtls_ssl_write(&tep->ssl, dataBuf, dataLen - written);
1840             if (ret < 0)
1841             {
1842                 if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
1843                 {
1844                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned 0x%x", -ret);
1845                     RemovePeerFromList(&tep->sep.endpoint);
1846                     oc_mutex_unlock(g_sslContextMutex);
1847                     return CA_STATUS_FAILED;
1848                 }
1849                 continue;
1850             }
1851             OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
1852
1853             dataBuf += ret;
1854             written += ret;
1855         } while (dataLen > written);
1856
1857     }
1858     else
1859     {
1860         SslCacheMessage_t * msg = NewCacheMessage((uint8_t*) data, dataLen);
1861         if (NULL == msg || !u_arraylist_add(tep->cacheList, (void *) msg))
1862         {
1863             OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1864             oc_mutex_unlock(g_sslContextMutex);
1865             return CA_STATUS_FAILED;
1866         }
1867     }
1868
1869     oc_mutex_unlock(g_sslContextMutex);
1870
1871     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1872     return CA_STATUS_OK;
1873 }
1874 /**
1875  * Sends cached messages via TLS connection.
1876  *
1877  * @param[in]  tep    remote address with session info
1878  */
1879 static void SendCacheMessages(SslEndPoint_t * tep)
1880 {
1881     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1882     VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "Param tep is NULL");
1883
1884     size_t listIndex = 0;
1885     size_t listLength = 0;
1886     listLength = u_arraylist_length(tep->cacheList);
1887     for (listIndex = 0; listIndex < listLength;)
1888     {
1889         int ret = 0;
1890         SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(tep->cacheList, listIndex);
1891         if (NULL != msg && NULL != msg->data && 0 != msg->len)
1892         {
1893             unsigned char *dataBuf = (unsigned char *)msg->data;
1894             size_t written = 0;
1895
1896             do
1897             {
1898                 ret = mbedtls_ssl_write(&tep->ssl, dataBuf, msg->len - written);
1899                 if (ret < 0)
1900                 {
1901                     if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
1902                     {
1903                         OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned -0x%x", -ret);
1904                         break;
1905                     }
1906                     continue;
1907                 }
1908                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
1909
1910                 dataBuf += ret;
1911                 written += ret;
1912             } while (msg->len > written);
1913
1914             if (u_arraylist_remove(tep->cacheList, listIndex))
1915             {
1916                 DeleteCacheMessage(msg);
1917                 // Reduce list length by 1 as we removed one element.
1918                 listLength--;
1919             }
1920             else
1921             {
1922                 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_remove failed.");
1923                 break;
1924             }
1925         }
1926         else
1927         {
1928             // Move to the next element
1929             ++listIndex;
1930         }
1931     }
1932     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1933 }
1934
1935 void CAsetSslHandshakeCallback(CAErrorCallback tlsHandshakeCallback)
1936 {
1937     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s(%p)", __func__, tlsHandshakeCallback);
1938     g_sslCallback = tlsHandshakeCallback;
1939     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s(%p)", __func__, tlsHandshakeCallback);
1940 }
1941
1942 /* Read data from TLS connection
1943  */
1944 CAResult_t CAdecryptSsl(const CASecureEndpoint_t *sep, uint8_t *data, size_t dataLen)
1945 {
1946     int ret = 0;
1947     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1948     VERIFY_NON_NULL_RET(sep, NET_SSL_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
1949     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , CA_STATUS_INVALID_PARAM);
1950
1951     oc_mutex_lock(g_sslContextMutex);
1952     if (NULL == g_caSslContext)
1953     {
1954         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1955         oc_mutex_unlock(g_sslContextMutex);
1956         return CA_STATUS_FAILED;
1957     }
1958
1959
1960     SslEndPoint_t * peer = GetSslPeer(&sep->endpoint);
1961     if (NULL == peer)
1962     {
1963         mbedtls_ssl_config * config = (sep->endpoint.adapter == CA_ADAPTER_IP ||
1964                                    sep->endpoint.adapter == CA_ADAPTER_GATT_BTLE ?
1965                                    &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
1966         peer = NewSslEndPoint(&sep->endpoint, config);
1967         if (NULL == peer)
1968         {
1969             OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1970             oc_mutex_unlock(g_sslContextMutex);
1971             return CA_STATUS_FAILED;
1972         }
1973         //Load allowed TLS suites from SVR DB
1974         SetupCipher(config, sep->endpoint.adapter);
1975
1976         ret = u_arraylist_add(g_caSslContext->peerList, (void *) peer);
1977         if (!ret)
1978         {
1979             OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1980             DeleteSslEndPoint(peer);
1981             oc_mutex_unlock(g_sslContextMutex);
1982             return CA_STATUS_FAILED;
1983         }
1984     }
1985
1986     peer->recBuf.buff = data;
1987     peer->recBuf.len = dataLen;
1988     peer->recBuf.loaded = 0;
1989
1990     while (MBEDTLS_SSL_HANDSHAKE_OVER != peer->ssl.state)
1991     {
1992         ret = mbedtls_ssl_handshake_step(&peer->ssl);
1993         if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
1994         {
1995             break;
1996         }
1997
1998         if (MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED == ret)
1999         {
2000             OIC_LOG(DEBUG, NET_SSL_TAG, "Hello verification requested");
2001             mbedtls_ssl_session_reset(&peer->ssl);
2002             mbedtls_ssl_set_client_transport_id(&peer->ssl,
2003                                                 (const unsigned char *) sep->endpoint.addr,
2004                                                  sizeof(sep->endpoint.addr));
2005             ret = mbedtls_ssl_handshake_step(&peer->ssl);
2006         }
2007         uint32_t flags = mbedtls_ssl_get_verify_result(&peer->ssl);
2008         if (0 != flags)
2009         {
2010             OIC_LOG_BUFFER(ERROR, NET_SSL_TAG, (const uint8_t *) &flags, sizeof(flags));
2011             if (!checkSslOperation(peer,
2012                                    (int)flags,
2013                                    "Cert verification failed",
2014                                    GetAlertCode(flags)))
2015             {
2016                 oc_mutex_unlock(g_sslContextMutex);
2017                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2018                 return CA_STATUS_FAILED;
2019             }
2020         }
2021         if (!checkSslOperation(peer,
2022                                ret,
2023                                "Handshake error",
2024                                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE))
2025         {
2026             oc_mutex_unlock(g_sslContextMutex);
2027             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2028             return CA_STATUS_FAILED;
2029         }
2030         if (MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC == peer->ssl.state)
2031         {
2032             memcpy(peer->master, peer->ssl.session_negotiate->master, sizeof(peer->master));
2033             g_caSslContext->selectedCipher = peer->ssl.session_negotiate->ciphersuite;
2034         }
2035         if (MBEDTLS_SSL_CLIENT_KEY_EXCHANGE == peer->ssl.state)
2036         {
2037             memcpy(peer->random, peer->ssl.handshake->randbytes, sizeof(peer->random));
2038         }
2039
2040         if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
2041         {
2042             SSL_RES(peer, CA_STATUS_OK);
2043             if (MBEDTLS_SSL_IS_CLIENT == peer->ssl.conf->endpoint)
2044             {
2045                 SendCacheMessages(peer);
2046             }
2047
2048             int selectedCipher = peer->ssl.session->ciphersuite;
2049             OIC_LOG_V(DEBUG, NET_SSL_TAG, "(D)TLS Session is connected via ciphersuite [0x%x]", selectedCipher);
2050             if (MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 != selectedCipher &&
2051                 MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 != selectedCipher)
2052             {
2053                 const mbedtls_x509_crt * peerCert = mbedtls_ssl_get_peer_cert(&peer->ssl);
2054                 const mbedtls_x509_name * name = NULL;
2055                 uint8_t pubKeyBuf[CA_SECURE_ENDPOINT_PUBLIC_KEY_MAX_LENGTH] = { 0 };
2056                 ret = (NULL == peerCert ? -1 : 0);
2057                 if (!checkSslOperation(peer,
2058                                        ret,
2059                                        "Failed to retrieve cert",
2060                                        MBEDTLS_SSL_ALERT_MSG_NO_CERT))
2061                 {
2062                     oc_mutex_unlock(g_sslContextMutex);
2063                     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2064                     return CA_STATUS_FAILED;
2065                 }
2066
2067                 /* mbedtls_pk_write_pubkey_der takes a non-const mbedtls_pk_context, but inspection
2068                  * shows that every place it's used internally treats it as const, so casting its
2069                  * constness away is safe.
2070                  */
2071                 ret = mbedtls_pk_write_pubkey_der((mbedtls_pk_context *)&peerCert->pk, pubKeyBuf, sizeof(pubKeyBuf));
2072                 if (ret <= 0)
2073                 {
2074                     OIC_LOG_V(ERROR, NET_SSL_TAG, "Failed to copy public key of remote peer: -0x%x", ret);
2075                     oc_mutex_unlock(g_sslContextMutex);
2076                     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2077                     return CA_STATUS_FAILED;
2078                 }
2079                 else if (ret > sizeof(peer->sep.publicKey))
2080                 {
2081                     assert(!"publicKey field of CASecureEndpoint_t is too small for the public key!");
2082                     OIC_LOG(ERROR, NET_SSL_TAG, "Public key of remote peer was too large");
2083                     oc_mutex_unlock(g_sslContextMutex);
2084                     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2085                     return CA_STATUS_FAILED;
2086                 }
2087                 /* DER data is written to the end of the buffer, so we have to skip ahead in it. */
2088                 memcpy(peer->sep.publicKey, (pubKeyBuf + sizeof(pubKeyBuf) - ret), ret);
2089                 peer->sep.publicKeyLength = ret;
2090
2091                 /* Find the CN component of the subject name. */
2092                 for (name = &peerCert->subject; NULL != name; name = name->next)
2093                 {
2094                     if (!name->oid.p)
2095                     {
2096                         continue;
2097                     }
2098
2099                     if ((name->oid.len < MBEDTLS_OID_SIZE(MBEDTLS_OID_AT_CN) ||
2100                         (0 != memcmp(MBEDTLS_OID_AT_CN, name->oid.p, name->oid.len))))
2101                     {
2102                         continue;
2103                     }
2104                 }
2105
2106                 if (NULL == name)
2107                 {
2108                     OIC_LOG(WARNING, NET_SSL_TAG, "no CN RDN found in subject name");
2109                 }
2110                 else
2111                 {
2112                     const size_t uuidBufLen = UUID_STRING_SIZE - 1;
2113                     char uuid[UUID_STRING_SIZE] = { 0 };
2114                     const unsigned char * uuidPos = NULL;
2115                     const unsigned char * userIdPos = NULL;
2116
2117                     uuidPos = (const unsigned char*)memmem(name->val.p, name->val.len,
2118                                                            UUID_PREFIX, sizeof(UUID_PREFIX) - 1);
2119
2120                     /* If UUID_PREFIX is present, ensure there's enough data for the prefix plus an entire
2121                      * UUID, to make sure we don't read past the end of the buffer.
2122                      */
2123                     if ((NULL != uuidPos) && 
2124                         (name->val.len >= ((uuidPos - name->val.p) + (sizeof(UUID_PREFIX) - 1) + uuidBufLen)))
2125                     {
2126                         memcpy(uuid, uuidPos + sizeof(UUID_PREFIX) - 1, uuidBufLen);
2127                         OIC_LOG_V(DEBUG, NET_SSL_TAG, "certificate uuid string: %s", uuid);
2128                         ret = (OCConvertStringToUuid(uuid, peer->sep.identity.id)) ? 0 : -1;
2129                         if (!checkSslOperation(peer,
2130                                                ret,
2131                                                "Failed to convert subject",
2132                                                MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT))
2133                         {
2134                             oc_mutex_unlock(g_sslContextMutex);
2135                             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2136                             return CA_STATUS_FAILED;
2137                         }
2138                     }
2139                     else
2140                     {
2141                         OIC_LOG(WARNING, NET_SSL_TAG, "uuid not found");
2142                     }
2143
2144                     /* If USERID_PREFIX is present, ensure there's enough data for the prefix plus an entire
2145                      * UUID, to make sure we don't read past the end of the buffer.
2146                      */
2147                     userIdPos = (const unsigned char*)memmem(name->val.p, name->val.len,
2148                                                              USERID_PREFIX, sizeof(USERID_PREFIX) - 1);
2149                     if ((NULL != userIdPos) &&
2150                         (name->val.len >= ((userIdPos - name->val.p) + (sizeof(USERID_PREFIX) - 1) + uuidBufLen)))
2151                     {
2152                         memcpy(uuid, userIdPos + sizeof(USERID_PREFIX) - 1, uuidBufLen);
2153                         ret = (OCConvertStringToUuid(uuid, peer->sep.userId.id)) ? 0 : -1;
2154                         if (!checkSslOperation(peer,
2155                                                ret,
2156                                                "Failed to convert subject alt name",
2157                                                MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT))
2158                         {
2159                             oc_mutex_unlock(g_sslContextMutex);
2160                             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2161                             return CA_STATUS_FAILED;
2162                         }
2163                     }
2164                     else
2165                     {
2166                         OIC_LOG(WARNING, NET_SSL_TAG, "Subject alternative name not found");
2167                     }
2168                 }
2169             }
2170             else
2171             {
2172                 /* No public key information for non-certificate-using ciphersuites. */
2173                 memset(&peer->sep.publicKey, 0, sizeof(peer->sep.publicKey));
2174                 peer->sep.publicKeyLength = 0;
2175             }
2176
2177             oc_mutex_unlock(g_sslContextMutex);
2178             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2179             return CA_STATUS_OK;
2180         }
2181     }
2182
2183     if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
2184     {
2185         uint8_t decryptBuffer[TLS_MSG_BUF_LEN] = {0};
2186         do
2187         {
2188             ret = mbedtls_ssl_read(&peer->ssl, decryptBuffer, TLS_MSG_BUF_LEN);
2189         } while (MBEDTLS_ERR_SSL_WANT_READ == ret);
2190
2191         if (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY == ret ||
2192             // TinyDTLS sends fatal close_notify alert
2193             (MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE == ret &&
2194              MBEDTLS_SSL_ALERT_LEVEL_FATAL == peer->ssl.in_msg[0] &&
2195              MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY == peer->ssl.in_msg[1]))
2196         {
2197             OIC_LOG(INFO, NET_SSL_TAG, "Connection was closed gracefully");
2198             RemovePeerFromList(&peer->sep.endpoint);
2199             oc_mutex_unlock(g_sslContextMutex);
2200             return CA_STATUS_OK;
2201         }
2202
2203         if (0 > ret)
2204         {
2205             OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_ssl_read returned -0x%x", -ret);
2206             //SSL_RES(peer, CA_STATUS_FAILED);
2207             RemovePeerFromList(&peer->sep.endpoint);
2208             oc_mutex_unlock(g_sslContextMutex);
2209             return CA_STATUS_FAILED;
2210         }
2211         else if (0 < ret)
2212         {
2213             int adapterIndex = GetAdapterIndex(peer->sep.endpoint.adapter);
2214             if (0 <= adapterIndex && MAX_SUPPORTED_ADAPTERS > adapterIndex)
2215             {
2216                 g_caSslContext->adapterCallbacks[adapterIndex].recvCallback(&peer->sep, decryptBuffer, ret);
2217             }
2218             else
2219             {
2220                 OIC_LOG(ERROR, NET_SSL_TAG, "Unsuported adapter");
2221                 RemovePeerFromList(&peer->sep.endpoint);
2222                 oc_mutex_unlock(g_sslContextMutex);
2223                 return CA_STATUS_FAILED;
2224             }
2225         }
2226     }
2227
2228     oc_mutex_unlock(g_sslContextMutex);
2229     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2230     return CA_STATUS_OK;
2231 }
2232
2233 void CAsetSslAdapterCallbacks(CAPacketReceivedCallback recvCallback,
2234                               CAPacketSendCallback sendCallback,
2235                               CATransportAdapter_t type)
2236 {
2237     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2238     VERIFY_NON_NULL_VOID(sendCallback, NET_SSL_TAG, "sendCallback is NULL");
2239     VERIFY_NON_NULL_VOID(recvCallback, NET_SSL_TAG, "recvCallback is NULL");
2240     oc_mutex_lock(g_sslContextMutex);
2241     if (NULL == g_caSslContext)
2242     {
2243         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2244         oc_mutex_unlock(g_sslContextMutex);
2245         return;
2246     }
2247
2248     switch (type)
2249     {
2250         case CA_ADAPTER_IP:
2251             g_caSslContext->adapterCallbacks[0].recvCallback = recvCallback;
2252             g_caSslContext->adapterCallbacks[0].sendCallback = sendCallback;
2253             break;
2254         case CA_ADAPTER_TCP:
2255             g_caSslContext->adapterCallbacks[1].recvCallback = recvCallback;
2256             g_caSslContext->adapterCallbacks[1].sendCallback = sendCallback;
2257             break;
2258         case CA_ADAPTER_GATT_BTLE:
2259             g_caSslContext->adapterCallbacks[2].recvCallback = recvCallback;
2260             g_caSslContext->adapterCallbacks[2].sendCallback = sendCallback;
2261             break;
2262         default:
2263             OIC_LOG_V(ERROR, NET_SSL_TAG, "Unsupported adapter: %d", type);
2264     }
2265
2266     oc_mutex_unlock(g_sslContextMutex);
2267     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2268 }
2269 /**
2270  * Gets index of the TLS ciphersuite in the SslCipher_t enum.
2271  *
2272  * @param[in]  cipher    TLS chiphersuite code
2273  *
2274  * @return   corresponding enum
2275  */
2276
2277 static SslCipher_t GetCipherIndex(const uint32_t cipher)
2278 {
2279     switch(cipher)
2280     {
2281         case MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256:
2282         {
2283             return SSL_RSA_WITH_AES_256_CBC_SHA256;
2284         }
2285         case MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256:
2286         {
2287             return SSL_RSA_WITH_AES_128_GCM_SHA256;
2288         }
2289         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
2290         {
2291             return SSL_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
2292         }
2293         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2294         {
2295             return SSL_ECDHE_ECDSA_WITH_AES_128_CCM_8;
2296         }
2297         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
2298         {
2299             return SSL_ECDHE_ECDSA_WITH_AES_128_CCM;
2300         }
2301         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2302         {
2303             return SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256;
2304         }
2305         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
2306         {
2307             return SSL_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384;
2308         }
2309         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
2310         {
2311             return SSL_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384;
2312         }
2313         case MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
2314         {
2315             return SSL_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
2316         }
2317         case MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
2318         {
2319             return SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256;
2320         }
2321         case MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256:
2322         {
2323             return SSL_ECDH_ANON_WITH_AES_128_CBC_SHA256;
2324         }
2325         default:
2326         {
2327             return SSL_CIPHER_MAX;
2328         }
2329     }
2330 }
2331
2332 CAResult_t CAsetTlsCipherSuite(const uint32_t cipher)
2333 {
2334     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2335     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL context is not initialized." , CA_STATUS_NOT_INITIALIZED);
2336
2337     CAResult_t res = CA_STATUS_FAILED;
2338     SslCipher_t index = GetCipherIndex(cipher);
2339     if (SSL_CIPHER_MAX == index)
2340     {
2341         OIC_LOG(WARNING, NET_SSL_TAG, "Unknown cipher");
2342     }
2343     else
2344     {
2345 #ifdef __WITH_TLS__
2346         CONF_SSL(&g_caSslContext->clientTlsConf, &g_caSslContext->serverTlsConf,
2347         mbedtls_ssl_conf_ciphersuites, tlsCipher[index]);
2348 #endif
2349 #ifdef __WITH_DTLS__
2350         CONF_SSL(&g_caSslContext->clientDtlsConf, &g_caSslContext->serverDtlsConf,
2351         mbedtls_ssl_conf_ciphersuites, tlsCipher[index]);
2352 #endif
2353         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Selected cipher: 0x%x", cipher);
2354     }
2355     g_caSslContext->cipher = index;
2356
2357     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2358     return CA_STATUS_OK;
2359 }
2360
2361 CAResult_t CAinitiateSslHandshake(const CAEndpoint_t *endpoint)
2362 {
2363     CAResult_t res = CA_STATUS_OK;
2364     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2365     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
2366     oc_mutex_lock(g_sslContextMutex);
2367     if (NULL == InitiateTlsHandshake(endpoint))
2368     {
2369         OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
2370         res = CA_STATUS_FAILED;
2371     }
2372     oc_mutex_unlock(g_sslContextMutex);
2373     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2374     return res;
2375 }
2376 /**
2377  * Expands the secret into blocks of data according
2378  * to the algorithm specified in section 5 of RFC 4346
2379  *
2380  * This function writes upto @p bufLen bytes into the given output buffer @p buf
2381  *
2382  * @param  key    secret key.
2383  * @param  keyLen    secret key length.
2384  * @param  label    A PRF label.
2385  * @param  labelLen     Actual length of @p label.
2386  * @param  random1    Random seed.
2387  * @param  random1Len     Actual length of @p random1 (may be zero).
2388  * @param  random2     Random seed.
2389  * @param  random2Len    Actual length of @p random2 (may be zero).
2390  * @param  buf    Output buffer for generated random data.
2391  * @param  bufLen    Maximum size of @p buf. Must not be larger than INT_MAX.
2392  *
2393  * @return The actual number of bytes written to @p buf or @c -1 on error.
2394  */
2395
2396 static int pHash (const unsigned char *key, size_t keyLen,
2397      const unsigned char *label, size_t labelLen,
2398      const unsigned char *random1, size_t random1Len,
2399      const unsigned char *random2, size_t random2Len,
2400      unsigned char *buf, size_t bufLen)
2401 {
2402     unsigned char A[RANDOM_LEN] = {0};
2403     unsigned char tmp[RANDOM_LEN] = {0};
2404     size_t dLen;   /* digest length */
2405     size_t len = 0;   /* result length */
2406
2407     VERIFY_TRUE_RET(bufLen <= INT_MAX, NET_SSL_TAG, "buffer too large", -1);
2408     VERIFY_NON_NULL_RET(key, NET_SSL_TAG, "key is NULL", -1);
2409     VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", -1);
2410     VERIFY_NON_NULL_RET(random1, NET_SSL_TAG, "random1 is NULL", -1);
2411     VERIFY_NON_NULL_RET(random2, NET_SSL_TAG, "random2 is NULL", -1);
2412     VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "buf is NULL", -1);
2413
2414     mbedtls_md_context_t hmacA;
2415     mbedtls_md_context_t hmacP;
2416
2417     mbedtls_md_init(&hmacA);
2418     mbedtls_md_init(&hmacP);
2419
2420     CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacA, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2421     CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacP, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2422
2423     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen );
2424     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, label, labelLen);
2425     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random1, random1Len);
2426     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random2, random2Len);
2427     CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2428
2429     dLen = RANDOM_LEN;
2430
2431     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2432
2433     while (len + dLen < bufLen)
2434     {
2435         CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2436         CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2437         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2438         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2439         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2440         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2441
2442         CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2443
2444         len += RANDOM_LEN;
2445
2446         memcpy(buf, tmp, dLen);
2447         buf += dLen;
2448
2449         CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacA);
2450         CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen);
2451         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, A, dLen);
2452         CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2453     }
2454
2455     CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2456     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2457     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2458
2459     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2460     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2461     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2462     CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2463
2464     memcpy(buf, tmp, bufLen - len);
2465
2466     mbedtls_md_free(&hmacA);
2467     mbedtls_md_free(&hmacP);
2468     return (int)bufLen;
2469     // exit label required for CHECK_MBEDTLS_RET macro
2470 exit:
2471     mbedtls_md_free(&hmacA);
2472     mbedtls_md_free(&hmacP);
2473     return -1;
2474 }
2475
2476 CAResult_t CAsslGenerateOwnerPsk(const CAEndpoint_t *endpoint,
2477                             const uint8_t* label, const size_t labelLen,
2478                             const uint8_t* rsrcServerDeviceId, const size_t rsrcServerDeviceIdLen,
2479                             const uint8_t* provServerDeviceId, const size_t provServerDeviceIdLen,
2480                             uint8_t* ownerPsk, const size_t ownerPskSize)
2481 {
2482     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2483     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint is NULL", CA_STATUS_INVALID_PARAM);
2484     VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", CA_STATUS_INVALID_PARAM);
2485     VERIFY_NON_NULL_RET(rsrcServerDeviceId, NET_SSL_TAG, "rsrcId is NULL", CA_STATUS_INVALID_PARAM);
2486     VERIFY_NON_NULL_RET(provServerDeviceId, NET_SSL_TAG, "provId is NULL", CA_STATUS_INVALID_PARAM);
2487     VERIFY_NON_NULL_RET(ownerPsk, NET_SSL_TAG, "ownerPSK is NULL", CA_STATUS_INVALID_PARAM);
2488
2489     oc_mutex_lock(g_sslContextMutex);
2490     if (NULL == g_caSslContext)
2491     {
2492         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2493         oc_mutex_unlock(g_sslContextMutex);
2494         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2495         return CA_STATUS_FAILED;
2496     }
2497     SslEndPoint_t * tep = GetSslPeer(endpoint);
2498     if (NULL == tep)
2499     {
2500         OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
2501         oc_mutex_unlock(g_sslContextMutex);
2502         return CA_STATUS_FAILED;
2503     }
2504
2505     // keyBlockLen set up according to OIC 1.1 Security Specification Section 7.3.2
2506     int macKeyLen = 0;
2507     int ivSize = 0;
2508     int keySize = 0;
2509     int keyBlockLen = 0;
2510     if (MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2511         MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2512         MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2513         MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher)
2514     {
2515         // 2 * ( 32 + 0 + 16 ) = 96
2516         macKeyLen = SHA256_MAC_KEY_LENGTH;
2517         ivSize = CBC_IV_LENGTH;
2518         keySize = AES128_KEY_LENGTH;
2519     }
2520     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM == g_caSslContext->selectedCipher ||
2521              MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caSslContext->selectedCipher)
2522     {
2523         // 2 * ( 0 + 4 + 16 ) = 40
2524         macKeyLen = CCM_MAC_KEY_LENGTH;
2525         ivSize = CCM_IV_LENGTH;
2526         keySize = AES128_KEY_LENGTH;
2527     }
2528     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 == g_caSslContext->selectedCipher)
2529     {
2530         // 2 * ( 32 + 12 + 16 ) = 120
2531         macKeyLen = SHA256_MAC_KEY_LENGTH;
2532         ivSize = GCM_IV_LENGTH;
2533         keySize = AES128_KEY_LENGTH;
2534     }
2535     else if (MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 == g_caSslContext->selectedCipher)
2536     {
2537         // 2 * ( 32 + 0 + 32 ) = 128
2538         macKeyLen = SHA256_MAC_KEY_LENGTH;
2539         ivSize = CBC_IV_LENGTH;
2540         keySize = AES256_KEY_LENGTH;
2541     }
2542     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 == g_caSslContext->selectedCipher)
2543     {
2544         // 2 * ( 48 + 0 + 32 ) = 160
2545         macKeyLen = SHA384_MAC_KEY_LENGTH;
2546         ivSize = CBC_IV_LENGTH;
2547         keySize = AES256_KEY_LENGTH;
2548     }
2549     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 == g_caSslContext->selectedCipher)
2550     {
2551         // 2 * ( 48 + 12 + 32 ) = 184
2552         macKeyLen = SHA384_MAC_KEY_LENGTH;
2553         ivSize = GCM_IV_LENGTH;
2554         keySize = AES256_KEY_LENGTH;
2555     }
2556     else if (MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 == g_caSslContext->selectedCipher)
2557     {
2558         // 2 * ( 48 + 12 + 32 ) = 184
2559         macKeyLen = SHA256_MAC_KEY_LENGTH;
2560         ivSize = GCM_IV_LENGTH;
2561         keySize = AES128_KEY_LENGTH;
2562     }
2563     keyBlockLen = 2 * (macKeyLen + keySize + ivSize);
2564
2565     uint8_t * keyblock = (uint8_t *)OICMalloc(keyBlockLen);
2566     if (NULL == keyblock)
2567     {
2568         OIC_LOG(ERROR, NET_SSL_TAG, "Failed to OICMalloc for keyblock");
2569         oc_mutex_unlock(g_sslContextMutex);
2570         return CA_STATUS_FAILED;
2571     }
2572
2573     // "key expansion"
2574     uint8_t lab[] = {0x6b, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70, 0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e};
2575     int ret = pHash(tep->master, sizeof(tep->master), lab, sizeof(lab),
2576                     (tep->random) + RANDOM_LEN, RANDOM_LEN, tep->random, RANDOM_LEN,
2577                     keyblock, keyBlockLen);
2578     if (-1 == ret)
2579     {
2580         OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
2581         OICFree(keyblock);
2582         oc_mutex_unlock(g_sslContextMutex);
2583         return CA_STATUS_FAILED;
2584     }
2585
2586     ret = pHash(keyblock, keyBlockLen, label, labelLen,
2587                 rsrcServerDeviceId, rsrcServerDeviceIdLen,
2588                 provServerDeviceId, provServerDeviceIdLen,
2589                 ownerPsk, ownerPskSize);
2590     if (-1 == ret)
2591     {
2592         OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
2593         OICFree(keyblock);
2594         oc_mutex_unlock(g_sslContextMutex);
2595         return CA_STATUS_FAILED;
2596     }
2597
2598     OICFree(keyblock);
2599     oc_mutex_unlock(g_sslContextMutex);
2600
2601     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2602     return CA_STATUS_OK;
2603 }