Fix mbedtls debug format
[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     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data len: %zu", dataLen);
560     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Adapter: %u", ((SslEndPoint_t * )tep)->sep.endpoint.adapter);
561     ssize_t sentLen = 0;
562     int adapterIndex = GetAdapterIndex(((SslEndPoint_t * )tep)->sep.endpoint.adapter);
563     if (0 <= adapterIndex && MAX_SUPPORTED_ADAPTERS > adapterIndex)
564     {
565         CAPacketSendCallback sendCallback = g_caSslContext->adapterCallbacks[adapterIndex].sendCallback;
566         sentLen = sendCallback(&(((SslEndPoint_t * )tep)->sep.endpoint), (const void *) data, dataLen);
567         if (sentLen != dataLen)
568         {
569             OIC_LOG_V(DEBUG, NET_SSL_TAG,
570                       "Packet was partially sent - total/sent/remained bytes : %d/%d/%d",
571                       sentLen, dataLen, (dataLen - sentLen));
572         }
573     }
574     else
575     {
576         OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
577         return -1;
578     }
579
580     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
581     return sentLen;
582 }
583 /**
584  * Read callback.
585  *
586  * @param[in]  tep    TLS endpoint
587  * @param[in]  data    message
588  * @param[in]  dataLen    message length
589  *
590  * @return  read length
591  */
592 static int RecvCallBack(void * tep, unsigned char * data, size_t dataLen)
593 {
594     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
595     VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "endpoint is NULL", 0);
596     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", 0);
597
598     SslRecBuf_t *recBuf = &((SslEndPoint_t *)tep)->recBuf;
599     size_t retLen = (recBuf->len > recBuf->loaded ? recBuf->len - recBuf->loaded : 0);
600     retLen = (retLen < dataLen ? retLen : dataLen);
601
602     memcpy(data, recBuf->buff + recBuf->loaded, retLen);
603     recBuf->loaded += retLen;
604
605     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
606     return (int)retLen;
607 }
608
609 /**
610  * Parse chain of X.509 certificates.
611  *
612  * @param[out] crt     container for X.509 certificates
613  * @param[in]  data    buffer with X.509 certificates. Certificates may be in either in PEM
614                        or DER format in a jumble, delimiting symbols does not matter.
615  * @param[in]  bufLen  buffer length
616  * @param[in]  errNum  number certificates that failed to parse
617  *
618  * @return  number of successfully parsed certificates or -1 on error
619  */
620 static int ParseChain(mbedtls_x509_crt * crt, unsigned char * buf, int bufLen, int * errNum)
621 {
622     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
623     VERIFY_NON_NULL_RET(crt, NET_SSL_TAG, "Param crt is NULL" , -1);
624     VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "Param buf is NULL" , -1);
625
626     char pemCertHeader[] = {
627         0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52,
628         0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
629     };
630     char pemCertFooter[] = {
631         0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49,
632         0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
633     };
634     size_t pemCertHeaderLen = sizeof(pemCertHeader);
635     size_t pemCertFooterLen = sizeof(pemCertFooter);
636
637     size_t len = 0;
638     unsigned char * tmp = NULL;
639     int count = 0;
640     int ret = 0;
641     int pos = 0;
642
643     *errNum = 0;
644     while (pos < bufLen)
645     {
646         if (buf[pos] == 0x30 && buf[pos + 1] == 0x82)
647         {
648             tmp = (unsigned char *)buf + pos + 1;
649             CHECK_MBEDTLS_RET(mbedtls_asn1_get_len, &tmp, buf + bufLen, &len);
650             if (pos + len < bufLen)
651             {
652                 ret = mbedtls_x509_crt_parse_der(crt, buf + pos, len + 4);
653                 if (0 == ret)
654                 {
655                     count++;
656                 }
657                 else
658                 {
659                     (*errNum)++;
660                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse_der returned -0x%04x\n", -(ret));
661                 }
662             }
663             pos += len + 4;
664         }
665         else if ((buf + pos + pemCertHeaderLen < buf + bufLen) &&
666                  (0 == memcmp(buf + pos, pemCertHeader, pemCertHeaderLen)))
667         {
668             void * endPos = NULL;
669             endPos = memmem(&(buf[pos]), bufLen - pos, pemCertFooter, pemCertFooterLen);
670             if (NULL == endPos)
671             {
672                 OIC_LOG(ERROR, NET_SSL_TAG, "Error: end of PEM certificate not found.");
673                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
674                 return -1;
675             }
676             len = (char*)endPos - ((char*)buf + pos) + pemCertFooterLen;
677             if (pos + len + 1 <= bufLen)
678             {
679                 char con = buf[pos + len];
680                 buf[pos + len] = 0x00;
681                 ret = mbedtls_x509_crt_parse(crt, buf + pos, len + 1);
682                 if (0 == ret)
683                 {
684                     count++;
685                 }
686                 else
687                 {
688                     (*errNum)++;
689                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse returned -0x%04x\n", -(ret));
690                 }
691                 buf[pos + len] = con;
692             }
693             else
694             {
695                 unsigned char * lastCert = (unsigned char *)OICMalloc((len + 1) * sizeof(unsigned char));
696                 memcpy(lastCert, buf + pos, len);
697                 lastCert[len] = 0x00;
698                 ret = mbedtls_x509_crt_parse(crt, lastCert, len + 1);
699                 if (0 == ret)
700                 {
701                     count++;
702                 }
703                 else
704                 {
705                     (*errNum)++;
706                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse returned -0x%04x\n", -(ret));
707                 }
708                 OICFree(lastCert);
709             }
710             pos += len;
711         }
712         else
713         {
714             pos++;
715         }
716     }
717     OIC_LOG_V(DEBUG, NET_SSL_TAG, "%s successfully parsed %d certificates", __func__, count);
718     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
719     return count;
720
721 exit:
722     return -1;
723 }
724
725 //Loads PKIX related information from SRM
726 static int InitPKIX(CATransportAdapter_t adapter)
727 {
728     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
729     VERIFY_NON_NULL_RET(g_getPkixInfoCallback, NET_SSL_TAG, "PKIX info callback is NULL", -1);
730     g_getPkixInfoCallback(&g_pkiInfo);
731
732     mbedtls_x509_crt_free(&g_caSslContext->ca);
733     mbedtls_x509_crt_free(&g_caSslContext->crt);
734     mbedtls_pk_free(&g_caSslContext->pkey);
735     mbedtls_x509_crl_free(&g_caSslContext->crl);
736
737     mbedtls_x509_crt_init(&g_caSslContext->ca);
738     mbedtls_x509_crt_init(&g_caSslContext->crt);
739     mbedtls_pk_init(&g_caSslContext->pkey);
740     mbedtls_x509_crl_init(&g_caSslContext->crl);
741
742     mbedtls_ssl_config * serverConf = (adapter == CA_ADAPTER_IP ||
743                                    adapter == CA_ADAPTER_GATT_BTLE ?
744                                    &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
745     mbedtls_ssl_config * clientConf = (adapter == CA_ADAPTER_IP ||
746                                    adapter == CA_ADAPTER_GATT_BTLE ?
747                                    &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
748     // optional
749     int ret;
750     int errNum;
751     int count = ParseChain(&g_caSslContext->crt, g_pkiInfo.crt.data, g_pkiInfo.crt.len, &errNum);
752     if (0 >= count)
753     {
754         OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate chain parsing error");
755         goto required;
756     }
757     if (0 != errNum)
758     {
759         OIC_LOG_V(WARNING, NET_SSL_TAG, "Own certificate chain parsing error: %d certs failed to parse", errNum);
760         goto required;
761     }
762     ret =  mbedtls_pk_parse_key(&g_caSslContext->pkey, g_pkiInfo.key.data, g_pkiInfo.key.len,
763                                                                                NULL, 0);
764     if (0 != ret)
765     {
766         OIC_LOG(WARNING, NET_SSL_TAG, "Key parsing error");
767         goto required;
768     }
769
770     ret = mbedtls_ssl_conf_own_cert(serverConf, &g_caSslContext->crt, &g_caSslContext->pkey);
771     if (0 != ret)
772     {
773         OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate parsing error");
774         goto required;
775     }
776     ret = mbedtls_ssl_conf_own_cert(clientConf, &g_caSslContext->crt, &g_caSslContext->pkey);
777     if(0 != ret)
778     {
779         OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate configuration error");
780         goto required;
781     }
782
783     required:
784     count = ParseChain(&g_caSslContext->ca, g_pkiInfo.ca.data, g_pkiInfo.ca.len, &errNum);
785     if(0 >= count)
786     {
787         OIC_LOG(ERROR, NET_SSL_TAG, "CA chain parsing error");
788         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
789         return -1;
790     }
791     if(0 != errNum)
792     {
793         OIC_LOG_V(WARNING, NET_SSL_TAG, "CA chain parsing warning: %d certs failed to parse", errNum);
794     }
795
796     ret = mbedtls_x509_crl_parse_der(&g_caSslContext->crl, g_pkiInfo.crl.data, g_pkiInfo.crl.len);
797     if(0 != ret)
798     {
799         OIC_LOG(WARNING, NET_SSL_TAG, "CRL parsing error");
800         CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain, &g_caSslContext->ca, NULL);
801     }
802     else
803     {
804         CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain,
805                  &g_caSslContext->ca, &g_caSslContext->crl);
806     }
807
808     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
809     return 0;
810 }
811
812 /*
813  * PSK callback.
814  *
815  * @param[in]  notUsed     opaque context
816  * @param[in]  ssl    mbedTLS context
817  * @param[in]  desc    identity
818  * @param[in]  descLen    identity length
819  *
820  * @return  0 on success any other return value will result in a denied PSK identity
821  */
822 static int GetPskCredentialsCallback(void * notUsed, mbedtls_ssl_context * ssl,
823                                      const unsigned char * desc, size_t descLen)
824 {
825     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
826     VERIFY_NON_NULL_RET(g_getCredentialsCallback, NET_SSL_TAG, "Credential callback s NULL", -1);
827     VERIFY_NON_NULL_RET(ssl, NET_SSL_TAG, "ssl pointer is NULL", -1);
828     VERIFY_NON_NULL_RET(desc, NET_SSL_TAG, "desc pointer is NULL", -1);
829     if (descLen > CA_MAX_ENDPOINT_IDENTITY_LEN)
830     {
831         OIC_LOG(ERROR, NET_SSL_TAG, "desc too long!");
832         return -1;
833     }
834     (void) notUsed;
835     uint8_t keyBuf[PSK_LENGTH] = {0};
836
837     // Retrieve the credentials blob from security module
838     int ret = g_getCredentialsCallback(CA_DTLS_PSK_KEY, desc, descLen, keyBuf, PSK_LENGTH);
839     if (ret > 0)
840     {
841         memcpy(((SslEndPoint_t *) ssl)->sep.identity.id, desc, descLen);
842         ((SslEndPoint_t *) ssl)->sep.identity.id_length = descLen;
843         OIC_LOG(DEBUG, NET_SSL_TAG, "PSK:");
844         OIC_LOG_BUFFER(DEBUG, NET_SSL_TAG, keyBuf, ret);
845
846         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
847         return(mbedtls_ssl_set_hs_psk(ssl, keyBuf, ret));
848     }
849     OIC_LOG_V(WARNING, NET_SSL_TAG, "Out %s", __func__);
850     return -1;
851 }
852 /**
853  * Gets session corresponding for endpoint.
854  *
855  * @param[in]  peer    remote address
856  *
857  * @return  TLS session or NULL
858  */
859 static SslEndPoint_t *GetSslPeer(const CAEndpoint_t *peer)
860 {
861     uint32_t listIndex = 0;
862     uint32_t listLength = 0;
863     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
864     VERIFY_NON_NULL_RET(peer, NET_SSL_TAG, "TLS peer is NULL", NULL);
865
866     SslEndPoint_t *tep = NULL;
867     listLength = u_arraylist_length(g_caSslContext->peerList);
868     for (listIndex = 0; listIndex < listLength; listIndex++)
869     {
870         tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
871         if (NULL == tep)
872         {
873             continue;
874         }
875
876         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Compare [%s:%d] and [%s:%d] for %d adapter",
877                   peer->addr, peer->port, tep->sep.endpoint.addr, tep->sep.endpoint.port,
878                   peer->adapter);
879
880         if((peer->adapter == tep->sep.endpoint.adapter)
881                 && (0 == strncmp(peer->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA))
882                 && (peer->port == tep->sep.endpoint.port || CA_ADAPTER_GATT_BTLE == peer->adapter))
883         {
884             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
885             return tep;
886         }
887     }
888     OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
889     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
890     return NULL;
891 }
892
893 #ifdef MULTIPLE_OWNER
894 /**
895  * Gets CA secure endpoint info corresponding for endpoint.
896  *
897  * @param[in]  peer    remote address
898  *
899  * @return  CASecureEndpoint or NULL
900  */
901 const CASecureEndpoint_t *GetCASecureEndpointData(const CAEndpoint_t* peer)
902 {
903     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
904
905     // TODO: Added as workaround, need to debug
906     oc_mutex_unlock(g_sslContextMutex);
907
908     oc_mutex_lock(g_sslContextMutex);
909     if (NULL == g_caSslContext)
910     {
911         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
912         oc_mutex_unlock(g_sslContextMutex);
913         return NULL;
914     }
915
916     SslEndPoint_t* sslPeer = GetSslPeer(peer);
917     if(sslPeer)
918     {
919         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
920         oc_mutex_unlock(g_sslContextMutex);
921         return &sslPeer->sep;
922     }
923
924     OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
925     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
926     oc_mutex_unlock(g_sslContextMutex);
927     return NULL;
928 }
929 #endif
930
931 /**
932  * Deletes cached message.
933  *
934  * @param[in]  msg    message
935  */
936 static void DeleteCacheMessage(SslCacheMessage_t * msg)
937 {
938     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
939     VERIFY_NON_NULL_VOID(msg, NET_SSL_TAG, "msg");
940
941     OICFree(msg->data);
942     OICFree(msg);
943
944     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
945 }
946 /**
947  * Deletes cached message list.
948  *
949  * @param[in] cacheList  list of cached messages
950  */
951 static void DeleteCacheList(u_arraylist_t * cacheList)
952 {
953     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
954     VERIFY_NON_NULL_VOID(cacheList, NET_SSL_TAG, "cacheList");
955     uint32_t listIndex = 0;
956     uint32_t listLength = 0;
957
958     listLength = u_arraylist_length(cacheList);
959     for (listIndex = 0; listIndex < listLength; listIndex++)
960     {
961         SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(cacheList, listIndex);
962         if (NULL != msg)
963         {
964             DeleteCacheMessage(msg);
965         }
966     }
967     u_arraylist_free(&cacheList);
968
969     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
970 }
971 /**
972  * Deletes endpoint with session.
973  *
974  * @param[in]  tep    endpoint with session info
975  */
976 static void DeleteSslEndPoint(SslEndPoint_t * tep)
977 {
978     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
979     VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "tep");
980
981     mbedtls_ssl_free(&tep->ssl);
982 #ifdef __WITH_DTLS__
983     mbedtls_ssl_cookie_free(&tep->cookieCtx);
984 #endif
985     DeleteCacheList(tep->cacheList);
986     OICFree(tep);
987     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
988 }
989 /**
990  * Removes endpoint session from list.
991  *
992  * @param[in]  endpoint    remote address
993  */
994 static void RemovePeerFromList(CAEndpoint_t * endpoint)
995 {
996     uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
997     VERIFY_NON_NULL_VOID(endpoint, NET_SSL_TAG, "endpoint");
998     for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
999     {
1000         SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
1001         if (NULL == tep)
1002         {
1003             continue;
1004         }
1005         if(0 == strncmp(endpoint->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA)
1006                 && (endpoint->port == tep->sep.endpoint.port))
1007         {
1008             u_arraylist_remove(g_caSslContext->peerList, listIndex);
1009             DeleteSslEndPoint(tep);
1010             return;
1011         }
1012     }
1013 }
1014 /**
1015  * Deletes session list.
1016  */
1017 static void DeletePeerList()
1018 {
1019     uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
1020     for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
1021     {
1022         SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
1023         if (NULL == tep)
1024         {
1025             continue;
1026         }
1027         if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1028         {
1029             int ret = 0;
1030             do
1031             {
1032                 ret = mbedtls_ssl_close_notify(&tep->ssl);
1033             }
1034             while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
1035         }
1036         DeleteSslEndPoint(tep);
1037     }
1038     u_arraylist_free(&g_caSslContext->peerList);
1039 }
1040
1041 CAResult_t CAcloseSslConnection(const CAEndpoint_t *endpoint)
1042 {
1043     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1044     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
1045
1046     oc_mutex_lock(g_sslContextMutex);
1047     if (NULL == g_caSslContext)
1048     {
1049         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1050         oc_mutex_unlock(g_sslContextMutex);
1051         return CA_STATUS_FAILED;
1052     }
1053     SslEndPoint_t * tep = GetSslPeer(endpoint);
1054     if (NULL == tep)
1055     {
1056         OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
1057         oc_mutex_unlock(g_sslContextMutex);
1058         return CA_STATUS_FAILED;
1059     }
1060     /* No error checking, the connection might be closed already */
1061     int ret = 0;
1062     do
1063     {
1064         ret = mbedtls_ssl_close_notify(&tep->ssl);
1065     }
1066     while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
1067
1068     RemovePeerFromList(&tep->sep.endpoint);
1069     oc_mutex_unlock(g_sslContextMutex);
1070
1071     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1072     return CA_STATUS_OK;
1073 }
1074
1075 void CAcloseSslConnectionAll()
1076 {
1077     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1078     oc_mutex_lock(g_sslContextMutex);
1079     if (NULL == g_caSslContext)
1080     {
1081         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1082         oc_mutex_unlock(g_sslContextMutex);
1083         return;
1084     }
1085
1086     uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
1087     for (uint32_t i = listLength; i > 0; i--)
1088     {
1089         SslEndPoint_t *tep = (SslEndPoint_t *)u_arraylist_remove(g_caSslContext->peerList, i - 1);
1090         if (NULL == tep)
1091         {
1092             continue;
1093         }
1094         OIC_LOG_V(DEBUG, NET_SSL_TAG, "SSL Connection [%s:%d]",
1095                   tep->sep.endpoint.addr, tep->sep.endpoint.port);
1096
1097         // TODO: need to check below code after socket close is ensured.
1098         /*int ret = 0;
1099         do
1100         {
1101             ret = mbedtls_ssl_close_notify(&tep->ssl);
1102         }
1103         while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);*/
1104
1105         DeleteSslEndPoint(tep);
1106     }
1107     oc_mutex_unlock(g_sslContextMutex);
1108
1109     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1110     return;
1111 }
1112 /**
1113  * Creates session for endpoint.
1114  *
1115  * @param[in]  endpoint    remote address
1116  * @param[in]  config    mbedTLS configuration info
1117  *
1118  * @return  TLS endpoint or NULL
1119  */
1120 static SslEndPoint_t * NewSslEndPoint(const CAEndpoint_t * endpoint, mbedtls_ssl_config * config)
1121 {
1122     SslEndPoint_t * tep = NULL;
1123     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1124     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint", NULL);
1125     VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "config", NULL);
1126
1127     tep = (SslEndPoint_t *) OICCalloc(1, sizeof (SslEndPoint_t));
1128     if (NULL == tep)
1129     {
1130         OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1131         return NULL;
1132     }
1133
1134     tep->sep.endpoint = *endpoint;
1135     tep->sep.endpoint.flags = (CATransportFlags_t)(tep->sep.endpoint.flags | CA_SECURE);
1136
1137     if(0 != mbedtls_ssl_setup(&tep->ssl, config))
1138     {
1139         OIC_LOG(ERROR, NET_SSL_TAG, "Setup failed");
1140         OICFree(tep);
1141         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1142         return NULL;
1143     }
1144
1145     mbedtls_ssl_set_bio(&tep->ssl, tep, SendCallBack, RecvCallBack, NULL);
1146     if (MBEDTLS_SSL_TRANSPORT_DATAGRAM == config->transport)
1147     {
1148         mbedtls_ssl_set_timer_cb(&tep->ssl, &tep->timer,
1149                                   mbedtls_timing_set_delay, mbedtls_timing_get_delay);
1150         if (MBEDTLS_SSL_IS_SERVER == config->endpoint)
1151         {
1152             if (0 != mbedtls_ssl_cookie_setup(&tep->cookieCtx, mbedtls_ctr_drbg_random,
1153                                               &g_caSslContext->rnd))
1154             {
1155                 OIC_LOG(ERROR, NET_SSL_TAG, "Cookie setup failed!");
1156                 OICFree(tep);
1157                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1158                 return NULL;
1159             }
1160             mbedtls_ssl_conf_dtls_cookies(config, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check,
1161                                           &tep->cookieCtx);
1162             if (0 != mbedtls_ssl_set_client_transport_id(&tep->ssl,
1163                                     (const unsigned char *) endpoint->addr, sizeof(endpoint->addr)))
1164             {
1165                 OIC_LOG(ERROR, NET_SSL_TAG, "Transport id setup failed!");
1166                 OICFree(tep);
1167                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1168                 return NULL;
1169             }
1170         }
1171     }
1172     tep->cacheList = u_arraylist_create();
1173     if (NULL == tep->cacheList)
1174     {
1175         OIC_LOG(ERROR, NET_SSL_TAG, "cacheList initialization failed!");
1176         mbedtls_ssl_free(&tep->ssl);
1177         OICFree(tep);
1178         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1179         return NULL;
1180     }
1181     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1182     return tep;
1183 }
1184 /**
1185  * Initializes PSK identity.
1186  *
1187  * @param[out]  config    client/server config to be updated
1188  *
1189  * @return  0 on success or -1 on error
1190  */
1191 static int InitPskIdentity(mbedtls_ssl_config * config)
1192 {
1193     uint8_t idBuf[UUID_LENGTH] = {0};
1194     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1195     VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "Param config is NULL" , -1);
1196
1197     if (0 > g_getCredentialsCallback(CA_DTLS_PSK_IDENTITY, NULL, 0, idBuf, UUID_LENGTH))
1198     {
1199         OIC_LOG(ERROR, NET_SSL_TAG, "Identity not found");
1200         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1201         return -1;
1202     }
1203     if (0 != mbedtls_ssl_conf_psk(config, idBuf, 0, idBuf, UUID_LENGTH))
1204     {
1205         OIC_LOG(ERROR, NET_SSL_TAG, "Identity initialization failed!");
1206         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1207         return -1;
1208     }
1209     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1210     return 0;
1211 }
1212 static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapter)
1213 {
1214     int index = 0;
1215     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1216     if (NULL == g_getCredentialTypesCallback)
1217     {
1218         OIC_LOG(ERROR, NET_SSL_TAG, "Param callback is null");
1219         return;
1220     }
1221
1222     g_getCredentialTypesCallback(g_caSslContext->cipherFlag);
1223     // Retrieve the PSK credential from SRM
1224     if (0 != InitPskIdentity(config))
1225     {
1226         OIC_LOG(ERROR, NET_SSL_TAG, "PSK identity initialization failed!");
1227     }
1228
1229     // Retrieve the Cert credential from SRM
1230     if (true == g_caSslContext->cipherFlag[1])
1231     {
1232         int ret = InitPKIX(adapter);
1233         if (0 != ret)
1234         {
1235             OIC_LOG(ERROR, NET_SSL_TAG, "Failed to init X.509");
1236         }
1237     }
1238
1239     memset(g_cipherSuitesList, 0, sizeof(g_cipherSuitesList));
1240     if (SSL_CIPHER_MAX != g_caSslContext->cipher)
1241     {
1242         g_cipherSuitesList[index] = tlsCipher[g_caSslContext->cipher][0];
1243     }
1244     else
1245     {
1246     if (true == g_caSslContext->cipherFlag[1])
1247     {
1248         for (int i = 2; i < SSL_CIPHER_MAX - 2; i++)
1249             {
1250                 g_cipherSuitesList[index] = tlsCipher[i][0];
1251                 index ++;
1252             }
1253         }
1254         if (true == g_caSslContext->cipherFlag[0])
1255         {
1256            g_cipherSuitesList[index] = MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
1257         }
1258     }
1259
1260     mbedtls_ssl_conf_ciphersuites(config, g_cipherSuitesList);
1261
1262     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1263 }
1264 /**
1265  * Initiate TLS handshake with endpoint.
1266  *
1267  * @param[in]  endpoint    remote address
1268  *
1269  * @return  TLS endpoint or NULL
1270  */
1271 static SslEndPoint_t * InitiateTlsHandshake(const CAEndpoint_t *endpoint)
1272 {
1273     int ret = 0;
1274     SslEndPoint_t * tep = NULL;
1275
1276     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1277     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , NULL);
1278
1279
1280     mbedtls_ssl_config * config = (endpoint->adapter == CA_ADAPTER_IP ||
1281                                    endpoint->adapter == CA_ADAPTER_GATT_BTLE ?
1282                                    &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
1283     tep = NewSslEndPoint(endpoint, config);
1284     if (NULL == tep)
1285     {
1286         OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1287         return NULL;
1288     }
1289
1290     //Load allowed SVR suites from SVR DB
1291     SetupCipher(config, endpoint->adapter);
1292
1293     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Add %s:%d", tep->sep.endpoint.addr, tep->sep.endpoint.port);
1294     ret = u_arraylist_add(g_caSslContext->peerList, (void *) tep);
1295     if (!ret)
1296     {
1297         OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1298         DeleteSslEndPoint(tep);
1299         return NULL;
1300     }
1301
1302     while (MBEDTLS_SSL_HANDSHAKE_OVER > tep->ssl.state)
1303     {
1304         ret = mbedtls_ssl_handshake_step(&tep->ssl);
1305         if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
1306         {
1307             break;
1308         }
1309         else if (-1 == ret)
1310         {
1311             OIC_LOG(ERROR, NET_SSL_TAG, "Handshake failed due to socket error");
1312             RemovePeerFromList(&tep->sep.endpoint);
1313             return NULL;
1314         }
1315         SSL_CHECK_FAIL(tep, ret, "Handshake error", 0, NULL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1316     }
1317     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1318     return tep;
1319 }
1320 #ifdef __WITH_DTLS__
1321 /**
1322  * Stops DTLS retransmission.
1323  */
1324 static void StopRetransmit()
1325 {
1326     if (g_caSslContext)
1327     {
1328         unregisterTimer(g_caSslContext->timerId);
1329         g_caSslContext->timerId= -1;
1330     }
1331 }
1332 #endif
1333 void CAdeinitSslAdapter()
1334 {
1335     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1336
1337     VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "context is NULL");
1338     VERIFY_NON_NULL_VOID(g_sslContextMutex, NET_SSL_TAG, "context mutex is NULL");
1339
1340     //Lock tlsContext mutex
1341     oc_mutex_lock(g_sslContextMutex);
1342
1343     // Clear all lists
1344     DeletePeerList();
1345
1346     // De-initialize mbedTLS
1347     mbedtls_x509_crt_free(&g_caSslContext->crt);
1348     mbedtls_pk_free(&g_caSslContext->pkey);
1349 #ifdef __WITH_TLS__
1350     mbedtls_ssl_config_free(&g_caSslContext->clientTlsConf);
1351     mbedtls_ssl_config_free(&g_caSslContext->serverTlsConf);
1352 #endif // __WITH_TLS__
1353 #ifdef __WITH_DTLS__
1354     mbedtls_ssl_config_free(&g_caSslContext->clientDtlsConf);
1355     mbedtls_ssl_config_free(&g_caSslContext->serverDtlsConf);
1356 #endif // __WITH_DTLS__
1357     mbedtls_ctr_drbg_free(&g_caSslContext->rnd);
1358     mbedtls_entropy_free(&g_caSslContext->entropy);
1359 #ifdef __WITH_DTLS__
1360     StopRetransmit();
1361 #endif
1362     // De-initialize tls Context
1363     OICFree(g_caSslContext);
1364     g_caSslContext = NULL;
1365
1366     // Unlock tlsContext mutex and de-initialize it
1367     oc_mutex_unlock(g_sslContextMutex);
1368     oc_mutex_free(g_sslContextMutex);
1369     g_sslContextMutex = NULL;
1370
1371     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s ", __func__);
1372 }
1373
1374 static int InitConfig(mbedtls_ssl_config * conf, int transport, int mode)
1375 {
1376     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1377     VERIFY_NON_NULL_RET(conf, NET_SSL_TAG, "Param conf is NULL" , -1);
1378     mbedtls_ssl_config_init(conf);
1379     if (mbedtls_ssl_config_defaults(conf, mode, transport, MBEDTLS_SSL_PRESET_DEFAULT) != 0)
1380     {
1381         OIC_LOG(ERROR, NET_SSL_TAG, "Config initialization failed!");
1382         return -1;
1383     }
1384
1385     /*
1386      * Configure mbedTLS runtime options. Many options are configured at build
1387      * time, see extlibs/mbedtls/config-iotivity.h
1388      */
1389     mbedtls_ssl_conf_psk_cb(conf, GetPskCredentialsCallback, NULL);
1390     mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, &g_caSslContext->rnd);
1391     mbedtls_ssl_conf_curves(conf, curve[ADAPTER_CURVE_SECP256R1]);
1392     mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1393
1394     /* Set TLS 1.2 as the minimum allowed version. */
1395     mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
1396
1397 #if !defined(NDEBUG) || defined(TB_LOG)
1398     mbedtls_ssl_conf_dbg(conf, DebugSsl, NULL);
1399     mbedtls_debug_set_threshold(MBED_TLS_DEBUG_LEVEL);
1400 #endif
1401     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1402     return 0;
1403 }
1404 #ifdef __WITH_DTLS__
1405 /**
1406  * Starts DTLS retransmission.
1407  */
1408 static int StartRetransmit()
1409 {
1410     uint32_t listIndex = 0;
1411     uint32_t listLength = 0;
1412     SslEndPoint_t *tep = NULL;
1413
1414     oc_mutex_lock(g_sslContextMutex);
1415     if (NULL == g_caSslContext)
1416     {
1417         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL. Stop retransmission");
1418         oc_mutex_unlock(g_sslContextMutex);
1419         return -1;
1420     }
1421
1422     if (g_caSslContext->timerId != -1)
1423     {
1424         //clear previous timer
1425         unregisterTimer(g_caSslContext->timerId);
1426
1427         listLength = u_arraylist_length(g_caSslContext->peerList);
1428         for (listIndex = 0; listIndex < listLength; listIndex++)
1429         {
1430             tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
1431             if (NULL == tep
1432                 || (tep->ssl.conf && MBEDTLS_SSL_TRANSPORT_STREAM == tep->ssl.conf->transport)
1433                 || MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1434             {
1435                 continue;
1436             }
1437             int ret = mbedtls_ssl_handshake_step(&tep->ssl);
1438
1439             if (MBEDTLS_ERR_SSL_CONN_EOF != ret)
1440             {
1441                 //start new timer
1442                 registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, (void *) StartRetransmit);
1443                 //unlock & return
1444                 SSL_CHECK_FAIL(tep, ret, "Retransmission", 1, CA_STATUS_FAILED,
1445                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1446             }
1447         }
1448     }
1449     //start new timer
1450     registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, (void *) StartRetransmit);
1451     oc_mutex_unlock(g_sslContextMutex);
1452     return 0;
1453 }
1454 #endif
1455
1456 CAResult_t CAinitSslAdapter()
1457 {
1458     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1459     // Initialize mutex for tlsContext
1460     if (NULL == g_sslContextMutex)
1461     {
1462         g_sslContextMutex = oc_mutex_new();
1463         VERIFY_NON_NULL_RET(g_sslContextMutex, NET_SSL_TAG, "malloc failed", CA_MEMORY_ALLOC_FAILED);
1464     }
1465     else
1466     {
1467         OIC_LOG(INFO, NET_SSL_TAG, "Done already!");
1468         return CA_STATUS_OK;
1469     }
1470
1471     // Lock tlsContext mutex and create tlsContext
1472     oc_mutex_lock(g_sslContextMutex);
1473     g_caSslContext = (SslContext_t *)OICCalloc(1, sizeof(SslContext_t));
1474
1475     if (NULL == g_caSslContext)
1476     {
1477         OIC_LOG(ERROR, NET_SSL_TAG, "Context malloc failed");
1478         oc_mutex_unlock(g_sslContextMutex);
1479         oc_mutex_free(g_sslContextMutex);
1480         g_sslContextMutex = NULL;
1481         return CA_MEMORY_ALLOC_FAILED;
1482     }
1483
1484     // Create peer list
1485     g_caSslContext->peerList = u_arraylist_create();
1486
1487     if(NULL == g_caSslContext->peerList)
1488     {
1489         OIC_LOG(ERROR, NET_SSL_TAG, "peerList initialization failed!");
1490         OICFree(g_caSslContext);
1491         g_caSslContext = NULL;
1492         oc_mutex_unlock(g_sslContextMutex);
1493         oc_mutex_free(g_sslContextMutex);
1494         g_sslContextMutex = NULL;
1495         return CA_STATUS_FAILED;
1496     }
1497
1498     /* Initialize TLS library
1499      */
1500 #if !defined(NDEBUG) || defined(TB_LOG)
1501 #ifdef MBEDTLS_VERSION_C
1502     char version[MBED_TLS_VERSION_LEN];
1503     mbedtls_version_get_string(version);
1504     OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", version);
1505 #else
1506     OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", MBEDTLS_VERSION_STRING);
1507 #endif
1508 #endif
1509
1510     /* Entropy settings
1511      */
1512     mbedtls_entropy_init(&g_caSslContext->entropy);
1513     mbedtls_ctr_drbg_init(&g_caSslContext->rnd);
1514
1515     if(0 != mbedtls_ctr_drbg_seed(&g_caSslContext->rnd, mbedtls_entropy_func,
1516                                   &g_caSslContext->entropy,
1517                                   (const unsigned char*) PERSONALIZATION_STRING, sizeof(PERSONALIZATION_STRING)))
1518     {
1519         OIC_LOG(ERROR, NET_SSL_TAG, "Seed initialization failed!");
1520         oc_mutex_unlock(g_sslContextMutex);
1521         CAdeinitSslAdapter();
1522         return CA_STATUS_FAILED;
1523     }
1524     mbedtls_ctr_drbg_set_prediction_resistance(&g_caSslContext->rnd, MBEDTLS_CTR_DRBG_PR_ON);
1525
1526 #ifdef __WITH_TLS__
1527     if (0 != InitConfig(&g_caSslContext->clientTlsConf,
1528                         MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_CLIENT))
1529     {
1530         OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
1531         oc_mutex_unlock(g_sslContextMutex);
1532         CAdeinitSslAdapter();
1533         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1534         return CA_STATUS_FAILED;
1535     }
1536
1537     if (0 != InitConfig(&g_caSslContext->serverTlsConf,
1538                         MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_SERVER))
1539     {
1540         OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
1541         oc_mutex_unlock(g_sslContextMutex);
1542         CAdeinitSslAdapter();
1543         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1544         return CA_STATUS_FAILED;
1545     }
1546 #endif // __WITH_TLS__
1547 #ifdef __WITH_DTLS__
1548     if (0 != InitConfig(&g_caSslContext->clientDtlsConf,
1549                         MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_CLIENT))
1550     {
1551         OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
1552         oc_mutex_unlock(g_sslContextMutex);
1553         CAdeinitSslAdapter();
1554         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1555         return CA_STATUS_FAILED;
1556     }
1557
1558     if (0 != InitConfig(&g_caSslContext->serverDtlsConf,
1559                         MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_SERVER))
1560     {
1561         OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
1562         oc_mutex_unlock(g_sslContextMutex);
1563         CAdeinitSslAdapter();
1564         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1565         return CA_STATUS_FAILED;
1566     }
1567 #endif // __WITH_DTLS__
1568
1569     // set default cipher
1570     g_caSslContext->cipher = SSL_CIPHER_MAX;
1571
1572     // init X.509
1573     mbedtls_x509_crt_init(&g_caSslContext->ca);
1574     mbedtls_x509_crt_init(&g_caSslContext->crt);
1575     mbedtls_pk_init(&g_caSslContext->pkey);
1576     mbedtls_x509_crl_init(&g_caSslContext->crl);
1577
1578 #ifdef __WITH_DTLS__
1579     g_caSslContext->timerId = -1;
1580 #endif
1581
1582    oc_mutex_unlock(g_sslContextMutex);
1583 #ifdef __WITH_DTLS__
1584     StartRetransmit();
1585 #endif
1586
1587     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1588     return CA_STATUS_OK;
1589 }
1590
1591 SslCacheMessage_t *  NewCacheMessage(uint8_t * data, size_t dataLen)
1592 {
1593     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1594     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , NULL);
1595     if (0 == dataLen)
1596     {
1597         OIC_LOG(ERROR, NET_SSL_TAG, "dataLen is equal to zero");
1598         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1599         return NULL;
1600     }
1601     SslCacheMessage_t * message = (SslCacheMessage_t *) OICCalloc(1, sizeof(SslCacheMessage_t));
1602     if (NULL == message)
1603     {
1604         OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
1605         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1606         return NULL;
1607     }
1608
1609     message->data = (uint8_t *)OICCalloc(dataLen, sizeof(uint8_t));
1610     if (NULL == message->data)
1611     {
1612         OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
1613         OICFree(message);
1614         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1615         return NULL;
1616     }
1617     memcpy(message->data, data, dataLen);
1618     message->len = dataLen;
1619     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1620     return message;
1621 }
1622
1623 /* Send data via TLS connection.
1624  */
1625 CAResult_t CAencryptSsl(const CAEndpoint_t *endpoint,
1626                         void *data, uint32_t dataLen)
1627 {
1628     int ret = 0;
1629
1630     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s ", __func__);
1631
1632     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG,"Remote address is NULL", CA_STATUS_INVALID_PARAM);
1633     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Data is NULL", CA_STATUS_INVALID_PARAM);
1634     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Port %d", endpoint->port);
1635
1636     if (0 == dataLen)
1637     {
1638         OIC_LOG_V(ERROR, NET_SSL_TAG, "dataLen is zero [%d]", dataLen);
1639         return CA_STATUS_FAILED;
1640     }
1641
1642     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data to be encrypted dataLen [%d]", dataLen);
1643
1644     oc_mutex_lock(g_sslContextMutex);
1645     if(NULL == g_caSslContext)
1646     {
1647         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1648         oc_mutex_unlock(g_sslContextMutex);
1649         return CA_STATUS_FAILED;
1650     }
1651
1652     SslEndPoint_t * tep = GetSslPeer(endpoint);
1653     if (NULL == tep)
1654     {
1655         tep = InitiateTlsHandshake(endpoint);
1656     }
1657     if (NULL == tep)
1658     {
1659         OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
1660         oc_mutex_unlock(g_sslContextMutex);
1661         return CA_STATUS_FAILED;
1662     }
1663
1664     if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1665     {
1666         unsigned char *dataBuf = (unsigned char *)data;
1667         size_t written = 0;
1668
1669         do
1670         {
1671             ret = mbedtls_ssl_write(&tep->ssl, dataBuf, dataLen - written);
1672             if (ret < 0)
1673             {
1674                 if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
1675                 {
1676                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned 0x%x", -ret);
1677                     RemovePeerFromList(&tep->sep.endpoint);
1678                     oc_mutex_unlock(g_sslContextMutex);
1679                     return CA_STATUS_FAILED;
1680                 }
1681                 continue;
1682             }
1683             OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
1684
1685             dataBuf += ret;
1686             written += ret;
1687         } while (dataLen > written);
1688
1689     }
1690     else
1691     {
1692         SslCacheMessage_t * msg = NewCacheMessage((uint8_t*) data, dataLen);
1693         if (NULL == msg || !u_arraylist_add(tep->cacheList, (void *) msg))
1694         {
1695             OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1696             oc_mutex_unlock(g_sslContextMutex);
1697             return CA_STATUS_FAILED;
1698         }
1699     }
1700
1701     oc_mutex_unlock(g_sslContextMutex);
1702
1703     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1704     return CA_STATUS_OK;
1705 }
1706 /**
1707  * Sends cached messages via TLS connection.
1708  *
1709  * @param[in]  tep    remote address with session info
1710  */
1711 static void SendCacheMessages(SslEndPoint_t * tep)
1712 {
1713     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1714     VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "Param tep is NULL");
1715
1716     uint32_t listIndex = 0;
1717     uint32_t listLength = 0;
1718     listLength = u_arraylist_length(tep->cacheList);
1719     for (listIndex = 0; listIndex < listLength;)
1720     {
1721         int ret = 0;
1722         SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(tep->cacheList, listIndex);
1723         if (NULL != msg && NULL != msg->data && 0 != msg->len)
1724         {
1725             unsigned char *dataBuf = (unsigned char *)msg->data;
1726             size_t written = 0;
1727
1728             do
1729             {
1730                 ret = mbedtls_ssl_write(&tep->ssl, dataBuf, msg->len - written);
1731                 if (ret < 0)
1732                 {
1733                     if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
1734                     {
1735                         OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned -0x%x", -ret);
1736                         break;
1737                     }
1738                     continue;
1739                 }
1740                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
1741
1742                 dataBuf += ret;
1743                 written += ret;
1744             } while (msg->len > written);
1745
1746             if (u_arraylist_remove(tep->cacheList, listIndex))
1747             {
1748                 DeleteCacheMessage(msg);
1749                 // Reduce list length by 1 as we removed one element.
1750                 listLength--;
1751             }
1752             else
1753             {
1754                 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_remove failed.");
1755                 break;
1756             }
1757         }
1758         else
1759         {
1760             // Move to the next element
1761             ++listIndex;
1762         }
1763     }
1764     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1765 }
1766
1767 void CAsetSslHandshakeCallback(CAErrorCallback tlsHandshakeCallback)
1768 {
1769     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1770     g_sslCallback = tlsHandshakeCallback;
1771     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1772 }
1773
1774 /* Read data from TLS connection
1775  */
1776 CAResult_t CAdecryptSsl(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t dataLen)
1777 {
1778     int ret = 0;
1779     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1780     VERIFY_NON_NULL_RET(sep, NET_SSL_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
1781     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , CA_STATUS_INVALID_PARAM);
1782
1783     oc_mutex_lock(g_sslContextMutex);
1784     if (NULL == g_caSslContext)
1785     {
1786         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1787         oc_mutex_unlock(g_sslContextMutex);
1788         return CA_STATUS_FAILED;
1789     }
1790
1791
1792     SslEndPoint_t * peer = GetSslPeer(&sep->endpoint);
1793     if (NULL == peer)
1794     {
1795         mbedtls_ssl_config * config = (sep->endpoint.adapter == CA_ADAPTER_IP ||
1796                                    sep->endpoint.adapter == CA_ADAPTER_GATT_BTLE ?
1797                                    &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
1798         peer = NewSslEndPoint(&sep->endpoint, config);
1799         if (NULL == peer)
1800         {
1801             OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1802             oc_mutex_unlock(g_sslContextMutex);
1803             return CA_STATUS_FAILED;
1804         }
1805         //Load allowed TLS suites from SVR DB
1806         SetupCipher(config, sep->endpoint.adapter);
1807
1808         ret = u_arraylist_add(g_caSslContext->peerList, (void *) peer);
1809         if (!ret)
1810         {
1811             OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1812             OICFree(peer);
1813             oc_mutex_unlock(g_sslContextMutex);
1814             return CA_STATUS_FAILED;
1815         }
1816     }
1817
1818     peer->recBuf.buff = data;
1819     peer->recBuf.len = dataLen;
1820     peer->recBuf.loaded = 0;
1821
1822     while (MBEDTLS_SSL_HANDSHAKE_OVER != peer->ssl.state)
1823     {
1824         ret = mbedtls_ssl_handshake_step(&peer->ssl);
1825         if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
1826         {
1827             break;
1828         }
1829
1830         if (MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED == ret)
1831         {
1832             OIC_LOG(DEBUG, NET_SSL_TAG, "Hello verification requested");
1833             mbedtls_ssl_session_reset(&peer->ssl);
1834             mbedtls_ssl_set_client_transport_id(&peer->ssl,
1835                                                 (const unsigned char *) sep->endpoint.addr,
1836                                                  sizeof(sep->endpoint.addr));
1837             ret = mbedtls_ssl_handshake_step(&peer->ssl);
1838         }
1839         uint32_t flags = mbedtls_ssl_get_verify_result(&peer->ssl);
1840         if (0 != flags)
1841         {
1842             OIC_LOG_BUFFER(ERROR, NET_SSL_TAG, (const uint8_t *) &flags, sizeof(flags));
1843             SSL_CHECK_FAIL(peer, flags, "Cert verification failed", 1,
1844                                                      CA_STATUS_FAILED, GetAlertCode(flags));
1845         }
1846         SSL_CHECK_FAIL(peer, ret, "Handshake error", 1, CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1847         if (MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC == peer->ssl.state)
1848         {
1849             memcpy(peer->master, peer->ssl.session_negotiate->master, sizeof(peer->master));
1850             g_caSslContext->selectedCipher = peer->ssl.session_negotiate->ciphersuite;
1851         }
1852         if (MBEDTLS_SSL_CLIENT_KEY_EXCHANGE == peer->ssl.state)
1853         {
1854             memcpy(peer->random, peer->ssl.handshake->randbytes, sizeof(peer->random));
1855         }
1856
1857         if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
1858         {
1859             SSL_RES(peer, CA_STATUS_OK);
1860             if (MBEDTLS_SSL_IS_CLIENT == peer->ssl.conf->endpoint)
1861             {
1862                 SendCacheMessages(peer);
1863             }
1864
1865             int selectedCipher = peer->ssl.session->ciphersuite;
1866             OIC_LOG_V(DEBUG, NET_SSL_TAG, "(D)TLS Session is connected via ciphersuite [0x%x]", selectedCipher);
1867             if (MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 != selectedCipher &&
1868                 MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 != selectedCipher)
1869             {
1870                 char uuid[UUID_LENGTH * 2 + 5] = {0};
1871                 void * uuidPos = NULL;
1872                 void * userIdPos = NULL;
1873                 const mbedtls_x509_crt * peerCert = mbedtls_ssl_get_peer_cert(&peer->ssl);
1874                 ret = (NULL == peerCert ? -1 : 0);
1875                 SSL_CHECK_FAIL(peer, ret, "Failed to retrieve cert", 1,
1876                                             CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_NO_CERT);
1877                 uuidPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
1878                                                  UUID_PREFIX, sizeof(UUID_PREFIX) - 1);
1879
1880                 if (NULL != uuidPos)
1881                 {
1882                     memcpy(uuid, (char*) uuidPos + sizeof(UUID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
1883                     OIC_LOG_V(DEBUG, NET_SSL_TAG, "certificate uuid string: %s" , uuid);
1884                     ret = (OCConvertStringToUuid(uuid, peer->sep.identity.id)) ? 0 : -1;
1885                     SSL_CHECK_FAIL(peer, ret, "Failed to convert subject", 1,
1886                                           CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
1887                 }
1888                 else
1889                 {
1890                     OIC_LOG(WARNING, NET_SSL_TAG, "uuid not found");
1891                 }
1892
1893                 userIdPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
1894                                              USERID_PREFIX, sizeof(USERID_PREFIX) - 1);
1895                 if (NULL != userIdPos)
1896                 {
1897                     memcpy(uuid, (char*) userIdPos + sizeof(USERID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
1898                     ret = (OCConvertStringToUuid(uuid, peer->sep.userId.id)) ? 0 : -1;
1899                     SSL_CHECK_FAIL(peer, ret, "Failed to convert subject alt name", 1,
1900                                       CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
1901                 }
1902                 else
1903                 {
1904                     OIC_LOG(WARNING, NET_SSL_TAG, "Subject alternative name not found");
1905                 }
1906             }
1907
1908             oc_mutex_unlock(g_sslContextMutex);
1909             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1910             return CA_STATUS_OK;
1911         }
1912     }
1913
1914     if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
1915     {
1916         uint8_t decryptBuffer[TLS_MSG_BUF_LEN] = {0};
1917         do
1918         {
1919             ret = mbedtls_ssl_read(&peer->ssl, decryptBuffer, TLS_MSG_BUF_LEN);
1920         } while (MBEDTLS_ERR_SSL_WANT_READ == ret);
1921
1922         if (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY == ret ||
1923             // TinyDTLS sends fatal close_notify alert
1924             (MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE == ret &&
1925              MBEDTLS_SSL_ALERT_LEVEL_FATAL == peer->ssl.in_msg[0] &&
1926              MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY == peer->ssl.in_msg[1]))
1927         {
1928             OIC_LOG(INFO, NET_SSL_TAG, "Connection was closed gracefully");
1929             RemovePeerFromList(&peer->sep.endpoint);
1930             oc_mutex_unlock(g_sslContextMutex);
1931             return CA_STATUS_OK;
1932         }
1933
1934         if (0 > ret)
1935         {
1936             OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_ssl_read returned -0x%x", -ret);
1937             //SSL_RES(peer, CA_STATUS_FAILED);
1938             RemovePeerFromList(&peer->sep.endpoint);
1939             oc_mutex_unlock(g_sslContextMutex);
1940             return CA_STATUS_FAILED;
1941         }
1942         else if (0 < ret)
1943         {
1944             int adapterIndex = GetAdapterIndex(peer->sep.endpoint.adapter);
1945             if (0 <= adapterIndex && MAX_SUPPORTED_ADAPTERS > adapterIndex)
1946             {
1947                 g_caSslContext->adapterCallbacks[adapterIndex].recvCallback(&peer->sep, decryptBuffer, ret);
1948             }
1949             else
1950             {
1951                 OIC_LOG(ERROR, NET_SSL_TAG, "Unsuported adapter");
1952                 RemovePeerFromList(&peer->sep.endpoint);
1953                 oc_mutex_unlock(g_sslContextMutex);
1954                 return CA_STATUS_FAILED;
1955             }
1956         }
1957     }
1958
1959     oc_mutex_unlock(g_sslContextMutex);
1960     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1961     return CA_STATUS_OK;
1962 }
1963
1964 void CAsetSslAdapterCallbacks(CAPacketReceivedCallback recvCallback,
1965                               CAPacketSendCallback sendCallback,
1966                               CATransportAdapter_t type)
1967 {
1968     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1969     VERIFY_NON_NULL_VOID(sendCallback, NET_SSL_TAG, "sendCallback is NULL");
1970     VERIFY_NON_NULL_VOID(recvCallback, NET_SSL_TAG, "recvCallback is NULL");
1971     oc_mutex_lock(g_sslContextMutex);
1972     if (NULL == g_caSslContext)
1973     {
1974         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1975         oc_mutex_unlock(g_sslContextMutex);
1976         return;
1977     }
1978
1979     switch (type)
1980     {
1981         case CA_ADAPTER_IP:
1982             g_caSslContext->adapterCallbacks[0].recvCallback = recvCallback;
1983             g_caSslContext->adapterCallbacks[0].sendCallback = sendCallback;
1984             break;
1985         case CA_ADAPTER_TCP:
1986             g_caSslContext->adapterCallbacks[1].recvCallback = recvCallback;
1987             g_caSslContext->adapterCallbacks[1].sendCallback = sendCallback;
1988             break;
1989         case CA_ADAPTER_GATT_BTLE:
1990             g_caSslContext->adapterCallbacks[2].recvCallback = recvCallback;
1991             g_caSslContext->adapterCallbacks[2].sendCallback = sendCallback;
1992             break;
1993         default:
1994             OIC_LOG_V(ERROR, NET_SSL_TAG, "Unsupported adapter: %d", type);
1995     }
1996
1997     oc_mutex_unlock(g_sslContextMutex);
1998     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1999 }
2000 /**
2001  * Gets index of the TLS ciphersuite in the SslCipher_t enum.
2002  *
2003  * @param[in]  cipher    TLS chiphersuite code
2004  *
2005  * @return   corresponding enum
2006  */
2007
2008 static SslCipher_t GetCipherIndex(const uint32_t cipher)
2009 {
2010     switch(cipher)
2011     {
2012         case MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256:
2013         {
2014             return SSL_RSA_WITH_AES_256_CBC_SHA256;
2015         }
2016         case MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256:
2017         {
2018             return SSL_RSA_WITH_AES_128_GCM_SHA256;
2019         }
2020         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
2021         {
2022             return SSL_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
2023         }
2024         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2025         {
2026             return SSL_ECDHE_ECDSA_WITH_AES_128_CCM_8;
2027         }
2028         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
2029         {
2030             return SSL_ECDHE_ECDSA_WITH_AES_128_CCM;
2031         }
2032         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2033         {
2034             return SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256;
2035         }
2036         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
2037         {
2038             return SSL_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384;
2039         }
2040         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
2041         {
2042             return SSL_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384;
2043         }
2044         case MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
2045         {
2046             return SSL_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
2047         }
2048         case MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
2049         {
2050             return SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256;
2051         }
2052         case MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256:
2053         {
2054             return SSL_ECDH_ANON_WITH_AES_128_CBC_SHA256;
2055         }
2056         default:
2057         {
2058             return SSL_CIPHER_MAX;
2059         }
2060     }
2061 }
2062
2063 CAResult_t CAsetTlsCipherSuite(const uint32_t cipher)
2064 {
2065     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2066     CAResult_t res = CA_STATUS_FAILED;
2067     SslCipher_t index = GetCipherIndex(cipher);
2068     if (SSL_CIPHER_MAX == index)
2069     {
2070         OIC_LOG(WARNING, NET_SSL_TAG, "Unknown cipher");
2071     }
2072     else
2073     {
2074 #ifdef __WITH_TLS__
2075         CONF_SSL(&g_caSslContext->clientTlsConf, &g_caSslContext->serverTlsConf,
2076         mbedtls_ssl_conf_ciphersuites, tlsCipher[index]);
2077 #endif
2078 #ifdef __WITH_DTLS__
2079         CONF_SSL(&g_caSslContext->clientDtlsConf, &g_caSslContext->serverDtlsConf,
2080         mbedtls_ssl_conf_ciphersuites, tlsCipher[index]);
2081 #endif
2082         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Selected cipher: 0x%x", cipher);
2083     }
2084     g_caSslContext->cipher = index;
2085
2086     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2087     return CA_STATUS_OK;
2088 }
2089
2090 CAResult_t CAinitiateSslHandshake(const CAEndpoint_t *endpoint)
2091 {
2092     CAResult_t res = CA_STATUS_OK;
2093     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2094     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
2095     oc_mutex_lock(g_sslContextMutex);
2096     if (NULL == InitiateTlsHandshake(endpoint))
2097     {
2098         OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
2099         res = CA_STATUS_FAILED;
2100     }
2101     oc_mutex_unlock(g_sslContextMutex);
2102     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2103     return res;
2104 }
2105 /**
2106  * Expands the secret into blocks of data according
2107  * to the algorithm specified in section 5 of RFC 4346
2108  *
2109  * This function writes upto @p bufLen bytes into the given output buffer @p buf
2110  *
2111  * @param  key    secret key.
2112  * @param  keyLen    secret key length.
2113  * @param  label    A PRF label.
2114  * @param  labelLen     Actual length of @p label.
2115  * @param  random1    Random seed.
2116  * @param  random1Len     Actual length of @p random1 (may be zero).
2117  * @param  random2     Random seed.
2118  * @param  random2Len    Actual length of @p random2 (may be zero).
2119  * @param  buf    Output buffer for generated random data.
2120  * @param  bufLen    Maximum size of @p buf.
2121  *
2122  * @return The actual number of bytes written to @p buf or @c -1 on error.
2123  */
2124
2125 static int pHash (const unsigned char *key, size_t keyLen,
2126      const unsigned char *label, size_t labelLen,
2127      const unsigned char *random1, size_t random1Len,
2128      const unsigned char *random2, size_t random2Len,
2129      unsigned char *buf, size_t bufLen)
2130 {
2131     unsigned char A[RANDOM_LEN] = {0};
2132     unsigned char tmp[RANDOM_LEN] = {0};
2133     size_t dLen;   /* digest length */
2134     size_t len = 0;   /* result length */
2135
2136     VERIFY_NON_NULL_RET(key, NET_SSL_TAG, "key is NULL", -1);
2137     VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", -1);
2138     VERIFY_NON_NULL_RET(random1, NET_SSL_TAG, "random1 is NULL", -1);
2139     VERIFY_NON_NULL_RET(random2, NET_SSL_TAG, "random2 is NULL", -1);
2140     VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "buf is NULL", -1);
2141
2142     mbedtls_md_context_t hmacA;
2143     mbedtls_md_context_t hmacP;
2144
2145     mbedtls_md_init(&hmacA);
2146     mbedtls_md_init(&hmacP);
2147
2148     CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacA, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2149     CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacP, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2150
2151     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen );
2152     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, label, labelLen);
2153     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random1, random1Len);
2154     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random2, random2Len);
2155     CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2156
2157     dLen = RANDOM_LEN;
2158
2159     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2160
2161     while (len + dLen < bufLen)
2162     {
2163         CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2164         CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2165         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2166         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2167         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2168         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2169
2170         CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2171
2172         len += RANDOM_LEN;
2173
2174         memcpy(buf, tmp, dLen);
2175         buf += dLen;
2176
2177         CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacA);
2178         CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen);
2179         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, A, dLen);
2180         CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2181     }
2182
2183     CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2184     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2185     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2186
2187     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2188     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2189     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2190     CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2191
2192     memcpy(buf, tmp, bufLen - len);
2193
2194     mbedtls_md_free(&hmacA);
2195     mbedtls_md_free(&hmacP);
2196     return bufLen;
2197     // exit label required for CHECK_MBEDTLS_RET macro
2198 exit:
2199     mbedtls_md_free(&hmacA);
2200     mbedtls_md_free(&hmacP);
2201     return -1;
2202 }
2203
2204 CAResult_t CAsslGenerateOwnerPsk(const CAEndpoint_t *endpoint,
2205                             const uint8_t* label, const size_t labelLen,
2206                             const uint8_t* rsrcServerDeviceId, const size_t rsrcServerDeviceIdLen,
2207                             const uint8_t* provServerDeviceId, const size_t provServerDeviceIdLen,
2208                             uint8_t* ownerPsk, const size_t ownerPskSize)
2209 {
2210     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2211     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint is NULL", CA_STATUS_INVALID_PARAM);
2212     VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", CA_STATUS_INVALID_PARAM);
2213     VERIFY_NON_NULL_RET(rsrcServerDeviceId, NET_SSL_TAG, "rsrcId is NULL", CA_STATUS_INVALID_PARAM);
2214     VERIFY_NON_NULL_RET(provServerDeviceId, NET_SSL_TAG, "provId is NULL", CA_STATUS_INVALID_PARAM);
2215     VERIFY_NON_NULL_RET(ownerPsk, NET_SSL_TAG, "ownerPSK is NULL", CA_STATUS_INVALID_PARAM);
2216
2217     // TODO: Added as workaround, need to debug
2218     oc_mutex_unlock(g_sslContextMutex);
2219
2220     oc_mutex_lock(g_sslContextMutex);
2221     if (NULL == g_caSslContext)
2222     {
2223         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2224         oc_mutex_unlock(g_sslContextMutex);
2225         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2226         return CA_STATUS_FAILED;
2227     }
2228     SslEndPoint_t * tep = GetSslPeer(endpoint);
2229     if (NULL == tep)
2230     {
2231         OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
2232         oc_mutex_unlock(g_sslContextMutex);
2233         return CA_STATUS_FAILED;
2234     }
2235
2236     // keyBlockLen set up according to OIC 1.1 Security Specification Section 7.3.2
2237     int macKeyLen = 0;
2238     int ivSize = 0;
2239     int keySize = 0;
2240     int keyBlockLen = 0;
2241     if (MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2242         MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2243         MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2244         MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher)
2245     {
2246         // 2 * ( 32 + 0 + 16 ) = 96
2247         macKeyLen = SHA256_MAC_KEY_LENGTH;
2248         ivSize = CBC_IV_LENGTH;
2249         keySize = AES128_KEY_LENGTH;
2250     }
2251     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM == g_caSslContext->selectedCipher ||
2252              MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caSslContext->selectedCipher)
2253     {
2254         // 2 * ( 0 + 4 + 16 ) = 40
2255         macKeyLen = CCM_MAC_KEY_LENGTH;
2256         ivSize = CCM_IV_LENGTH;
2257         keySize = AES128_KEY_LENGTH;
2258     }
2259     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 == g_caSslContext->selectedCipher)
2260     {
2261         // 2 * ( 32 + 12 + 16 ) = 120
2262         macKeyLen = SHA256_MAC_KEY_LENGTH;
2263         ivSize = GCM_IV_LENGTH;
2264         keySize = AES128_KEY_LENGTH;
2265     }
2266     else if (MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 == g_caSslContext->selectedCipher)
2267     {
2268         // 2 * ( 32 + 0 + 32 ) = 128
2269         macKeyLen = SHA256_MAC_KEY_LENGTH;
2270         ivSize = CBC_IV_LENGTH;
2271         keySize = AES256_KEY_LENGTH;
2272     }
2273     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 == g_caSslContext->selectedCipher)
2274     {
2275         // 2 * ( 48 + 0 + 32 ) = 160
2276         macKeyLen = SHA384_MAC_KEY_LENGTH;
2277         ivSize = CBC_IV_LENGTH;
2278         keySize = AES256_KEY_LENGTH;
2279     }
2280     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 == g_caSslContext->selectedCipher)
2281     {
2282         // 2 * ( 48 + 12 + 32 ) = 184
2283         macKeyLen = SHA384_MAC_KEY_LENGTH;
2284         ivSize = GCM_IV_LENGTH;
2285         keySize = AES256_KEY_LENGTH;
2286     }
2287     else if (MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 == g_caSslContext->selectedCipher)
2288     {
2289         // 2 * ( 48 + 12 + 32 ) = 184
2290         macKeyLen = SHA256_MAC_KEY_LENGTH;
2291         ivSize = GCM_IV_LENGTH;
2292         keySize = AES128_KEY_LENGTH;
2293     }
2294     keyBlockLen = 2 * (macKeyLen + keySize + ivSize);
2295
2296     uint8_t * keyblock = (uint8_t *)OICMalloc(keyBlockLen);
2297     if (NULL == keyblock)
2298     {
2299         OIC_LOG(ERROR, NET_SSL_TAG, "Failed to OICMalloc for keyblock");
2300         oc_mutex_unlock(g_sslContextMutex);
2301         return CA_STATUS_FAILED;
2302     }
2303
2304     // "key expansion"
2305     uint8_t lab[] = {0x6b, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70, 0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e};
2306     int ret = pHash(tep->master, sizeof(tep->master), lab, sizeof(lab),
2307                     (tep->random) + RANDOM_LEN, RANDOM_LEN, tep->random, RANDOM_LEN,
2308                     keyblock, keyBlockLen);
2309     if (-1 == ret)
2310     {
2311         OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
2312         OICFree(keyblock);
2313         oc_mutex_unlock(g_sslContextMutex);
2314         return CA_STATUS_FAILED;
2315     }
2316
2317     ret = pHash(keyblock, keyBlockLen, label, labelLen,
2318                 rsrcServerDeviceId, rsrcServerDeviceIdLen,
2319                 provServerDeviceId, provServerDeviceIdLen,
2320                 ownerPsk, ownerPskSize);
2321     if (-1 == ret)
2322     {
2323         OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
2324         OICFree(keyblock);
2325         oc_mutex_unlock(g_sslContextMutex);
2326         return CA_STATUS_FAILED;
2327     }
2328
2329     OICFree(keyblock);
2330     oc_mutex_unlock(g_sslContextMutex);
2331
2332     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2333     return CA_STATUS_OK;
2334 }