Add PKIX resources
[platform/upstream/iotivity.git] / resource / csdk / security / src / doxmresource.c
1 //******************************************************************
2 //
3 // Copyright 2015 Intel Mobile Communications GmbH 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 #include "ocstack.h"
22 #include "logger.h"
23 #include "oic_malloc.h"
24 #include "cJSON.h"
25 #include "resourcemanager.h"
26 #include "doxmresource.h"
27 #include "psinterface.h"
28 #include "utlist.h"
29 #include "srmresourcestrings.h"
30 #include "securevirtualresourcetypes.h"
31 #include "base64.h"
32 #include "ocrandom.h"
33 #include "cainterface.h"
34 #include "credresource.h"
35 #include "ocserverrequest.h"
36 #include "srmutility.h"
37 #include "pinoxmcommon.h"
38
39 #ifdef __WITH_DTLS__
40 #include "global.h"
41 #endif
42
43 #include <stdlib.h>
44 #include <string.h>
45
46 #if HAVE_STRINGS_H
47 #include <strings.h>
48 #endif
49
50 #define TAG  PCF("SRM-DOXM")
51
52 static OicSecDoxm_t        *gDoxm = NULL;
53 static OCResourceHandle    gDoxmHandle = NULL;
54
55 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
56 static OicSecDoxm_t gDefaultDoxm =
57 {
58     NULL,                   /* OicUrn_t *oxmType */
59     0,                      /* size_t oxmTypeLen */
60     &gOicSecDoxmJustWorks,  /* uint16_t *oxm */
61     1,                      /* size_t oxmLen */
62     OIC_JUST_WORKS,         /* uint16_t oxmSel */
63     false,                  /* bool owned */
64     {.id = {0}},            /* OicUuid_t deviceID */
65     {.id = {0}},            /* OicUuid_t owner */
66 };
67
68 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
69 {
70     if (doxm)
71     {
72         //Clean oxmType
73         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
74         {
75             OICFree(doxm->oxmType[i]);
76         }
77         OICFree(doxm->oxmType);
78
79         //clean oxm
80         OICFree(doxm->oxm);
81
82         //Clean doxm itself
83         OICFree(doxm);
84     }
85 }
86
87 char * BinToDoxmJSON(const OicSecDoxm_t * doxm)
88 {
89     if (NULL == doxm)
90     {
91         return NULL;
92     }
93
94     char *jsonStr = NULL;
95     cJSON *jsonDoxm = NULL;
96     char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
97     uint32_t outLen = 0;
98     B64Result b64Ret = B64_OK;
99
100     cJSON *jsonRoot = cJSON_CreateObject();
101     VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
102
103     jsonDoxm = cJSON_CreateObject();
104     VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
105     cJSON_AddItemToObject(jsonRoot, OIC_JSON_DOXM_NAME, jsonDoxm );
106
107     //OxmType -- Not Mandatory
108     if(doxm->oxmTypeLen > 0)
109     {
110         cJSON *jsonOxmTyArray = cJSON_CreateArray();
111         VERIFY_NON_NULL(TAG, jsonOxmTyArray, ERROR);
112         cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_TYPE_NAME, jsonOxmTyArray );
113         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
114         {
115             cJSON_AddItemToArray (jsonOxmTyArray, cJSON_CreateString(doxm->oxmType[i]));
116         }
117     }
118
119     //Oxm -- Not Mandatory
120     if(doxm->oxmLen > 0)
121     {
122         cJSON *jsonOxmArray = cJSON_CreateArray();
123         VERIFY_NON_NULL(TAG, jsonOxmArray, ERROR);
124         cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_NAME,jsonOxmArray );
125         for (size_t i = 0; i < doxm->oxmLen; i++)
126         {
127             cJSON_AddItemToArray (jsonOxmArray, cJSON_CreateNumber(doxm->oxm[i]));
128         }
129     }
130
131     //OxmSel -- Mandatory
132     cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_OXM_SEL_NAME, (int)doxm->oxmSel);
133
134     //Owned -- Mandatory
135     cJSON_AddBoolToObject(jsonDoxm, OIC_JSON_OWNED_NAME, doxm->owned);
136
137     //TODO: Need more clarification on deviceIDFormat field type.
138 #if 0
139     //DeviceIdFormat -- Mandatory
140     cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_DEVICE_ID_FORMAT_NAME, doxm->deviceIDFormat);
141 #endif
142
143     //DeviceId -- Mandatory
144     outLen = 0;
145     b64Ret = b64Encode(doxm->deviceID.id, sizeof(doxm->deviceID.id), base64Buff,
146                     sizeof(base64Buff), &outLen);
147     VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
148     cJSON_AddStringToObject(jsonDoxm, OIC_JSON_DEVICE_ID_NAME, base64Buff);
149
150     //Owner -- Mandatory
151     outLen = 0;
152     b64Ret = b64Encode(doxm->owner.id, sizeof(doxm->owner.id), base64Buff,
153                     sizeof(base64Buff), &outLen);
154     VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
155     cJSON_AddStringToObject(jsonDoxm, OIC_JSON_OWNER_NAME, base64Buff);
156
157     jsonStr = cJSON_PrintUnformatted(jsonRoot);
158
159 exit:
160     if (jsonRoot)
161     {
162         cJSON_Delete(jsonRoot);
163     }
164     return jsonStr;
165 }
166
167 OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
168 {
169
170     if (NULL == jsonStr)
171     {
172         return NULL;
173     }
174
175     OCStackResult ret = OC_STACK_ERROR;
176     OicSecDoxm_t *doxm =  NULL;
177     cJSON *jsonDoxm = NULL;
178     cJSON *jsonObj = NULL;
179
180     size_t jsonObjLen = 0;
181     unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
182     uint32_t outLen = 0;
183     B64Result b64Ret = B64_OK;
184
185     cJSON *jsonRoot = cJSON_Parse(jsonStr);
186     VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
187
188     jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
189     VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
190
191     doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
192     VERIFY_NON_NULL(TAG, doxm, ERROR);
193
194     //OxmType -- not Mandatory
195     jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME);
196     if ((jsonObj) && (cJSON_Array == jsonObj->type))
197     {
198         doxm->oxmTypeLen = cJSON_GetArraySize(jsonObj);
199         VERIFY_SUCCESS(TAG, doxm->oxmTypeLen > 0, ERROR);
200
201         doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *));
202         VERIFY_NON_NULL(TAG, (doxm->oxmType), ERROR);
203
204         for (size_t i  = 0; i < doxm->oxmTypeLen ; i++)
205         {
206             cJSON *jsonOxmTy = cJSON_GetArrayItem(jsonObj, i);
207             VERIFY_NON_NULL(TAG, jsonOxmTy, ERROR);
208
209             jsonObjLen = strlen(jsonOxmTy->valuestring) + 1;
210             doxm->oxmType[i] = (char*)OICMalloc(jsonObjLen);
211             VERIFY_NON_NULL(TAG, doxm->oxmType[i], ERROR);
212             strncpy((char *)doxm->oxmType[i], (char *)jsonOxmTy->valuestring, jsonObjLen);
213         }
214     }
215
216     //Oxm -- not Mandatory
217     jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_NAME);
218     if (jsonObj && cJSON_Array == jsonObj->type)
219     {
220         doxm->oxmLen = cJSON_GetArraySize(jsonObj);
221         VERIFY_SUCCESS(TAG, doxm->oxmLen > 0, ERROR);
222
223         doxm->oxm = (OicSecOxm_t*)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t));
224         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
225
226         for (size_t i  = 0; i < doxm->oxmLen ; i++)
227         {
228             cJSON *jsonOxm = cJSON_GetArrayItem(jsonObj, i);
229             VERIFY_NON_NULL(TAG, jsonOxm, ERROR);
230             doxm->oxm[i] = (OicSecOxm_t)jsonOxm->valueint;
231         }
232     }
233
234     //OxmSel -- Mandatory
235     jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_SEL_NAME);
236     if(jsonObj)
237     {
238         VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
239         doxm->oxmSel = (OicSecOxm_t)jsonObj->valueint;
240     }
241     else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
242     {
243         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
244         doxm->oxmSel = gDoxm->oxmSel;
245     }
246
247     //Owned -- Mandatory
248     jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNED_NAME);
249     if(jsonObj)
250     {
251         VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR);
252         doxm->owned = jsonObj->valueint;
253     }
254     else // PUT/POST JSON may not have owned so set it to the gDomx->owned
255     {
256         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
257         doxm->owned = gDoxm->owned;
258     }
259
260     //DeviceId -- Mandatory
261     jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVICE_ID_NAME);
262     if(jsonObj)
263     {
264         VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
265         if(cJSON_String == jsonObj->type)
266         {
267             //Check for empty string, in case DeviceId field has not been set yet
268             if (jsonObj->valuestring[0])
269             {
270                 outLen = 0;
271                 b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
272                         sizeof(base64Buff), &outLen);
273                 VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(doxm->deviceID.id)),
274                                 ERROR);
275                 memcpy(doxm->deviceID.id, base64Buff, outLen);
276             }
277         }
278     }
279     else // PUT/POST JSON will not have deviceID so set it to the gDoxm->deviceID.id
280     {
281         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
282         memcpy((char *)doxm->deviceID.id, (char *)gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
283     }
284
285     //Owner -- will be empty when device status is unowned.
286     jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNER_NAME);
287     if(true == doxm->owned)
288     {
289         VERIFY_NON_NULL(TAG, jsonObj, ERROR);
290     }
291     if(jsonObj)
292     {
293         VERIFY_SUCCESS(TAG, (cJSON_String == jsonObj->type), ERROR);
294         outLen = 0;
295         b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
296                 sizeof(base64Buff), &outLen);
297         VERIFY_SUCCESS(TAG, ((b64Ret == B64_OK) && (outLen <= sizeof(doxm->owner.id))), ERROR);
298         memcpy(doxm->owner.id, base64Buff, outLen);
299     }
300
301     ret = OC_STACK_OK;
302
303 exit:
304     cJSON_Delete(jsonRoot);
305     if (OC_STACK_OK != ret)
306     {
307         DeleteDoxmBinData(doxm);
308         doxm = NULL;
309     }
310
311     return doxm;
312 }
313
314 /**
315  * @todo document this function including why code might need to call this.
316  * The current suspicion is that it's not being called as much as it should.
317  */
318 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
319 {
320     bool bRet = false;
321
322     if (NULL != doxm)
323     {
324         // Convert Doxm data into JSON for update to persistent storage
325         char *jsonStr = BinToDoxmJSON(doxm);
326         if (jsonStr)
327         {
328             cJSON *jsonDoxm = cJSON_Parse(jsonStr);
329             OICFree(jsonStr);
330
331             if (jsonDoxm &&
332                     (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_DOXM_NAME, jsonDoxm)))
333             {
334                 bRet = true;
335             }
336             cJSON_Delete(jsonDoxm);
337         }
338     }
339
340     return bRet;
341 }
342
343 static bool ValidateQuery(unsigned char * query)
344 {
345     // Send doxm resource data if the state of doxm resource
346     // matches with the query parameters.
347     // else send doxm resource data as NULL
348     // TODO Remove this check and rely on Policy Engine
349     // and Provisioning Mode to enforce provisioning-state
350     // access rules. Eventually, the PE and PM code will
351     // not send a request to the /doxm Entity Handler at all
352     // if it should not respond.
353     OC_LOG (INFO, TAG, PCF("In ValidateQuery"));
354     if(NULL == gDoxm)
355     {
356         return false;
357     }
358
359     OicParseQueryIter_t parseIter = {.attrPos = NULL};
360
361     ParseQueryIterInit(query, &parseIter);
362
363     while(GetNextQuery(&parseIter))
364     {
365         if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
366         {
367             if((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
368                     (gDoxm->owned))
369             {
370                 return true;
371             }
372             else if((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
373                     && (!gDoxm->owned))
374             {
375                 return true;
376             }
377         }
378     }
379     return false;
380 }
381
382 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
383 {
384     char* jsonStr = NULL;
385     OCEntityHandlerResult ehRet = OC_EH_OK;
386
387     OC_LOG (INFO, TAG, PCF("Doxm EntityHandle processing GET request"));
388
389     //Checking if Get request is a query.
390     if(ehRequest->query)
391     {
392         OC_LOG (INFO, TAG, PCF("HandleDoxmGetRequest processing query"));
393         if(!ValidateQuery((unsigned char *)ehRequest->query))
394         {
395             ehRet = OC_EH_ERROR;
396         }
397     }
398
399     /*
400      * For GET or Valid Query request return doxm resource json payload.
401      * For non-valid query return NULL json payload.
402      * A device will 'always' have a default Doxm, so BinToDoxmJSON will
403      * return valid doxm resource json.
404      */
405
406     jsonStr = (ehRet == OC_EH_OK) ? BinToDoxmJSON(gDoxm) : NULL;
407
408     // Send response payload to request originator
409     if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, jsonStr))
410     {
411         OC_LOG (ERROR, TAG, PCF("SendSRMResponse failed in HandleDoxmGetRequest"));
412     }
413
414     OICFree(jsonStr);
415
416     return ehRet;
417 }
418
419 #ifdef __WITH_DTLS__
420 /*
421  * Generating new credential for provisioning tool
422  *
423  * PSK generated by
424  */
425 static OCEntityHandlerResult AddOwnerPSK(const CAEndpoint_t* endpoint,
426                     OicSecDoxm_t* ptDoxm,
427                     const uint8_t* label, const size_t labelLen)
428 {
429     size_t ownLen = 1;
430     uint32_t outLen = 0;
431     OicSecCred_t *cred = NULL;
432     uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {};
433
434     CAResult_t pskRet = CAGenerateOwnerPSK(endpoint,
435         label, labelLen,
436         ptDoxm->owner.id, sizeof(ptDoxm->owner.id),
437         gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
438         ownerPSK, OWNER_PSK_LENGTH_128);
439
440     VERIFY_SUCCESS(TAG, pskRet == CA_STATUS_OK, ERROR);
441
442     char base64Buff[B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128) + 1] = {};
443     B64Result b64Ret = b64Encode(ownerPSK, OWNER_PSK_LENGTH_128, base64Buff,
444                     sizeof(base64Buff), &outLen);
445     VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
446
447     OC_LOG (INFO, TAG, PCF("Doxm EntityHandle  generating Credential"));
448     cred = GenerateCredential(&ptDoxm->owner, SYMMETRIC_PAIR_WISE_KEY,
449                               NULL, base64Buff, ownLen, &ptDoxm->owner);
450     VERIFY_NON_NULL(TAG, cred, ERROR);
451
452     //Adding provisioning tool credential to cred Resource.
453     VERIFY_SUCCESS(TAG, OC_STACK_OK == AddCredential(cred), ERROR);
454
455     gDoxm->owned = true;
456     gDoxm->oxmSel = ptDoxm->oxmSel;
457     memcpy(&(gDoxm->owner), &(ptDoxm->owner), sizeof(OicUuid_t));
458
459     return OC_EH_OK;
460
461 exit:
462     return OC_EH_ERROR;
463 }
464 #endif //__WITH_DTLS__
465
466 static OCEntityHandlerResult HandleDoxmPutRequest (const OCEntityHandlerRequest * ehRequest)
467 {
468     OC_LOG (INFO, TAG, PCF("Doxm EntityHandle  processing PUT request"));
469     OCEntityHandlerResult ehRet = OC_EH_ERROR;
470     OicUuid_t emptyOwner = {.id = {0}};
471
472     /*
473      * Convert JSON Doxm data into binary. This will also validate
474      * the Doxm data received.
475      */
476     OicSecDoxm_t* newDoxm = JSONToDoxmBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
477
478     if (newDoxm)
479     {
480         // Iotivity SRM ONLY supports OIC_JUST_WORKS now
481         if (OIC_JUST_WORKS == newDoxm->oxmSel)
482         {
483             /*
484              * If current state of the device is un-owned, enable
485              * anonymous ECDH cipher in tinyDTLS so that Provisioning
486              * tool can initiate JUST_WORKS ownership transfer process.
487              */
488             if ((false == gDoxm->owned) && (false == newDoxm->owned))
489             {
490                 OC_LOG (INFO, TAG, PCF("Doxm EntityHandle  enabling AnonECDHCipherSuite"));
491 #ifdef __WITH_DTLS__
492                 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
493 #endif //__WITH_DTLS__
494                 goto exit;
495             }
496
497             /*
498              * When current state of the device is un-owned and Provisioning
499              * Tool is attempting to change the state to 'Owned' with a
500              * qualified value for the field 'Owner'
501              */
502             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
503                 (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0))
504             {
505                 /*
506                  * Generate OwnerPSK and create credential for Provisioning
507                  * tool with the generated OwnerPSK.
508                  * Update persistent storage and disable anonymous ECDH cipher
509                  *
510                  */
511 #ifdef __WITH_DTLS__
512                 OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
513
514                 //Generating OwnerPSK
515                 OC_LOG (INFO, TAG, PCF("Doxm EntityHandle  generating OwnerPSK"));
516
517                 //Generate new credential for provisioning tool
518                 ehRet = AddOwnerPSK((CAEndpoint_t *)&request->devAddr, newDoxm,
519                         (uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS));
520
521                 VERIFY_SUCCESS(TAG, ehRet == OC_EH_OK, ERROR);
522
523                 // Update new state in persistent storage
524                 if (true == UpdatePersistentStorage(gDoxm))
525                 {
526                     ehRet = OC_EH_OK;
527                 }
528                 else
529                 {
530                     ehRet = OC_EH_ERROR;
531
532                     /*
533                      * If persistent storage update failed, revert back the state
534                      * for global variable.
535                      */
536                     gDoxm->owned = false;
537                     gDoxm->oxmSel = 0;
538                     memset(&(gDoxm->owner), 0, sizeof(OicUuid_t));
539                 }
540
541                 /*
542                  * Disable anonymous ECDH cipher in tinyDTLS since device is now
543                  * in owned state.
544                  */
545                 CAEnableAnonECDHCipherSuite(false);
546 #ifdef __WITH_X509__
547 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE
548                 CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
549 #endif //__WITH_X509__
550 #endif //__WITH_DTLS__
551             }
552         }
553         else if(OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
554         {
555             //this temp Credential ID is used to track temporal Cred Id
556             static OicUuid_t tmpCredId = {.id={0}};
557             static bool tmpCredGenFlag = false;
558
559             if ((false == gDoxm->owned) && (false == newDoxm->owned))
560             {
561 #ifdef __WITH_DTLS__
562                 CAEnableAnonECDHCipherSuite(false);
563                 OC_LOG(DEBUG, TAG, "ECDH_ANON CipherSuite is DISABLED");
564                 CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
565
566                 char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
567                 if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
568                 {
569                     if(tmpCredGenFlag)
570                     {
571                        OC_LOG(DEBUG, TAG, "Corrupted PSK is detected!!!");
572                        VERIFY_SUCCESS(TAG,
573                                       OC_STACK_RESOURCE_DELETED == RemoveCredential(&tmpCredId),
574                                       ERROR);
575                     }
576
577                     OCStackResult res = AddTmpPskWithPIN( &(newDoxm->owner), SYMMETRIC_PAIR_WISE_KEY,
578                                      ranPin, OXM_RANDOM_PIN_SIZE, 1, &(newDoxm->owner), &tmpCredId);
579                     VERIFY_SUCCESS(TAG, res == OC_STACK_OK, ERROR);
580                     tmpCredGenFlag = true;
581                     ehRet = OC_EH_OK;
582                 }
583                 else
584                 {
585                     OC_LOG(ERROR, TAG, "Failed to generate random PIN");
586                     ehRet = OC_EH_ERROR;
587                 }
588
589 #endif //__WITH_DTLS__
590             }
591
592             /*
593              * When current state of the device is un-owned and Provisioning
594              * Tool is attempting to change the state to 'Owned' with a
595              * qualified value for the field 'Owner'
596              */
597             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
598                 (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0))
599             {
600 #ifdef __WITH_DTLS__
601                 OCServerRequest * request = (OCServerRequest *)ehRequest->requestHandle;
602
603                 //Remove Temporal Credential resource
604                 if(tmpCredGenFlag)
605                 {
606                     VERIFY_SUCCESS(TAG,
607                                    OC_STACK_RESOURCE_DELETED == RemoveCredential(&tmpCredId),
608                                    ERROR);
609                     tmpCredGenFlag = false;
610                 }
611
612                 //Generate new credential for provisioning tool
613                 ehRet = AddOwnerPSK((CAEndpoint_t*)(&request->devAddr), newDoxm,
614                                     (uint8_t*)OXM_RANDOM_DEVICE_PIN, strlen(OXM_RANDOM_DEVICE_PIN));
615                 VERIFY_SUCCESS(TAG, OC_EH_OK == ehRet, ERROR);
616
617                 //Update new state in persistent storage
618                 if((UpdatePersistentStorage(gDoxm) == true))
619                 {
620                     ehRet = OC_EH_OK;
621                 }
622                 else
623                 {
624                     /*
625                      * If persistent storage update failed, revert back the state
626                      * for global variable.
627                      */
628                     gDoxm->owned = false;
629                     gDoxm->oxmSel = 0;
630                     memset(&(gDoxm->owner), 0, sizeof(OicUuid_t));
631                     ehRet = OC_EH_ERROR;
632
633                 }
634 #endif
635              }
636         }
637     }
638
639 exit:
640
641     //Send payload to request originator
642     if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL))
643     {
644         OC_LOG (ERROR, TAG, PCF("SendSRMResponse failed in HandlePstatPostRequest"));
645     }
646     DeleteDoxmBinData(newDoxm);
647
648     return ehRet;
649 }
650
651 /*
652  * This internal method is the entity handler for DOXM resources.
653  */
654 OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
655                                         OCEntityHandlerRequest * ehRequest,
656                                         void* callbackParam)
657 {
658     (void)callbackParam;
659     OCEntityHandlerResult ehRet = OC_EH_ERROR;
660
661     if(NULL == ehRequest)
662     {
663         return ehRet;
664     }
665
666
667     if (flag & OC_REQUEST_FLAG)
668     {
669         OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
670         switch (ehRequest->method)
671         {
672             case OC_REST_GET:
673                 ehRet = HandleDoxmGetRequest(ehRequest);
674                 break;
675
676             case OC_REST_PUT:
677                 ehRet = HandleDoxmPutRequest(ehRequest);
678                 break;
679
680             default:
681                 ehRet = OC_EH_ERROR;
682                 SendSRMResponse(ehRequest, ehRet, NULL);
683                 break;
684         }
685     }
686
687     return ehRet;
688 }
689
690 /*
691  * This internal method is used to create '/oic/sec/doxm' resource.
692  */
693 OCStackResult CreateDoxmResource()
694 {
695     OCStackResult ret;
696
697     ret = OCCreateResource(&gDoxmHandle,
698                            OIC_RSRC_TYPE_SEC_DOXM,
699                            OIC_MI_DEF,
700                            OIC_RSRC_DOXM_URI,
701                            DoxmEntityHandler,
702                            NULL,
703                            OC_OBSERVABLE | OC_SECURE | OC_EXPLICIT_DISCOVERABLE);
704
705     if (OC_STACK_OK != ret)
706     {
707         OC_LOG (FATAL, TAG, PCF("Unable to instantiate Doxm resource"));
708         DeInitDoxmResource();
709     }
710     return ret;
711 }
712
713 /**
714  * Checks if DeviceID is generated during provisioning for the new device.
715  * If DeviceID is NULL then generates the new DeviceID.
716  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
717  *
718  */
719 static OCStackResult CheckDeviceID()
720 {
721     OCStackResult ret = OC_STACK_ERROR;
722     bool validId = false;
723     for (uint8_t i = 0; i < UUID_LENGTH; i++)
724     {
725         if (gDoxm->deviceID.id[i] != 0)
726         {
727             validId = true;
728             break;
729         }
730     }
731
732     if (!validId)
733     {
734         if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
735         {
736             OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
737             return ret;
738         }
739         ret = OC_STACK_OK;
740
741         if (UpdatePersistentStorage(gDoxm))
742         {
743             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
744             OC_LOG(FATAL, TAG, PCF("UpdatePersistentStorage failed!"));
745         }
746     }
747     else
748     {
749         ret = OC_STACK_OK;
750     }
751     return ret;
752 }
753
754 /**
755  * Get the default value.
756  * @retval  the gDefaultDoxm pointer;
757  */
758 static OicSecDoxm_t* GetDoxmDefault()
759 {
760     OC_LOG (INFO, TAG, PCF("GetDoxmToDefault"));
761     return &gDefaultDoxm;
762 }
763
764 /**
765  * This method is used by SRM to retrieve DOXM resource data.
766  *
767  * @retval  reference to @ref OicSecDoxm_t, binary format of Doxm resource data
768  */
769 const OicSecDoxm_t* GetDoxmResourceData()
770 {
771     return gDoxm;
772 }
773
774 /**
775  * Initialize DOXM resource by loading data from persistent storage.
776  *
777  * @retval  OC_STACK_OK for Success, otherwise some error value
778  */
779 OCStackResult InitDoxmResource()
780 {
781     OCStackResult ret = OC_STACK_ERROR;
782
783     //Read DOXM resource from PS
784     char* jsonSVRDatabase = GetSVRDatabase();
785     if(jsonSVRDatabase)
786     {
787         //Convert JSON DOXM into binary format
788         gDoxm = JSONToDoxmBin(jsonSVRDatabase);
789     }
790     /*
791      * If SVR database in persistent storage got corrupted or
792      * is not available for some reason, a default doxm is created
793      * which allows user to initiate doxm provisioning again.
794      */
795     if(!jsonSVRDatabase || !gDoxm)
796     {
797         gDoxm = GetDoxmDefault();
798     }
799     ret = CheckDeviceID();
800     if (ret == OC_STACK_OK)
801     {
802         //Instantiate 'oic.sec.doxm'
803         ret = CreateDoxmResource();
804     }
805     else
806     {
807         OC_LOG (ERROR, TAG, PCF("CheckDeviceID failed"));
808     }
809     OICFree(jsonSVRDatabase);
810     return ret;
811 }
812
813 /**
814  * Perform cleanup for DOXM resources.
815  *
816  * @return
817  * OC_STACK_OK    - no error
818  * OC_STACK_ERROR - stack process error
819  *
820  */
821 OCStackResult DeInitDoxmResource()
822 {
823     OCStackResult ret = OCDeleteResource(gDoxmHandle);
824     if(gDoxm  != &gDefaultDoxm)
825     {
826         DeleteDoxmBinData(gDoxm);
827     }
828     gDoxm = NULL;
829
830     if(OC_STACK_OK == ret)
831     {
832         return OC_STACK_OK;
833     }
834     else
835     {
836         return OC_STACK_ERROR;
837     }
838 }
839
840
841 /**
842  * This method returns the SRM device ID for this device.
843  *
844  * @retval  OC_STACK_OK for Success, otherwise some error value
845  */
846 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
847 {
848     if(deviceID && gDoxm)
849     {
850        *deviceID = gDoxm->deviceID;
851         return OC_STACK_OK;
852     }
853     return OC_STACK_ERROR;
854 }
855
856 /**
857  * @brief Gets the OicUuid_t value for the owner of this device.
858  *
859  * @return OC_STACK_OK if devOwner is a valid UUID, otherwise OC_STACK_ERROR.
860  */
861 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devOwner)
862 {
863     OCStackResult retVal = OC_STACK_ERROR;
864     if(gDoxm)
865     {
866         if(gDoxm->owned) {
867             *devOwner = gDoxm->owner; // TODO change to devOwner when available
868             retVal = OC_STACK_OK;
869         }
870     }
871     return retVal;
872 }