1 /*
2 * Copyright (C) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "dl_speke_protocol.h"
17
18 #include "alg_loader.h"
19 #include "common_defs.h"
20 #include "device_auth_defines.h"
21 #include "hc_log.h"
22
23 #define DL_SPEKE_AUTH_ID_MAX_LEN 256
24 #define DL_SPEKE_SALT_LEN 16
25 #define DL_SPEKE_KCF_CODE_LEN 1
26 #define DL_SPEKE_SECRET_LEN 32
27 #define DL_SPEKE_SESSION_KEY_LEN 32
28 #define DL_SPEKE_EXP_LEN 1
29 #define DL_SPEKE_ESK_SMALL_LEN 28
30 #define DL_SPEKE_ESK_LEN 32
31 #define DL_SPEKE_PRIME_SMALL_LEN 256
32 #define DL_SPEKE_PRIME_LEN 384
33 #define HICHAIN_SPEKE_BASE_INFO "hichain_speke_base_info"
34 #define SHARED_SECRET_DERIVED_FACTOR "hichain_speke_shared_secret_info"
35 #define HICHAIN_SPEKE_SESSIONKEY_INFO "hichain_speke_sessionkey_info"
36
37 #define FIELD_EVENT "event"
38 #define FIELD_ERR_CODE "errCode"
39
40 #define FIELD_SALT "salt"
41 #define FIELD_AUTH_ID_CLIENT "authIdC"
42 #define FIELD_AUTH_ID_SERVER "authIdS"
43 #define FIELD_EPK_CLIENT "epkC"
44 #define FIELD_EPK_SERVER "epkS"
45 #define FIELD_KCF_DATA_CLIENT "kcfDataC"
46 #define FIELD_KCF_DATA_SERVER "kcfDataS"
47
48 static const uint8_t KCF_CODE_CLIENT[DL_SPEKE_KCF_CODE_LEN] = { 0x04 };
49 static const uint8_t KCF_CODE_SERVER[DL_SPEKE_KCF_CODE_LEN] = { 0x03 };
50
51 static const char * const LARGE_PRIME_NUMBER_HEX_384 =
52 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74"\
53 "020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437"\
54 "4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"\
55 "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05"\
56 "98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB"\
57 "9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"\
58 "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"\
59 "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33"\
60 "A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"\
61 "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864"\
62 "D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E2"\
63 "08E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF";
64
65 static const char * const LARGE_PRIME_NUMBER_HEX_256 =
66 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74"\
67 "020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437"\
68 "4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"\
69 "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05"\
70 "98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB"\
71 "9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"\
72 "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"\
73 "3995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF";
74
75 typedef struct {
76 Uint8Buff psk;
77 Uint8Buff salt;
78 Uint8Buff base;
79 Uint8Buff eskSelf;
80 Uint8Buff epkSelf;
81 Uint8Buff epkPeer;
82 Uint8Buff authIdSelf;
83 Uint8Buff authIdPeer;
84 Uint8Buff kcfDataSelf;
85 Uint8Buff kcfDataPeer;
86 Uint8Buff sharedSecret;
87 uint32_t innerKeyLen;
88 const char *largePrimeNumHex;
89 DlSpekePrimeMod primeMod;
90 int32_t osAccountId;
91 } DlSpekeParams;
92
93 typedef struct {
94 BaseProtocol base;
95 DlSpekeParams params;
96 } DlSpekeProtocol;
97
98 typedef struct {
99 int32_t curState;
100 int32_t eventType;
101 int32_t (*stateProcessFunc)(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData);
102 void (*exceptionHandleFunc)(int32_t errorCode, CJson **outputData);
103 int32_t nextState;
104 } ProtocolStateNode;
105
DlSpekeClientStartReqBuildEvent(const DlSpekeParams * params,CJson ** outputData)106 static int32_t DlSpekeClientStartReqBuildEvent(const DlSpekeParams *params, CJson **outputData)
107 {
108 CJson *json = CreateJson();
109 if (json == NULL) {
110 LOGE("Creating json failed.");
111 return HC_ERR_JSON_CREATE;
112 }
113 if (AddIntToJson(json, FIELD_EVENT, CLEINT_START_REQ_EVENT) != HC_SUCCESS) {
114 LOGE("Adding eventName to json failed.");
115 FreeJson(json);
116 return HC_ERR_JSON_ADD;
117 }
118 if (AddByteToJson(json, FIELD_AUTH_ID_CLIENT, params->authIdSelf.val,
119 params->authIdSelf.length) != HC_SUCCESS) {
120 LOGE("Adding authIdC to json failed.");
121 FreeJson(json);
122 return HC_ERR_JSON_ADD;
123 }
124 bool isOnly256ModSupported = (((uint32_t)params->primeMod | DL_SPEKE_PRIME_MOD_256) == DL_SPEKE_PRIME_MOD_256);
125 if (AddBoolToJson(json, FIELD_SUPPORT_256_MOD, isOnly256ModSupported) != HC_SUCCESS) {
126 LOGE("Add isOnly256ModSupported failed.");
127 FreeJson(json);
128 return HC_ERR_JSON_ADD;
129 }
130 *outputData = json;
131 return HC_SUCCESS;
132 }
133
GetAuthIdPeerFromInput(const CJson * inputData,DlSpekeParams * params,bool isClient)134 static int32_t GetAuthIdPeerFromInput(const CJson *inputData, DlSpekeParams *params, bool isClient)
135 {
136 const char *authIdPeerStr = isClient ? GetStringFromJson(inputData, FIELD_AUTH_ID_SERVER) :
137 GetStringFromJson(inputData, FIELD_AUTH_ID_CLIENT);
138 if (authIdPeerStr == NULL) {
139 LOGE("get authIdPeerStr from inputData fail.");
140 return HC_ERR_JSON_GET;
141 }
142 uint32_t authIdPeerStrLen = HcStrlen(authIdPeerStr) / BYTE_TO_HEX_OPER_LENGTH;
143 if (authIdPeerStrLen == 0 || authIdPeerStrLen > DL_SPEKE_AUTH_ID_MAX_LEN) {
144 LOGE("Invalid authIdPeerStrLen: %" LOG_PUB "u.", authIdPeerStrLen);
145 return HC_ERR_CONVERT_FAILED;
146 }
147 if (InitUint8Buff(¶ms->authIdPeer, authIdPeerStrLen) != HC_SUCCESS) {
148 LOGE("allocate authIdPeer memory failed.");
149 return HC_ERR_ALLOC_MEMORY;
150 }
151 if (HexStringToByte(authIdPeerStr, params->authIdPeer.val, params->authIdPeer.length) != HC_SUCCESS) {
152 LOGE("HexStringToByte for peerAuthIdStr failed.");
153 return HC_ERR_CONVERT_FAILED;
154 }
155 return HC_SUCCESS;
156 }
157
GetSaltFromInput(const CJson * inputData,DlSpekeParams * params)158 static int32_t GetSaltFromInput(const CJson *inputData, DlSpekeParams *params)
159 {
160 if (InitUint8Buff(¶ms->salt, DL_SPEKE_SALT_LEN) != HC_SUCCESS) {
161 LOGE("allocate salt memory fail.");
162 return HC_ERR_ALLOC_MEMORY;
163 }
164 if (GetByteFromJson(inputData, FIELD_SALT, params->salt.val, params->salt.length) != HC_SUCCESS) {
165 LOGE("get salt from inputData fail.");
166 return HC_ERR_JSON_GET;
167 }
168 return HC_SUCCESS;
169 }
170
GetEpkPeerFromInput(const CJson * inputData,DlSpekeParams * params,bool isClient)171 static int32_t GetEpkPeerFromInput(const CJson *inputData, DlSpekeParams *params, bool isClient)
172 {
173 const char *epkPeerStr = isClient ? GetStringFromJson(inputData, FIELD_EPK_SERVER) :
174 GetStringFromJson(inputData, FIELD_EPK_CLIENT);
175 if (epkPeerStr == NULL) {
176 LOGE("get epkPeerStr from inputData failed, epkPeerStr is NULL.");
177 return HC_ERR_JSON_GET;
178 }
179 if (InitUint8Buff(¶ms->epkPeer, HcStrlen(epkPeerStr) / BYTE_TO_HEX_OPER_LENGTH) != HC_SUCCESS) {
180 LOGE("allocate epkPeerStr buff memory failed.");
181 return HC_ERR_ALLOC_MEMORY;
182 }
183 if (HexStringToByte(epkPeerStr, params->epkPeer.val, params->epkPeer.length) != HC_SUCCESS) {
184 LOGE("HexStringToByte for epkPeerStr failed.");
185 return HC_ERR_CONVERT_FAILED;
186 }
187 return HC_SUCCESS;
188 }
189
GetKcfDataPeerFromInput(const CJson * inputData,DlSpekeParams * params,bool isClient)190 static int32_t GetKcfDataPeerFromInput(const CJson *inputData, DlSpekeParams *params, bool isClient)
191 {
192 if (InitUint8Buff(¶ms->kcfDataPeer, SHA256_LEN) != HC_SUCCESS) {
193 LOGE("allocate kcfDataPeer fail.");
194 return HC_ERR_ALLOC_MEMORY;
195 }
196 if (GetByteFromJson(inputData, (isClient ? FIELD_KCF_DATA_SERVER : FIELD_KCF_DATA_CLIENT),
197 params->kcfDataPeer.val, params->kcfDataPeer.length) != HC_SUCCESS) {
198 LOGE("get kcfDataPeer from inputData fail.");
199 return HC_ERR_JSON_GET;
200 }
201 return HC_SUCCESS;
202 }
203
DlSpekeClientStartReq(DlSpekeProtocol * impl,const CJson * inputData,CJson ** outputData)204 static int32_t DlSpekeClientStartReq(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData)
205 {
206 (void)inputData;
207 return DlSpekeClientStartReqBuildEvent(&impl->params, outputData);
208 }
209
SetSelfKeyLenByMod(const CJson * inputData,DlSpekeParams * params)210 static int32_t SetSelfKeyLenByMod(const CJson *inputData, DlSpekeParams *params)
211 {
212 bool isOnly256ModSupported = true;
213 if (GetBoolFromJson(inputData, FIELD_SUPPORT_256_MOD, &isOnly256ModSupported) != HC_SUCCESS) {
214 LOGE("Get isOnly256ModSupported failed.");
215 return HC_ERR_JSON_GET;
216 }
217 params->primeMod = isOnly256ModSupported ? (DlSpekePrimeMod)(params->primeMod & DL_SPEKE_PRIME_MOD_256) :
218 (DlSpekePrimeMod)(params->primeMod & DL_SPEKE_PRIME_MOD_384);
219 if (((uint32_t)params->primeMod & DL_SPEKE_PRIME_MOD_384) != 0) {
220 params->eskSelf.length = DL_SPEKE_ESK_LEN;
221 params->innerKeyLen = DL_SPEKE_PRIME_LEN;
222 return HC_SUCCESS;
223 }
224 if (((uint32_t)params->primeMod & DL_SPEKE_PRIME_MOD_256) != 0) {
225 params->eskSelf.length = DL_SPEKE_ESK_SMALL_LEN;
226 params->innerKeyLen = DL_SPEKE_PRIME_SMALL_LEN;
227 return HC_SUCCESS;
228 }
229 LOGE("Unsupported DL SPEKE mod: %" LOG_PUB "x.", params->primeMod);
230 return HC_ERR_NOT_SUPPORT;
231 }
232
DlSpekeServerStartRspParseEvent(const CJson * inputData,DlSpekeParams * params)233 static int32_t DlSpekeServerStartRspParseEvent(const CJson *inputData, DlSpekeParams *params)
234 {
235 int32_t res = SetSelfKeyLenByMod(inputData, params);
236 if (res != HC_SUCCESS) {
237 return res;
238 }
239 return GetAuthIdPeerFromInput(inputData, params, false);
240 }
241
CalSalt(DlSpekeParams * params)242 static int32_t CalSalt(DlSpekeParams *params)
243 {
244 if (InitUint8Buff(¶ms->salt, DL_SPEKE_SALT_LEN) != HC_SUCCESS) {
245 LOGE("allocate salt memory fail.");
246 return HC_ERR_ALLOC_MEMORY;
247 }
248 int32_t res = GetLoaderInstance()->generateRandom(¶ms->salt);
249 if (res != HC_SUCCESS) {
250 LOGE("Generate salt failed, res: %" LOG_PUB "x.", res);
251 return res;
252 }
253 return HC_SUCCESS;
254 }
255
CalSecret(DlSpekeParams * params,Uint8Buff * secret)256 static int32_t CalSecret(DlSpekeParams *params, Uint8Buff *secret)
257 {
258 Uint8Buff keyInfo = { (uint8_t *)HICHAIN_SPEKE_BASE_INFO, HcStrlen(HICHAIN_SPEKE_BASE_INFO) };
259 KeyParams keyParams = { { params->psk.val, params->psk.length, false }, false, params->osAccountId };
260 int32_t res = GetLoaderInstance()->computeHkdf(&keyParams, &(params->salt), &keyInfo, secret);
261 if (res != HC_SUCCESS) {
262 LOGE("Derive secret from psk failed, res: %" LOG_PUB "x.", res);
263 return res;
264 }
265 ClearFreeUint8Buff(¶ms->psk);
266 return HC_SUCCESS;
267 }
268
SetSelfKeyLenByEpkPeerAndMod(DlSpekeParams * params)269 static int32_t SetSelfKeyLenByEpkPeerAndMod(DlSpekeParams *params)
270 {
271 if ((params->epkPeer.length == DL_SPEKE_PRIME_LEN) &&
272 (((uint32_t)params->primeMod & DL_SPEKE_PRIME_MOD_384) != 0)) {
273 params->eskSelf.length = DL_SPEKE_ESK_LEN;
274 params->innerKeyLen = DL_SPEKE_PRIME_LEN;
275 return HC_SUCCESS;
276 }
277 if ((params->epkPeer.length == DL_SPEKE_PRIME_SMALL_LEN) &&
278 (((uint32_t)params->primeMod & DL_SPEKE_PRIME_MOD_256) != 0)) {
279 params->eskSelf.length = DL_SPEKE_ESK_SMALL_LEN;
280 params->innerKeyLen = DL_SPEKE_PRIME_SMALL_LEN;
281 return HC_SUCCESS;
282 }
283 LOGE("DL SPEKE mod: %" LOG_PUB "x, Invalid epkPeer length: %" LOG_PUB "u.",
284 params->primeMod, params->epkPeer.length);
285 return HC_ERR_INVALID_LEN;
286 }
287
DlSpekeCalBase(DlSpekeParams * params,Uint8Buff * secret)288 static int32_t DlSpekeCalBase(DlSpekeParams *params, Uint8Buff *secret)
289 {
290 if (InitUint8Buff(¶ms->base, params->innerKeyLen) != HC_SUCCESS) {
291 LOGE("Failed to init base!");
292 return HC_ERR_ALLOC_MEMORY;
293 }
294 uint8_t expVal[DL_SPEKE_EXP_LEN] = { 2 };
295 Uint8Buff exp = { expVal, DL_SPEKE_EXP_LEN };
296 params->largePrimeNumHex = (params->innerKeyLen == DL_SPEKE_PRIME_SMALL_LEN) ?
297 LARGE_PRIME_NUMBER_HEX_256 : LARGE_PRIME_NUMBER_HEX_384;
298 int32_t res = GetLoaderInstance()->bigNumExpMod(secret, &exp, params->largePrimeNumHex, ¶ms->base);
299 if (res != HC_SUCCESS) {
300 LOGE("BigNumExpMod for base failed, res: %" LOG_PUB "x.", res);
301 }
302 return res;
303 }
304
DlSpekeCalEskSelf(DlSpekeParams * params)305 static int32_t DlSpekeCalEskSelf(DlSpekeParams *params)
306 {
307 if (InitUint8Buff(¶ms->eskSelf, params->eskSelf.length) != HC_SUCCESS) {
308 LOGE("Failed to init eskSelf!");
309 return HC_ERR_ALLOC_MEMORY;
310 }
311 int res = GetLoaderInstance()->generateRandom(&(params->eskSelf));
312 if (res != HC_SUCCESS) {
313 LOGE("GenerateRandom for eskSelf failed, res: %" LOG_PUB "x.", res);
314 }
315 return res;
316 }
317
DlSpekeCalEpkSelf(DlSpekeParams * params)318 static int32_t DlSpekeCalEpkSelf(DlSpekeParams *params)
319 {
320 if (InitUint8Buff(¶ms->epkSelf, params->innerKeyLen) != HC_SUCCESS) {
321 LOGE("Failed to init epkSelf!");
322 return HC_ERR_ALLOC_MEMORY;
323 }
324 int32_t res = GetLoaderInstance()->bigNumExpMod(¶ms->base, &(params->eskSelf),
325 params->largePrimeNumHex, &(params->epkSelf));
326 if (res != HC_SUCCESS) {
327 LOGE("BigNumExpMod for epkSelf failed, res: %" LOG_PUB "x.", res);
328 }
329 return res;
330 }
331
IsEpkPeerLenValid(DlSpekeParams * params)332 static bool IsEpkPeerLenValid(DlSpekeParams *params)
333 {
334 if ((params->epkPeer.length == DL_SPEKE_PRIME_LEN) &&
335 (((uint32_t)params->primeMod & DL_SPEKE_PRIME_MOD_384) != 0)) {
336 return true;
337 }
338 if ((params->epkPeer.length == DL_SPEKE_PRIME_SMALL_LEN) &&
339 (((uint32_t)params->primeMod & DL_SPEKE_PRIME_MOD_256) != 0)) {
340 return true;
341 }
342 LOGE("Invalid epkPeer length: %" LOG_PUB "u.", params->epkPeer.length);
343 return false;
344 }
345
CheckEpkPeerValid(DlSpekeParams * params)346 static int32_t CheckEpkPeerValid(DlSpekeParams *params)
347 {
348 if (!IsEpkPeerLenValid(params)) {
349 return HC_ERR_INVALID_LEN;
350 }
351 if (!GetLoaderInstance()->checkDlPublicKey(¶ms->epkPeer, params->largePrimeNumHex)) {
352 LOGE("Check EC_SPEKE publicKey fail.");
353 return HC_ERR_BAD_MESSAGE;
354 }
355 return HC_SUCCESS;
356 }
357
CalTmpSharedSecret(DlSpekeParams * params,Uint8Buff * tmpSharedSecret)358 static int32_t CalTmpSharedSecret(DlSpekeParams *params, Uint8Buff *tmpSharedSecret)
359 {
360 int32_t res = GetLoaderInstance()->bigNumExpMod(&(params->epkPeer), &(params->eskSelf),
361 params->largePrimeNumHex, tmpSharedSecret);
362 if (res != HC_SUCCESS) {
363 LOGE("Cal tmpSharedSecret failed, res: %" LOG_PUB "x", res);
364 }
365 return res;
366 }
367
CalSidSelf(DlSpekeParams * params,Uint8Buff * sidSelf)368 static int32_t CalSidSelf(DlSpekeParams *params, Uint8Buff *sidSelf)
369 {
370 uint32_t sidSelfMsgLen = params->authIdSelf.length + params->innerKeyLen;
371 Uint8Buff sidSelfMsg = { NULL, 0 };
372 if (InitUint8Buff(&sidSelfMsg, sidSelfMsgLen) != HC_SUCCESS) {
373 LOGE("Allocate sidSelfMsg memory fail.");
374 return HC_ERR_ALLOC_MEMORY;
375 }
376 if (memcpy_s(sidSelfMsg.val, sidSelfMsg.length, params->authIdSelf.val, params->authIdSelf.length) != EOK) {
377 LOGE("Memory copy savely for authIdSelf to sidSelfMsg val failed.");
378 ClearFreeUint8Buff(&sidSelfMsg);
379 return HC_ERR_MEMORY_COPY;
380 }
381 if (memcpy_s(sidSelfMsg.val + params->authIdSelf.length, sidSelfMsg.length - params->authIdSelf.length,
382 params->epkSelf.val, params->innerKeyLen) != EOK) { // only need x-coordinate
383 LOGE("Memory copy savely for epkSelf_X failed.");
384 ClearFreeUint8Buff(&sidSelfMsg);
385 return HC_ERR_MEMORY_COPY;
386 }
387 int32_t res = GetLoaderInstance()->sha256(&sidSelfMsg, sidSelf);
388 ClearFreeUint8Buff(&sidSelfMsg);
389 if (res != HC_SUCCESS) {
390 LOGE("Sha256 for sidSelf failed, res: %" LOG_PUB "x.", res);
391 return res;
392 }
393 return HC_SUCCESS;
394 }
395
CalSidPeer(DlSpekeParams * params,Uint8Buff * sidPeer)396 static int32_t CalSidPeer(DlSpekeParams *params, Uint8Buff *sidPeer)
397 {
398 uint32_t sidPeerMsgLen = params->authIdPeer.length + params->innerKeyLen;
399 Uint8Buff sidPeerMsg = { NULL, 0 };
400 if (InitUint8Buff(&sidPeerMsg, sidPeerMsgLen) != HC_SUCCESS) {
401 LOGE("Allocate sidPeerMsg memory failed!");
402 return HC_ERR_ALLOC_MEMORY;
403 }
404 if (memcpy_s(sidPeerMsg.val, sidPeerMsg.length, params->authIdPeer.val, params->authIdPeer.length) != EOK) {
405 LOGE("Memcpy savely for peer auth id failed!");
406 ClearFreeUint8Buff(&sidPeerMsg);
407 return HC_ERR_MEMORY_COPY;
408 }
409 if (memcpy_s(sidPeerMsg.val + params->authIdPeer.length, sidPeerMsg.length - params->authIdPeer.length,
410 params->epkPeer.val, params->innerKeyLen) != EOK) { // only need x-coordinate
411 LOGE("Memcpy savely for epkPeer_X failed!");
412 ClearFreeUint8Buff(&sidPeerMsg);
413 return HC_ERR_MEMORY_COPY;
414 }
415 int32_t res = GetLoaderInstance()->sha256(&sidPeerMsg, sidPeer);
416 ClearFreeUint8Buff(&sidPeerMsg);
417 if (res != HC_SUCCESS) {
418 LOGE("Sha256 for sidPeer failed, res: %" LOG_PUB "x.", res);
419 return res;
420 }
421 return HC_SUCCESS;
422 }
423
CalSid(DlSpekeParams * params,Uint8Buff * sid)424 static int32_t CalSid(DlSpekeParams *params, Uint8Buff *sid)
425 {
426 uint8_t sidSelfVal[SHA256_LEN] = { 0 };
427 uint8_t sidPeerVal[SHA256_LEN] = { 0 };
428 Uint8Buff sidSelf = { sidSelfVal, SHA256_LEN };
429 Uint8Buff sidPeer = { sidPeerVal, SHA256_LEN };
430 int32_t res = CalSidSelf(params, &sidSelf);
431 if (res != HC_SUCCESS) {
432 return res;
433 }
434 res = CalSidPeer(params, &sidPeer);
435 if (res != HC_SUCCESS) {
436 return res;
437 }
438 Uint8Buff *maxSid = &sidSelf;
439 Uint8Buff *minSid = &sidPeer;
440 if (GetLoaderInstance()->bigNumCompare(&sidSelf, &sidPeer) > 0) {
441 maxSid = &sidPeer;
442 minSid = &sidSelf;
443 }
444 if (memcpy_s(sid->val, sid->length, maxSid->val, maxSid->length) != EOK) {
445 LOGE("Memcpy for maxSid failed.");
446 return HC_ERR_MEMORY_COPY;
447 }
448 if (memcpy_s(sid->val + maxSid->length, sid->length - maxSid->length, minSid->val, minSid->length) != EOK) {
449 LOGE("Memcpy for minSid failed.");
450 return HC_ERR_MEMORY_COPY;
451 }
452 return HC_SUCCESS;
453 }
454
CombineSharedSecretMsg(DlSpekeParams * params,const Uint8Buff * tmpSharedSecret,const Uint8Buff * sid,Uint8Buff * sharedSecretMsg)455 static int32_t CombineSharedSecretMsg(DlSpekeParams *params, const Uint8Buff *tmpSharedSecret, const Uint8Buff *sid,
456 Uint8Buff *sharedSecretMsg)
457 {
458 uint32_t usedLen = 0;
459 if (memcpy_s(sharedSecretMsg->val, sharedSecretMsg->length, sid->val, sid->length) != EOK) {
460 LOGE("Memcpy for sidHex failed.");
461 return HC_ERR_MEMORY_COPY;
462 }
463 usedLen += sid->length;
464 // Only need x-coordinate
465 if (memcpy_s(sharedSecretMsg->val + usedLen, sharedSecretMsg->length - usedLen,
466 tmpSharedSecret->val, params->innerKeyLen) != EOK) {
467 LOGE("Memcpy for tmpSharedSecret failed.");
468 return HC_ERR_MEMORY_COPY;
469 }
470 usedLen += params->innerKeyLen;
471 if (memcpy_s(sharedSecretMsg->val + usedLen, sharedSecretMsg->length - usedLen,
472 SHARED_SECRET_DERIVED_FACTOR, HcStrlen(SHARED_SECRET_DERIVED_FACTOR)) != EOK) {
473 LOGE("Memcpy for sharedSecret derived factor failed.");
474 return HC_ERR_MEMORY_COPY;
475 }
476 return HC_SUCCESS;
477 }
478
GenerateSharedSecretMsg(DlSpekeParams * params,Uint8Buff * sharedSecretMsg)479 static int32_t GenerateSharedSecretMsg(DlSpekeParams *params, Uint8Buff *sharedSecretMsg)
480 {
481 Uint8Buff tmpSharedSecret = { NULL, 0 };
482 if (InitUint8Buff(&tmpSharedSecret, params->innerKeyLen) != HC_SUCCESS) {
483 LOGE("allocate p memory fail.");
484 return HC_ERR_ALLOC_MEMORY;
485 }
486 int32_t res = CalTmpSharedSecret(params, &tmpSharedSecret);
487 if (res != HC_SUCCESS) {
488 ClearFreeUint8Buff(&tmpSharedSecret);
489 return res;
490 }
491 // sid is composed of client sid and server sid, so need twice SHA256_LEN
492 uint8_t sidVal[SHA256_LEN * 2] = { 0 };
493 Uint8Buff sid = { sidVal, SHA256_LEN * 2 };
494 res = CalSid(params, &sid);
495 if (res != HC_SUCCESS) {
496 ClearFreeUint8Buff(&tmpSharedSecret);
497 return res;
498 }
499 res = CombineSharedSecretMsg(params, &tmpSharedSecret, &sid, sharedSecretMsg);
500 (void)memset_s(sid.val, sid.length, 0, sid.length);
501 ClearFreeUint8Buff(&tmpSharedSecret);
502 return res;
503 }
504
CalSharedSecret(DlSpekeParams * params)505 static int32_t CalSharedSecret(DlSpekeParams *params)
506 {
507 uint32_t sharedSecretMsgLen = SHA256_LEN * 2 + params->innerKeyLen + HcStrlen(SHARED_SECRET_DERIVED_FACTOR);
508 Uint8Buff sharedSecretMsg = { NULL, 0 };
509 if (InitUint8Buff(&sharedSecretMsg, sharedSecretMsgLen) != HC_SUCCESS) {
510 LOGE("allocate sharedSecretMsg memory fail.");
511 return HC_ERR_ALLOC_MEMORY;
512 }
513 int32_t res = GenerateSharedSecretMsg(params, &sharedSecretMsg);
514 if (res != HC_SUCCESS) {
515 ClearFreeUint8Buff(&sharedSecretMsg);
516 return res;
517 }
518 if (InitUint8Buff(¶ms->sharedSecret, SHA256_LEN)) {
519 LOGE("allocate sharedSecret memory fail.");
520 ClearFreeUint8Buff(&sharedSecretMsg);
521 return HC_ERR_ALLOC_MEMORY;
522 }
523 res = GetLoaderInstance()->sha256(&sharedSecretMsg, ¶ms->sharedSecret);
524 ClearFreeUint8Buff(&sharedSecretMsg);
525 if (res != HC_SUCCESS) {
526 LOGE("Sha256 for sharedSecret failed, res: %" LOG_PUB "x", res);
527 }
528 return res;
529 }
530
CombineProtectedMsg(DlSpekeProtocol * impl,bool isVerify,Uint8Buff * kcfDataMsg,uint32_t usedLen)531 static int32_t CombineProtectedMsg(DlSpekeProtocol *impl, bool isVerify, Uint8Buff *kcfDataMsg, uint32_t usedLen)
532 {
533 Uint8Buff *firstProtectedMsg = isVerify ? &(impl->base.protectedMsg.peerMsg) : &(impl->base.protectedMsg.selfMsg);
534 Uint8Buff *secondProtectedMsg = isVerify ? &(impl->base.protectedMsg.selfMsg) : &(impl->base.protectedMsg.peerMsg);
535 if (IsUint8BuffValid(firstProtectedMsg, PROTECTED_MSG_MAX_LEN)) {
536 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
537 firstProtectedMsg->val, firstProtectedMsg->length) != EOK) {
538 LOGE("Memcpy firstProtectedMsg failed.");
539 return HC_ERR_MEMORY_COPY;
540 }
541 usedLen += firstProtectedMsg->length;
542 }
543 if (IsUint8BuffValid(secondProtectedMsg, PROTECTED_MSG_MAX_LEN)) {
544 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
545 secondProtectedMsg->val, secondProtectedMsg->length) != EOK) {
546 LOGE("Memcpy secondProtectedMsg failed.");
547 return HC_ERR_MEMORY_COPY;
548 }
549 }
550 return HC_SUCCESS;
551 }
552
GenerateKcfDataMsg(DlSpekeProtocol * impl,bool isClient,bool isVerify,Uint8Buff * kcfDataMsg)553 static int32_t GenerateKcfDataMsg(DlSpekeProtocol *impl, bool isClient, bool isVerify, Uint8Buff *kcfDataMsg)
554 {
555 DlSpekeParams *params = &impl->params;
556 const uint8_t *kcfCode = ((isClient && !isVerify) || (!isClient && isVerify)) ? KCF_CODE_CLIENT : KCF_CODE_SERVER;
557 if (memcpy_s(kcfDataMsg->val, kcfDataMsg->length, kcfCode, DL_SPEKE_KCF_CODE_LEN) != HC_SUCCESS) {
558 LOGE("Memcpy for kcfCode failed.");
559 return HC_ERR_MEMORY_COPY;
560 }
561 uint32_t usedLen = DL_SPEKE_KCF_CODE_LEN;
562 Uint8Buff *epkClient = isClient ? ¶ms->epkSelf : ¶ms->epkPeer;
563 Uint8Buff *epkServer = isClient ? ¶ms->epkPeer : ¶ms->epkSelf;
564 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
565 epkClient->val, params->innerKeyLen) != EOK) { // Only the x-coordinate of epk is required
566 LOGE("Memcpy for epkClient failed.");
567 return HC_ERR_MEMORY_COPY;
568 }
569 usedLen += params->innerKeyLen;
570 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
571 epkServer->val, params->innerKeyLen) != EOK) { // Only the x-coordinate of epk is required
572 LOGE("Memcpy for epkServer failed.");
573 return HC_ERR_MEMORY_COPY;
574 }
575 usedLen += params->innerKeyLen;
576 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
577 params->sharedSecret.val, params->sharedSecret.length) != EOK) {
578 LOGE("Memcpy for sharedSecret failed.");
579 return HC_ERR_MEMORY_COPY;
580 }
581 usedLen += params->sharedSecret.length;
582 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
583 params->base.val, params->innerKeyLen) != EOK) { // Only the x-coordinate of base is required
584 LOGE("Memcpy for base_X failed.");
585 return HC_ERR_MEMORY_COPY;
586 }
587 usedLen += params->innerKeyLen;
588 return CombineProtectedMsg(impl, isVerify, kcfDataMsg, usedLen);
589 }
590
CalKcfDataSelf(DlSpekeProtocol * impl,bool isClient)591 static int32_t CalKcfDataSelf(DlSpekeProtocol *impl, bool isClient)
592 {
593 uint32_t kcfDataMsgLen = DL_SPEKE_KCF_CODE_LEN + impl->params.innerKeyLen + impl->params.innerKeyLen +
594 SHA256_LEN + impl->params.innerKeyLen + impl->base.protectedMsg.selfMsg.length +
595 impl->base.protectedMsg.peerMsg.length;
596 Uint8Buff kcfDataMsg = { NULL, 0 };
597 if (InitUint8Buff(&kcfDataMsg, kcfDataMsgLen) != HC_SUCCESS) {
598 LOGE("Init kcfDataMsg failed.");
599 return HC_ERR_ALLOC_MEMORY;
600 }
601 int32_t res = GenerateKcfDataMsg(impl, isClient, false, &kcfDataMsg);
602 if (res != HC_SUCCESS) {
603 ClearFreeUint8Buff(&kcfDataMsg);
604 return res;
605 }
606 if (InitUint8Buff(&impl->params.kcfDataSelf, SHA256_LEN) != HC_SUCCESS) {
607 LOGE("Init kcfDataSelf memory failed.");
608 ClearFreeUint8Buff(&kcfDataMsg);
609 return HC_ERR_ALLOC_MEMORY;
610 }
611 res = GetLoaderInstance()->sha256(&kcfDataMsg, &impl->params.kcfDataSelf);
612 ClearFreeUint8Buff(&kcfDataMsg);
613 if (res != HC_SUCCESS) {
614 LOGE("Error occurs, sha256 for kcfDataSelf failed, res: %" LOG_PUB "x", res);
615 }
616 return res;
617 }
618
VerifyKcfDataPeer(DlSpekeProtocol * impl,bool isClient)619 static int32_t VerifyKcfDataPeer(DlSpekeProtocol *impl, bool isClient)
620 {
621 uint32_t kcfDataMsgLen = DL_SPEKE_KCF_CODE_LEN + impl->params.innerKeyLen + impl->params.innerKeyLen +
622 SHA256_LEN + impl->params.innerKeyLen + impl->base.protectedMsg.selfMsg.length +
623 impl->base.protectedMsg.peerMsg.length;
624 Uint8Buff kcfDataMsg = { NULL, 0 };
625 if (InitUint8Buff(&kcfDataMsg, kcfDataMsgLen) != HC_SUCCESS) {
626 LOGE("Error occurs, init kcfDataMsg failed.");
627 return HC_ERR_ALLOC_MEMORY;
628 }
629 int32_t res = GenerateKcfDataMsg(impl, isClient, true, &kcfDataMsg);
630 if (res != HC_SUCCESS) {
631 ClearFreeUint8Buff(&kcfDataMsg);
632 return res;
633 }
634 uint8_t kcfDataPeerVal[SHA256_LEN] = { 0 };
635 Uint8Buff kcfDataPeer = { kcfDataPeerVal, SHA256_LEN };
636 res = GetLoaderInstance()->sha256(&kcfDataMsg, &kcfDataPeer);
637 ClearFreeUint8Buff(&kcfDataMsg);
638 if (res != HC_SUCCESS) {
639 LOGE("Sha256 for kcfDataPeer failed, res: %" LOG_PUB "x", res);
640 return res;
641 }
642 if (memcmp(kcfDataPeer.val, impl->params.kcfDataPeer.val, kcfDataPeer.length) != 0) {
643 LOGE("verify kcfData fail.");
644 (void)memset_s(kcfDataPeer.val, kcfDataPeer.length, 0, kcfDataPeer.length);
645 return PROOF_MISMATCH;
646 }
647 return HC_SUCCESS;
648 }
649
CalSessionKey(DlSpekeProtocol * impl)650 static int32_t CalSessionKey(DlSpekeProtocol *impl)
651 {
652 if (InitUint8Buff(&impl->base.sessionKey, DL_SPEKE_SESSION_KEY_LEN) != HC_SUCCESS) {
653 LOGE("Allocating sessionKey memory failed.");
654 return HC_ERR_ALLOC_MEMORY;
655 }
656 KeyParams keyParams = {
657 { impl->params.sharedSecret.val, impl->params.sharedSecret.length, false },
658 false,
659 impl->params.osAccountId
660 };
661 Uint8Buff keyInfo = { (uint8_t *)HICHAIN_SPEKE_SESSIONKEY_INFO, HcStrlen(HICHAIN_SPEKE_SESSIONKEY_INFO) };
662 int32_t res = GetLoaderInstance()->computeHkdf(&keyParams, &impl->params.salt, &keyInfo,
663 &impl->base.sessionKey);
664 ClearFreeUint8Buff(&impl->params.salt);
665 ClearFreeUint8Buff(&impl->params.sharedSecret);
666 if (res != HC_SUCCESS) {
667 LOGE("Computing Hkdf for sessionKey failed, res: %" LOG_PUB "x", res);
668 }
669 return res;
670 }
671
DlSpekeServerStartRspProcEvent(DlSpekeProtocol * impl)672 static int32_t DlSpekeServerStartRspProcEvent(DlSpekeProtocol *impl)
673 {
674 int32_t res = CalSalt(&impl->params);
675 if (res != HC_SUCCESS) {
676 return res;
677 }
678 uint8_t secretVal[DL_SPEKE_SECRET_LEN] = { 0 };
679 Uint8Buff secret = { secretVal, DL_SPEKE_SECRET_LEN };
680 res = CalSecret(&impl->params, &secret);
681 if (res != HC_SUCCESS) {
682 return res;
683 }
684 res = DlSpekeCalBase(&impl->params, &secret);
685 if (res != HC_SUCCESS) {
686 return res;
687 }
688 res = DlSpekeCalEskSelf(&impl->params);
689 if (res != HC_SUCCESS) {
690 return res;
691 }
692 return DlSpekeCalEpkSelf(&impl->params);
693 }
694
DlSpekeServerStartRspBuildEvent(const DlSpekeParams * params,CJson ** outputData)695 static int32_t DlSpekeServerStartRspBuildEvent(const DlSpekeParams *params, CJson **outputData)
696 {
697 CJson *json = CreateJson();
698 if (json == NULL) {
699 LOGE("Create json failed.");
700 return HC_ERR_JSON_CREATE;
701 }
702 if (AddIntToJson(json, FIELD_EVENT, SERVER_START_RSP_EVENT) != HC_SUCCESS) {
703 LOGE("Add eventName to json fail.");
704 FreeJson(json);
705 return HC_ERR_JSON_ADD;
706 }
707 if (AddByteToJson(json, FIELD_EPK_SERVER, params->epkSelf.val, params->epkSelf.length) != HC_SUCCESS) {
708 LOGE("Add server epk to json fail.");
709 FreeJson(json);
710 return HC_ERR_JSON_ADD;
711 }
712 if (AddByteToJson(json, FIELD_AUTH_ID_SERVER, params->authIdSelf.val,
713 params->authIdSelf.length) != HC_SUCCESS) {
714 LOGE("Add server auth id to json fail.");
715 FreeJson(json);
716 return HC_ERR_JSON_ADD;
717 }
718 if (AddByteToJson(json, FIELD_SALT, params->salt.val, params->salt.length) != HC_SUCCESS) {
719 LOGE("Add salt to json fail.");
720 FreeJson(json);
721 return HC_ERR_JSON_ADD;
722 }
723 *outputData = json;
724 return HC_SUCCESS;
725 }
726
DlSpekeServerStartRsp(DlSpekeProtocol * impl,const CJson * inputData,CJson ** outputData)727 static int32_t DlSpekeServerStartRsp(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData)
728 {
729 int32_t res = DlSpekeServerStartRspParseEvent(inputData, &impl->params);
730 if (res != HC_SUCCESS) {
731 return res;
732 }
733 res = DlSpekeServerStartRspProcEvent(impl);
734 if (res != HC_SUCCESS) {
735 return res;
736 }
737 return DlSpekeServerStartRspBuildEvent(&impl->params, outputData);
738 }
739
DlSpekeClientFinishReqParseEvent(const CJson * inputData,DlSpekeParams * params)740 static int32_t DlSpekeClientFinishReqParseEvent(const CJson *inputData, DlSpekeParams *params)
741 {
742 int32_t res = GetSaltFromInput(inputData, params);
743 if (res != HC_SUCCESS) {
744 return res;
745 }
746 res = GetEpkPeerFromInput(inputData, params, true);
747 if (res != HC_SUCCESS) {
748 return res;
749 }
750 return GetAuthIdPeerFromInput(inputData, params, true);
751 }
752
DlSpekeClientFinishReqProcEvent(DlSpekeProtocol * impl)753 static int32_t DlSpekeClientFinishReqProcEvent(DlSpekeProtocol *impl)
754 {
755 uint8_t secretVal[DL_SPEKE_SECRET_LEN] = { 0 };
756 Uint8Buff secret = { secretVal, DL_SPEKE_SECRET_LEN };
757 int32_t res = CalSecret(&impl->params, &secret);
758 if (res != HC_SUCCESS) {
759 return res;
760 }
761 res = DlSpekeCalBase(&impl->params, &secret);
762 (void)memset_s(secret.val, secret.length, 0, secret.length);
763 if (res != HC_SUCCESS) {
764 return res;
765 }
766 res = DlSpekeCalEskSelf(&impl->params);
767 if (res != HC_SUCCESS) {
768 return res;
769 }
770 res = DlSpekeCalEpkSelf(&impl->params);
771 if (res != HC_SUCCESS) {
772 return res;
773 }
774 res = CheckEpkPeerValid(&impl->params);
775 if (res != HC_SUCCESS) {
776 return res;
777 }
778 res = CalSharedSecret(&impl->params);
779 if (res != HC_SUCCESS) {
780 return res;
781 }
782 return CalKcfDataSelf(impl, true);
783 }
784
DlSpekeClientFinishReqBuildEvent(DlSpekeParams * params,CJson ** outputData)785 static int32_t DlSpekeClientFinishReqBuildEvent(DlSpekeParams *params, CJson **outputData)
786 {
787 CJson *json = CreateJson();
788 if (json == NULL) {
789 LOGE("Create json failed.");
790 return HC_ERR_JSON_CREATE;
791 }
792 if (AddIntToJson(json, FIELD_EVENT, CLEINT_FINISH_REQ_EVENT) != HC_SUCCESS) {
793 LOGE("Add eventName to json fail.");
794 FreeJson(json);
795 return HC_ERR_JSON_ADD;
796 }
797 if (AddByteToJson(json, FIELD_EPK_CLIENT, params->epkSelf.val, params->epkSelf.length) != HC_SUCCESS) {
798 LOGE("Add client epk to json fail.");
799 FreeJson(json);
800 return HC_ERR_JSON_ADD;
801 }
802 if (AddByteToJson(json, FIELD_KCF_DATA_CLIENT, params->kcfDataSelf.val,
803 params->kcfDataSelf.length) != HC_SUCCESS) {
804 LOGE("Add kcfDataC to json fail.");
805 FreeJson(json);
806 return HC_ERR_JSON_ADD;
807 }
808 *outputData = json;
809 return HC_SUCCESS;
810 }
811
DlSpekeClientFinishReq(DlSpekeProtocol * impl,const CJson * inputData,CJson ** outputData)812 static int32_t DlSpekeClientFinishReq(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData)
813 {
814 int32_t res = DlSpekeClientFinishReqParseEvent(inputData, &impl->params);
815 if (res != HC_SUCCESS) {
816 return res;
817 }
818 res = SetSelfKeyLenByEpkPeerAndMod(&impl->params);
819 if (res != HC_SUCCESS) {
820 return res;
821 }
822 res = DlSpekeClientFinishReqProcEvent(impl);
823 if (res != HC_SUCCESS) {
824 return res;
825 }
826 return DlSpekeClientFinishReqBuildEvent(&impl->params, outputData);
827 }
828
DlSpekeServerFinishRspParseEvent(const CJson * inputData,DlSpekeParams * params)829 static int32_t DlSpekeServerFinishRspParseEvent(const CJson *inputData, DlSpekeParams *params)
830 {
831 int32_t res = GetEpkPeerFromInput(inputData, params, false);
832 if (res != HC_SUCCESS) {
833 return res;
834 }
835 return GetKcfDataPeerFromInput(inputData, params, false);
836 }
837
DlSpekeServerFinishRspProcEvent(DlSpekeProtocol * impl)838 static int32_t DlSpekeServerFinishRspProcEvent(DlSpekeProtocol *impl)
839 {
840 int32_t res = CheckEpkPeerValid(&impl->params);
841 if (res != HC_SUCCESS) {
842 return res;
843 }
844 res = CalSharedSecret(&impl->params);
845 if (res != HC_SUCCESS) {
846 return res;
847 }
848 res = VerifyKcfDataPeer(impl, false);
849 if (res != HC_SUCCESS) {
850 return res;
851 }
852 res = CalKcfDataSelf(impl, false);
853 if (res != HC_SUCCESS) {
854 return res;
855 }
856 return CalSessionKey(impl);
857 }
858
DlSpekeServerFinishRspBuildEvent(DlSpekeParams * params,CJson ** outputData)859 static int32_t DlSpekeServerFinishRspBuildEvent(DlSpekeParams *params, CJson **outputData)
860 {
861 CJson *json = CreateJson();
862 if (json == NULL) {
863 LOGE("Create json failed.");
864 return HC_ERR_JSON_CREATE;
865 }
866 if (AddIntToJson(json, FIELD_EVENT, SERVER_FINISH_RSP_EVENT) != HC_SUCCESS) {
867 LOGE("Add event to out json fail.");
868 FreeJson(json);
869 return HC_ERR_JSON_ADD;
870 }
871 if (AddByteToJson(json, FIELD_KCF_DATA_SERVER, params->kcfDataSelf.val,
872 params->kcfDataSelf.length) != HC_SUCCESS) {
873 LOGE("Add kcfDataS to out json fail.");
874 FreeJson(json);
875 return HC_ERR_JSON_ADD;
876 }
877 *outputData = json;
878 return HC_SUCCESS;
879 }
880
DlSpekeServerFinishRsp(DlSpekeProtocol * impl,const CJson * inputData,CJson ** outputData)881 static int32_t DlSpekeServerFinishRsp(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData)
882 {
883 int32_t res = DlSpekeServerFinishRspParseEvent(inputData, &impl->params);
884 if (res != HC_SUCCESS) {
885 return res;
886 }
887 res = DlSpekeServerFinishRspProcEvent(impl);
888 if (res != HC_SUCCESS) {
889 return res;
890 }
891 return DlSpekeServerFinishRspBuildEvent(&impl->params, outputData);
892 }
893
DlSpekeClientFinishParseEvent(const CJson * inputData,DlSpekeParams * params)894 static int32_t DlSpekeClientFinishParseEvent(const CJson *inputData, DlSpekeParams *params)
895 {
896 return GetKcfDataPeerFromInput(inputData, params, true);
897 }
898
DlSpekeClientFinishProcEvent(DlSpekeProtocol * impl)899 static int32_t DlSpekeClientFinishProcEvent(DlSpekeProtocol *impl)
900 {
901 int32_t res = VerifyKcfDataPeer(impl, true);
902 if (res != HC_SUCCESS) {
903 return res;
904 }
905 return CalSessionKey(impl);
906 }
907
DlSpekeClientFinish(DlSpekeProtocol * impl,const CJson * inputData,CJson ** outputData)908 static int32_t DlSpekeClientFinish(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData)
909 {
910 (void)outputData;
911 int32_t res = DlSpekeClientFinishParseEvent(inputData, &impl->params);
912 if (res != HC_SUCCESS) {
913 return res;
914 }
915 return DlSpekeClientFinishProcEvent(impl);
916 }
917
ReturnError(int32_t errorCode,CJson ** outputData)918 static void ReturnError(int32_t errorCode, CJson **outputData)
919 {
920 (void)errorCode;
921 (void)outputData;
922 return;
923 }
924
NotifyPeerError(int32_t errorCode,CJson ** outputData)925 static void NotifyPeerError(int32_t errorCode, CJson **outputData)
926 {
927 CJson *json = CreateJson();
928 if (json == NULL) {
929 LOGE("Create json failed.");
930 return;
931 }
932 if (AddIntToJson(json, FIELD_ERR_CODE, errorCode) != HC_SUCCESS) {
933 LOGE("Add error code to json failed.");
934 FreeJson(json);
935 return;
936 }
937 if (AddIntToJson(json, FIELD_EVENT, FAIL_EVENT) != HC_SUCCESS) {
938 LOGE("Add fail event to json failed.");
939 FreeJson(json);
940 return;
941 }
942 *outputData = json;
943 return;
944 }
945
ThrowException(DlSpekeProtocol * impl,const CJson * inputData,CJson ** outputData)946 static int32_t ThrowException(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData)
947 {
948 (void)impl;
949 (void)outputData;
950 int32_t peerErrorCode = HC_ERR_PEER_ERROR;
951 (void)GetIntFromJson(inputData, FIELD_ERR_CODE, &peerErrorCode);
952 LOGE("An exception occurred in the peer protocol. [Code]: %" LOG_PUB "d", peerErrorCode);
953 return peerErrorCode;
954 }
955
956 static const ProtocolStateNode STATE_MACHINE[] = {
957 { CREATE_AS_CLIENT_STATE, START_AUTH_EVENT, DlSpekeClientStartReq, ReturnError, CLIENT_REQ_STATE },
958 { CREATE_AS_SERVER_STATE, CLEINT_START_REQ_EVENT, DlSpekeServerStartRsp, NotifyPeerError, SERVER_RSP_STATE },
959 { CLIENT_REQ_STATE, SERVER_START_RSP_EVENT, DlSpekeClientFinishReq, NotifyPeerError, CLIENT_FINISH_REQ_STATE },
960 { CLIENT_REQ_STATE, FAIL_EVENT, ThrowException, ReturnError, FAIL_STATE },
961 { SERVER_RSP_STATE, CLEINT_FINISH_REQ_EVENT, DlSpekeServerFinishRsp, NotifyPeerError, SERVER_FINISH_STATE },
962 { SERVER_RSP_STATE, FAIL_EVENT, ThrowException, ReturnError, FAIL_STATE },
963 { CLIENT_FINISH_REQ_STATE, SERVER_FINISH_RSP_EVENT, DlSpekeClientFinish, NotifyPeerError, CLIENT_FINISH_STATE },
964 { CLIENT_FINISH_REQ_STATE, FAIL_EVENT, ThrowException, ReturnError, FAIL_STATE },
965 };
966
DecodeEvent(const CJson * receviedMsg)967 static int32_t DecodeEvent(const CJson *receviedMsg)
968 {
969 if (receviedMsg == NULL) {
970 return START_AUTH_EVENT;
971 }
972 int32_t event;
973 if (GetIntFromJson(receviedMsg, FIELD_EVENT, &event) != HC_SUCCESS) {
974 LOGE("Get event from receviedMsg fail.");
975 return UNKNOWN_EVENT;
976 }
977 if (START_AUTH_EVENT <= event && event <= UNKNOWN_EVENT) {
978 return event;
979 }
980 LOGE("Unknown event.");
981 return UNKNOWN_EVENT;
982 }
983
DlSpekeProtocolSwitchState(BaseProtocol * self,const CJson * receviedMsg,CJson ** returnSendMsg)984 static int32_t DlSpekeProtocolSwitchState(BaseProtocol *self, const CJson *receviedMsg, CJson **returnSendMsg)
985 {
986 int32_t eventType = DecodeEvent(receviedMsg);
987 for (uint32_t i = 0; i < sizeof(STATE_MACHINE) / sizeof(STATE_MACHINE[0]); i++) {
988 if ((STATE_MACHINE[i].curState == self->curState) && (STATE_MACHINE[i].eventType == eventType)) {
989 int32_t res = STATE_MACHINE[i].stateProcessFunc((DlSpekeProtocol *)self, receviedMsg, returnSendMsg);
990 if (res != HC_SUCCESS) {
991 STATE_MACHINE[i].exceptionHandleFunc(res, returnSendMsg);
992 self->curState = self->failState;
993 return res;
994 }
995 self->curState = STATE_MACHINE[i].nextState;
996 LOGI("event: %" LOG_PUB "d, curState: %" LOG_PUB "d, nextState: %" LOG_PUB "d", eventType, self->curState,
997 STATE_MACHINE[i].nextState);
998 return HC_SUCCESS;
999 }
1000 }
1001 LOGI("Unsupported event type. Ignore process. [Event]: %" LOG_PUB "d, [CurState]: %" LOG_PUB "d. ",
1002 eventType, self->curState);
1003 return HC_SUCCESS;
1004 }
1005
StartDlSpekeProtocol(BaseProtocol * self,CJson ** returnSendMsg)1006 static int32_t StartDlSpekeProtocol(BaseProtocol *self, CJson **returnSendMsg)
1007 {
1008 if ((self == NULL) || (returnSendMsg == NULL)) {
1009 LOGE("invalid params.");
1010 return HC_ERR_INVALID_PARAMS;
1011 }
1012 if ((self->curState == self->finishState) || (self->curState == self->failState)) {
1013 LOGE("The protocol has ended, and the state switch cannot continue!");
1014 return HC_ERR_UNSUPPORTED_OPCODE;
1015 }
1016 return DlSpekeProtocolSwitchState(self, NULL, returnSendMsg);
1017 }
1018
ProcessDlSpekeProtocol(BaseProtocol * self,const CJson * receviedMsg,CJson ** returnSendMsg)1019 static int32_t ProcessDlSpekeProtocol(BaseProtocol *self, const CJson *receviedMsg, CJson **returnSendMsg)
1020 {
1021 if ((self == NULL) || (receviedMsg == NULL) || (returnSendMsg == NULL)) {
1022 LOGE("invalid params.");
1023 return HC_ERR_INVALID_PARAMS;
1024 }
1025 if ((self->curState == self->finishState) || (self->curState == self->failState)) {
1026 LOGE("The protocol has ended, and the state switch cannot continue!");
1027 return HC_ERR_UNSUPPORTED_OPCODE;
1028 }
1029 return DlSpekeProtocolSwitchState(self, receviedMsg, returnSendMsg);
1030 }
1031
SetDlSpekePsk(BaseProtocol * self,const Uint8Buff * psk)1032 static int32_t SetDlSpekePsk(BaseProtocol *self, const Uint8Buff *psk)
1033 {
1034 if ((self == NULL) || (psk == NULL) || (psk->val == NULL) || (psk->length == 0)) {
1035 LOGE("invalid params.");
1036 return HC_ERR_INVALID_PARAMS;
1037 }
1038 DlSpekeProtocol *impl = (DlSpekeProtocol *)self;
1039 if (DeepCopyUint8Buff(psk, &impl->params.psk) != HC_SUCCESS) {
1040 LOGE("copy psk fail.");
1041 return HC_ERR_ALLOC_MEMORY;
1042 }
1043 LOGI("set psk success.");
1044 return HC_SUCCESS;
1045 }
1046
SetDlSpekeSelfProtectedMsg(BaseProtocol * self,const Uint8Buff * selfMsg)1047 static int32_t SetDlSpekeSelfProtectedMsg(BaseProtocol *self, const Uint8Buff *selfMsg)
1048 {
1049 if ((self == NULL) || !IsUint8BuffValid(selfMsg, PROTECTED_MSG_MAX_LEN)) {
1050 LOGE("invalid params.");
1051 return HC_ERR_INVALID_PARAMS;
1052 }
1053 if (DeepCopyUint8Buff(selfMsg, &self->protectedMsg.selfMsg) != HC_SUCCESS) {
1054 LOGE("copy protected self msg fail.");
1055 return HC_ERR_ALLOC_MEMORY;
1056 }
1057 return HC_SUCCESS;
1058 }
1059
SetDlSpekePeerProtectedMsg(BaseProtocol * self,const Uint8Buff * peerMsg)1060 static int32_t SetDlSpekePeerProtectedMsg(BaseProtocol *self, const Uint8Buff *peerMsg)
1061 {
1062 if ((self == NULL) || !IsUint8BuffValid(peerMsg, PROTECTED_MSG_MAX_LEN)) {
1063 LOGE("Error occurs, params invalid.");
1064 return HC_ERR_INVALID_PARAMS;
1065 }
1066 if (DeepCopyUint8Buff(peerMsg, &self->protectedMsg.peerMsg) != HC_SUCCESS) {
1067 LOGE("Copy protected peer msg fail.");
1068 return HC_ERR_ALLOC_MEMORY;
1069 }
1070 return HC_SUCCESS;
1071 }
1072
GetDlSpekeSessionKey(BaseProtocol * self,Uint8Buff * returnSessionKey)1073 static int32_t GetDlSpekeSessionKey(BaseProtocol *self, Uint8Buff *returnSessionKey)
1074 {
1075 if ((self == NULL) || (returnSessionKey == NULL)) {
1076 LOGE("Null pointer.");
1077 return HC_ERR_INVALID_PARAMS;
1078 }
1079 if (self->curState != self->finishState) {
1080 LOGE("The protocol has not been completed, unable to obtain the protocol result!");
1081 return HC_ERR_UNSUPPORTED_OPCODE;
1082 }
1083 return DeepCopyUint8Buff(&self->sessionKey, returnSessionKey);
1084 }
1085
DestroyDlSpekeProtocol(BaseProtocol * self)1086 static void DestroyDlSpekeProtocol(BaseProtocol *self)
1087 {
1088 if (self == NULL) {
1089 LOGD("self is null.");
1090 return;
1091 }
1092 DlSpekeProtocol *dlSpekeProtocol = (DlSpekeProtocol *)self;
1093 ClearFreeUint8Buff(&dlSpekeProtocol->base.protectedMsg.selfMsg);
1094 ClearFreeUint8Buff(&dlSpekeProtocol->base.protectedMsg.peerMsg);
1095 ClearFreeUint8Buff(&dlSpekeProtocol->base.sessionKey);
1096 ClearFreeUint8Buff(&dlSpekeProtocol->params.psk);
1097 ClearFreeUint8Buff(&dlSpekeProtocol->params.salt);
1098 ClearFreeUint8Buff(&dlSpekeProtocol->params.base);
1099 ClearFreeUint8Buff(&dlSpekeProtocol->params.eskSelf);
1100 ClearFreeUint8Buff(&dlSpekeProtocol->params.epkSelf);
1101 ClearFreeUint8Buff(&dlSpekeProtocol->params.epkPeer);
1102 ClearFreeUint8Buff(&dlSpekeProtocol->params.authIdSelf);
1103 ClearFreeUint8Buff(&dlSpekeProtocol->params.authIdPeer);
1104 ClearFreeUint8Buff(&dlSpekeProtocol->params.kcfDataSelf);
1105 ClearFreeUint8Buff(&dlSpekeProtocol->params.kcfDataPeer);
1106 ClearFreeUint8Buff(&dlSpekeProtocol->params.sharedSecret);
1107 HcFree(dlSpekeProtocol);
1108 }
1109
BuildDlSpekeProtocolObj(const DlSpekeInitParams * params,bool isClient,DlSpekeProtocol * instance)1110 static int32_t BuildDlSpekeProtocolObj(const DlSpekeInitParams *params, bool isClient, DlSpekeProtocol *instance)
1111 {
1112 if (DeepCopyUint8Buff(¶ms->authId, &instance->params.authIdSelf) != HC_SUCCESS) {
1113 LOGE("Failed to set self authId!");
1114 return HC_ERR_ALLOC_MEMORY;
1115 }
1116 instance->params.osAccountId = params->osAccountId;
1117 instance->params.primeMod = (DlSpekePrimeMod)params->primeMod;
1118 instance->base.name = PROTOCOL_TYPE_DL_SPEKE;
1119 instance->base.beginState = isClient ? CREATE_AS_CLIENT_STATE : CREATE_AS_SERVER_STATE;
1120 instance->base.finishState = isClient ? CLIENT_FINISH_STATE : SERVER_FINISH_STATE;
1121 instance->base.failState = FAIL_STATE;
1122 instance->base.curState = instance->base.beginState;
1123 instance->base.start = StartDlSpekeProtocol;
1124 instance->base.process = ProcessDlSpekeProtocol;
1125 instance->base.setPsk = SetDlSpekePsk;
1126 instance->base.setSelfProtectedMsg = SetDlSpekeSelfProtectedMsg;
1127 instance->base.setPeerProtectedMsg = SetDlSpekePeerProtectedMsg;
1128 instance->base.getSessionKey = GetDlSpekeSessionKey;
1129 instance->base.destroy = DestroyDlSpekeProtocol;
1130 return HC_SUCCESS;
1131 }
1132
CreateDlSpekeProtocol(const void * baseParams,bool isClient,BaseProtocol ** returnObj)1133 int32_t CreateDlSpekeProtocol(const void *baseParams, bool isClient, BaseProtocol **returnObj)
1134 {
1135 if (baseParams == NULL || returnObj == NULL) {
1136 LOGE("null input params!");
1137 return HC_ERR_INVALID_PARAMS;
1138 }
1139 const DlSpekeInitParams *params = (const DlSpekeInitParams *)baseParams;
1140 if (!IsUint8BuffValid(¶ms->authId, DL_SPEKE_AUTH_ID_MAX_LEN)) {
1141 LOGE("Invalid authId!");
1142 return HC_ERR_INVALID_PARAMS;
1143 }
1144 DlSpekeProtocol *instance = (DlSpekeProtocol *)HcMalloc(sizeof(DlSpekeProtocol), 0);
1145 if (instance == NULL) {
1146 LOGE("Failed to alloc memory for protocol instance!");
1147 return HC_ERR_ALLOC_MEMORY;
1148 }
1149 int32_t res = BuildDlSpekeProtocolObj(params, isClient, instance);
1150 if (res != HC_SUCCESS) {
1151 DestroyDlSpekeProtocol((BaseProtocol *)instance);
1152 return res;
1153 }
1154 *returnObj = (BaseProtocol *)instance;
1155 return HC_SUCCESS;
1156 }
1157