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