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("create json failed.");
111 return HC_ERR_JSON_CREATE;
112 }
113 if (AddIntToJson(json, FIELD_EVENT, CLEINT_START_REQ_EVENT) != HC_SUCCESS) {
114 LOGE("add eventName to json fail.");
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("add authIdC to json fail.");
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: %u.", authIdPeerStrLen);
145 return HC_ERR_CONVERT_FAILED;
146 }
147 if (InitUint8Buff(¶ms->authIdPeer, authIdPeerStrLen) != HC_SUCCESS) {
148 LOGE("allocate authIdPeer memory fail.");
149 return HC_ERR_ALLOC_MEMORY;
150 }
151 if (HexStringToByte(authIdPeerStr, params->authIdPeer.val, params->authIdPeer.length) != HC_SUCCESS) {
152 LOGE("HexStringToByte for authIdPeerStr 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 fail.");
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 memory fail.");
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 ?
218 (params->primeMod & DL_SPEKE_PRIME_MOD_256) : (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: %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: %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: %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: %x, Invalid epkPeer length: %u.", params->primeMod, params->epkPeer.length);
284 return HC_ERR_INVALID_LEN;
285 }
286
DlSpekeCalBase(DlSpekeParams * params,Uint8Buff * secret)287 static int32_t DlSpekeCalBase(DlSpekeParams *params, Uint8Buff *secret)
288 {
289 if (InitUint8Buff(¶ms->base, params->innerKeyLen) != HC_SUCCESS) {
290 LOGE("Failed to init base!");
291 return HC_ERR_ALLOC_MEMORY;
292 }
293 uint8_t expVal[DL_SPEKE_EXP_LEN] = { 2 };
294 Uint8Buff exp = { expVal, DL_SPEKE_EXP_LEN };
295 params->largePrimeNumHex = (params->innerKeyLen == DL_SPEKE_PRIME_SMALL_LEN) ?
296 LARGE_PRIME_NUMBER_HEX_256 : LARGE_PRIME_NUMBER_HEX_384;
297 int32_t res = GetLoaderInstance()->bigNumExpMod(secret, &exp, params->largePrimeNumHex, ¶ms->base);
298 if (res != HC_SUCCESS) {
299 LOGE("BigNumExpMod for base failed, res: %x.", res);
300 }
301 return res;
302 }
303
DlSpekeCalEskSelf(DlSpekeParams * params)304 static int32_t DlSpekeCalEskSelf(DlSpekeParams *params)
305 {
306 if (InitUint8Buff(¶ms->eskSelf, params->eskSelf.length) != HC_SUCCESS) {
307 LOGE("Failed to init eskSelf!");
308 return HC_ERR_ALLOC_MEMORY;
309 }
310 int res = GetLoaderInstance()->generateRandom(&(params->eskSelf));
311 if (res != HC_SUCCESS) {
312 LOGE("GenerateRandom for eskSelf failed, res: %x.", res);
313 }
314 return res;
315 }
316
DlSpekeCalEpkSelf(DlSpekeParams * params)317 static int32_t DlSpekeCalEpkSelf(DlSpekeParams *params)
318 {
319 if (InitUint8Buff(¶ms->epkSelf, params->innerKeyLen) != HC_SUCCESS) {
320 LOGE("Failed to init epkSelf!");
321 return HC_ERR_ALLOC_MEMORY;
322 }
323 int32_t res = GetLoaderInstance()->bigNumExpMod(¶ms->base, &(params->eskSelf),
324 params->largePrimeNumHex, &(params->epkSelf));
325 if (res != HC_SUCCESS) {
326 LOGE("BigNumExpMod for epkSelf failed, res: %x.", res);
327 }
328 return res;
329 }
330
IsEpkPeerLenValid(DlSpekeParams * params)331 static bool IsEpkPeerLenValid(DlSpekeParams *params)
332 {
333 if ((params->epkPeer.length == DL_SPEKE_PRIME_LEN) &&
334 (((uint32_t)params->primeMod & DL_SPEKE_PRIME_MOD_384) != 0)) {
335 return true;
336 }
337 if ((params->epkPeer.length == DL_SPEKE_PRIME_SMALL_LEN) &&
338 (((uint32_t)params->primeMod & DL_SPEKE_PRIME_MOD_256) != 0)) {
339 return true;
340 }
341 LOGE("Invalid epkPeer length: %u.", params->epkPeer.length);
342 return false;
343 }
344
CheckEpkPeerValid(DlSpekeParams * params)345 static int32_t CheckEpkPeerValid(DlSpekeParams *params)
346 {
347 if (!IsEpkPeerLenValid(params)) {
348 return HC_ERR_INVALID_LEN;
349 }
350 if (!GetLoaderInstance()->checkDlPublicKey(¶ms->epkPeer, params->largePrimeNumHex)) {
351 LOGE("Check EC_SPEKE publicKey fail.");
352 return HC_ERR_BAD_MESSAGE;
353 }
354 return HC_SUCCESS;
355 }
356
CalTmpSharedSecret(DlSpekeParams * params,Uint8Buff * tmpSharedSecret)357 static int32_t CalTmpSharedSecret(DlSpekeParams *params, Uint8Buff *tmpSharedSecret)
358 {
359 int32_t res = GetLoaderInstance()->bigNumExpMod(&(params->epkPeer), &(params->eskSelf),
360 params->largePrimeNumHex, tmpSharedSecret);
361 if (res != HC_SUCCESS) {
362 LOGE("Cal tmpSharedSecret failed, res: %x", res);
363 }
364 return res;
365 }
366
CalSidSelf(DlSpekeParams * params,Uint8Buff * sidSelf)367 static int32_t CalSidSelf(DlSpekeParams *params, Uint8Buff *sidSelf)
368 {
369 uint32_t sidSelfMsgLen = params->authIdSelf.length + params->innerKeyLen;
370 Uint8Buff sidSelfMsg = { NULL, 0 };
371 if (InitUint8Buff(&sidSelfMsg, sidSelfMsgLen) != HC_SUCCESS) {
372 LOGE("allocate sidSelfMsg memory fail.");
373 return HC_ERR_ALLOC_MEMORY;
374 }
375 if (memcpy_s(sidSelfMsg.val, sidSelfMsg.length, params->authIdSelf.val, params->authIdSelf.length) != EOK) {
376 LOGE("Memcpy for authIdSelf failed.");
377 ClearFreeUint8Buff(&sidSelfMsg);
378 return HC_ERR_MEMORY_COPY;
379 }
380 if (memcpy_s(sidSelfMsg.val + params->authIdSelf.length, sidSelfMsg.length - params->authIdSelf.length,
381 params->epkSelf.val, params->innerKeyLen) != EOK) { // only need x-coordinate
382 LOGE("Memcpy for epkSelf_X failed.");
383 ClearFreeUint8Buff(&sidSelfMsg);
384 return HC_ERR_MEMORY_COPY;
385 }
386 int32_t res = GetLoaderInstance()->sha256(&sidSelfMsg, sidSelf);
387 ClearFreeUint8Buff(&sidSelfMsg);
388 if (res != HC_SUCCESS) {
389 LOGE("Sha256 for sidSelf failed, res: %x", res);
390 return res;
391 }
392 return HC_SUCCESS;
393 }
394
CalSidPeer(DlSpekeParams * params,Uint8Buff * sidPeer)395 static int32_t CalSidPeer(DlSpekeParams *params, Uint8Buff *sidPeer)
396 {
397 uint32_t sidPeerMsgLen = params->authIdPeer.length + params->innerKeyLen;
398 Uint8Buff sidPeerMsg = { NULL, 0 };
399 if (InitUint8Buff(&sidPeerMsg, sidPeerMsgLen) != HC_SUCCESS) {
400 LOGE("allocate sidPeerMsg memory fail.");
401 return HC_ERR_ALLOC_MEMORY;
402 }
403 if (memcpy_s(sidPeerMsg.val, sidPeerMsg.length, params->authIdPeer.val, params->authIdPeer.length) != EOK) {
404 LOGE("Memcpy for authIdPeer failed.");
405 ClearFreeUint8Buff(&sidPeerMsg);
406 return HC_ERR_MEMORY_COPY;
407 }
408 if (memcpy_s(sidPeerMsg.val + params->authIdPeer.length, sidPeerMsg.length - params->authIdPeer.length,
409 params->epkPeer.val, params->innerKeyLen) != EOK) { // only need x-coordinate
410 LOGE("Memcpy for epkPeer_X failed.");
411 ClearFreeUint8Buff(&sidPeerMsg);
412 return HC_ERR_MEMORY_COPY;
413 }
414 int32_t res = GetLoaderInstance()->sha256(&sidPeerMsg, sidPeer);
415 ClearFreeUint8Buff(&sidPeerMsg);
416 if (res != HC_SUCCESS) {
417 LOGE("Sha256 for sidPeer failed, res: %x", res);
418 return res;
419 }
420 return HC_SUCCESS;
421 }
422
CalSid(DlSpekeParams * params,Uint8Buff * sid)423 static int32_t CalSid(DlSpekeParams *params, Uint8Buff *sid)
424 {
425 uint8_t sidSelfVal[SHA256_LEN] = { 0 };
426 uint8_t sidPeerVal[SHA256_LEN] = { 0 };
427 Uint8Buff sidSelf = { sidSelfVal, SHA256_LEN };
428 Uint8Buff sidPeer = { sidPeerVal, SHA256_LEN };
429 int32_t res = CalSidSelf(params, &sidSelf);
430 if (res != HC_SUCCESS) {
431 return res;
432 }
433 res = CalSidPeer(params, &sidPeer);
434 if (res != HC_SUCCESS) {
435 return res;
436 }
437 Uint8Buff *maxSid = &sidSelf;
438 Uint8Buff *minSid = &sidPeer;
439 if (GetLoaderInstance()->bigNumCompare(&sidSelf, &sidPeer) > 0) {
440 maxSid = &sidPeer;
441 minSid = &sidSelf;
442 }
443 if (memcpy_s(sid->val, sid->length, maxSid->val, maxSid->length) != EOK) {
444 LOGE("Memcpy for maxSid failed.");
445 return HC_ERR_MEMORY_COPY;
446 }
447 if (memcpy_s(sid->val + maxSid->length, sid->length - maxSid->length, minSid->val, minSid->length) != EOK) {
448 LOGE("Memcpy for minSid failed.");
449 return HC_ERR_MEMORY_COPY;
450 }
451 return HC_SUCCESS;
452 }
453
CombineSharedSecretMsg(DlSpekeParams * params,const Uint8Buff * tmpSharedSecret,const Uint8Buff * sid,Uint8Buff * sharedSecretMsg)454 static int32_t CombineSharedSecretMsg(DlSpekeParams *params, const Uint8Buff *tmpSharedSecret, const Uint8Buff *sid,
455 Uint8Buff *sharedSecretMsg)
456 {
457 uint32_t usedLen = 0;
458 if (memcpy_s(sharedSecretMsg->val, sharedSecretMsg->length, sid->val, sid->length) != EOK) {
459 LOGE("Memcpy for sidHex failed.");
460 return HC_ERR_MEMORY_COPY;
461 }
462 usedLen += sid->length;
463 // Only need x-coordinate
464 if (memcpy_s(sharedSecretMsg->val + usedLen, sharedSecretMsg->length - usedLen,
465 tmpSharedSecret->val, params->innerKeyLen) != EOK) {
466 LOGE("Memcpy for tmpSharedSecret failed.");
467 return HC_ERR_MEMORY_COPY;
468 }
469 usedLen += params->innerKeyLen;
470 if (memcpy_s(sharedSecretMsg->val + usedLen, sharedSecretMsg->length - usedLen,
471 SHARED_SECRET_DERIVED_FACTOR, HcStrlen(SHARED_SECRET_DERIVED_FACTOR)) != EOK) {
472 LOGE("Memcpy for sharedSecret derived factor failed.");
473 return HC_ERR_MEMORY_COPY;
474 }
475 return HC_SUCCESS;
476 }
477
GenerateSharedSecretMsg(DlSpekeParams * params,Uint8Buff * sharedSecretMsg)478 static int32_t GenerateSharedSecretMsg(DlSpekeParams *params, Uint8Buff *sharedSecretMsg)
479 {
480 Uint8Buff tmpSharedSecret = { NULL, 0 };
481 if (InitUint8Buff(&tmpSharedSecret, params->innerKeyLen) != HC_SUCCESS) {
482 LOGE("allocate p memory fail.");
483 return HC_ERR_ALLOC_MEMORY;
484 }
485 int32_t res = CalTmpSharedSecret(params, &tmpSharedSecret);
486 if (res != HC_SUCCESS) {
487 ClearFreeUint8Buff(&tmpSharedSecret);
488 return res;
489 }
490 // sid is composed of client sid and server sid, so need twice SHA256_LEN
491 uint8_t sidVal[SHA256_LEN * 2] = { 0 };
492 Uint8Buff sid = { sidVal, SHA256_LEN * 2 };
493 res = CalSid(params, &sid);
494 if (res != HC_SUCCESS) {
495 ClearFreeUint8Buff(&tmpSharedSecret);
496 return res;
497 }
498 res = CombineSharedSecretMsg(params, &tmpSharedSecret, &sid, sharedSecretMsg);
499 (void)memset_s(sid.val, sid.length, 0, sid.length);
500 ClearFreeUint8Buff(&tmpSharedSecret);
501 return res;
502 }
503
CalSharedSecret(DlSpekeParams * params)504 static int32_t CalSharedSecret(DlSpekeParams *params)
505 {
506 uint32_t sharedSecretMsgLen = SHA256_LEN * 2 + params->innerKeyLen + HcStrlen(SHARED_SECRET_DERIVED_FACTOR);
507 Uint8Buff sharedSecretMsg = { NULL, 0 };
508 if (InitUint8Buff(&sharedSecretMsg, sharedSecretMsgLen) != HC_SUCCESS) {
509 LOGE("allocate sharedSecretMsg memory fail.");
510 return HC_ERR_ALLOC_MEMORY;
511 }
512 int32_t res = GenerateSharedSecretMsg(params, &sharedSecretMsg);
513 if (res != HC_SUCCESS) {
514 ClearFreeUint8Buff(&sharedSecretMsg);
515 return res;
516 }
517 if (InitUint8Buff(¶ms->sharedSecret, SHA256_LEN)) {
518 LOGE("allocate sharedSecret memory fail.");
519 ClearFreeUint8Buff(&sharedSecretMsg);
520 return HC_ERR_ALLOC_MEMORY;
521 }
522 res = GetLoaderInstance()->sha256(&sharedSecretMsg, ¶ms->sharedSecret);
523 ClearFreeUint8Buff(&sharedSecretMsg);
524 if (res != HC_SUCCESS) {
525 LOGE("Sha256 for sharedSecret failed, res: %x", res);
526 }
527 return res;
528 }
529
CombineProtectedMsg(DlSpekeProtocol * impl,bool isVerify,Uint8Buff * kcfDataMsg,uint32_t usedLen)530 static int32_t CombineProtectedMsg(DlSpekeProtocol *impl, bool isVerify, Uint8Buff *kcfDataMsg, uint32_t usedLen)
531 {
532 Uint8Buff *firstProtectedMsg = isVerify ? &(impl->base.protectedMsg.peerMsg) : &(impl->base.protectedMsg.selfMsg);
533 Uint8Buff *secondProtectedMsg = isVerify ? &(impl->base.protectedMsg.selfMsg) : &(impl->base.protectedMsg.peerMsg);
534 if (IsUint8BuffValid(firstProtectedMsg, PROTECTED_MSG_MAX_LEN)) {
535 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
536 firstProtectedMsg->val, firstProtectedMsg->length) != EOK) {
537 LOGE("Memcpy firstProtectedMsg failed.");
538 return HC_ERR_MEMORY_COPY;
539 }
540 usedLen += firstProtectedMsg->length;
541 }
542 if (IsUint8BuffValid(secondProtectedMsg, PROTECTED_MSG_MAX_LEN)) {
543 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
544 secondProtectedMsg->val, secondProtectedMsg->length) != EOK) {
545 LOGE("Memcpy secondProtectedMsg failed.");
546 return HC_ERR_MEMORY_COPY;
547 }
548 }
549 return HC_SUCCESS;
550 }
551
GenerateKcfDataMsg(DlSpekeProtocol * impl,bool isClient,bool isVerify,Uint8Buff * kcfDataMsg)552 static int32_t GenerateKcfDataMsg(DlSpekeProtocol *impl, bool isClient, bool isVerify, Uint8Buff *kcfDataMsg)
553 {
554 DlSpekeParams *params = &impl->params;
555 const uint8_t *kcfCode = ((isClient && !isVerify) || (!isClient && isVerify)) ? KCF_CODE_CLIENT : KCF_CODE_SERVER;
556 if (memcpy_s(kcfDataMsg->val, kcfDataMsg->length, kcfCode, DL_SPEKE_KCF_CODE_LEN) != HC_SUCCESS) {
557 LOGE("Memcpy for kcfCode failed.");
558 return HC_ERR_MEMORY_COPY;
559 }
560 uint32_t usedLen = DL_SPEKE_KCF_CODE_LEN;
561 Uint8Buff *epkClient = isClient ? ¶ms->epkSelf : ¶ms->epkPeer;
562 Uint8Buff *epkServer = isClient ? ¶ms->epkPeer : ¶ms->epkSelf;
563 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
564 epkClient->val, params->innerKeyLen) != EOK) { // Only the x-coordinate of epk is required
565 LOGE("Memcpy for epkClient failed.");
566 return HC_ERR_MEMORY_COPY;
567 }
568 usedLen += params->innerKeyLen;
569 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
570 epkServer->val, params->innerKeyLen) != EOK) { // Only the x-coordinate of epk is required
571 LOGE("Memcpy for epkServer failed.");
572 return HC_ERR_MEMORY_COPY;
573 }
574 usedLen += params->innerKeyLen;
575 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
576 params->sharedSecret.val, params->sharedSecret.length) != EOK) {
577 LOGE("Memcpy for sharedSecret failed.");
578 return HC_ERR_MEMORY_COPY;
579 }
580 usedLen += params->sharedSecret.length;
581 if (memcpy_s(kcfDataMsg->val + usedLen, kcfDataMsg->length - usedLen,
582 params->base.val, params->innerKeyLen) != EOK) { // Only the x-coordinate of base is required
583 LOGE("Memcpy for base_X failed.");
584 return HC_ERR_MEMORY_COPY;
585 }
586 usedLen += params->innerKeyLen;
587 return CombineProtectedMsg(impl, isVerify, kcfDataMsg, usedLen);
588 }
589
CalKcfDataSelf(DlSpekeProtocol * impl,bool isClient)590 static int32_t CalKcfDataSelf(DlSpekeProtocol *impl, bool isClient)
591 {
592 uint32_t kcfDataMsgLen = DL_SPEKE_KCF_CODE_LEN + impl->params.innerKeyLen + impl->params.innerKeyLen +
593 SHA256_LEN + impl->params.innerKeyLen + impl->base.protectedMsg.selfMsg.length +
594 impl->base.protectedMsg.peerMsg.length;
595 Uint8Buff kcfDataMsg = { NULL, 0 };
596 if (InitUint8Buff(&kcfDataMsg, kcfDataMsgLen) != HC_SUCCESS) {
597 LOGE("allocate kcfDataMsg memory fail.");
598 return HC_ERR_ALLOC_MEMORY;
599 }
600 int32_t res = GenerateKcfDataMsg(impl, isClient, false, &kcfDataMsg);
601 if (res != HC_SUCCESS) {
602 ClearFreeUint8Buff(&kcfDataMsg);
603 return res;
604 }
605 if (InitUint8Buff(&impl->params.kcfDataSelf, SHA256_LEN) != HC_SUCCESS) {
606 LOGE("allocate kcfDataSelf memory fail.");
607 ClearFreeUint8Buff(&kcfDataMsg);
608 return HC_ERR_ALLOC_MEMORY;
609 }
610 res = GetLoaderInstance()->sha256(&kcfDataMsg, &impl->params.kcfDataSelf);
611 ClearFreeUint8Buff(&kcfDataMsg);
612 if (res != HC_SUCCESS) {
613 LOGE("Sha256 for kcfDataSelf failed, res: %x", res);
614 }
615 return res;
616 }
617
VerifyKcfDataPeer(DlSpekeProtocol * impl,bool isClient)618 static int32_t VerifyKcfDataPeer(DlSpekeProtocol *impl, bool isClient)
619 {
620 uint32_t kcfDataMsgLen = DL_SPEKE_KCF_CODE_LEN + impl->params.innerKeyLen + impl->params.innerKeyLen +
621 SHA256_LEN + impl->params.innerKeyLen + impl->base.protectedMsg.selfMsg.length +
622 impl->base.protectedMsg.peerMsg.length;
623 Uint8Buff kcfDataMsg = { NULL, 0 };
624 if (InitUint8Buff(&kcfDataMsg, kcfDataMsgLen) != HC_SUCCESS) {
625 LOGE("allocate kcfDataMsg memory fail.");
626 return HC_ERR_ALLOC_MEMORY;
627 }
628 int32_t res = GenerateKcfDataMsg(impl, isClient, true, &kcfDataMsg);
629 if (res != HC_SUCCESS) {
630 ClearFreeUint8Buff(&kcfDataMsg);
631 return res;
632 }
633 uint8_t kcfDataPeerVal[SHA256_LEN] = { 0 };
634 Uint8Buff kcfDataPeer = { kcfDataPeerVal, SHA256_LEN };
635 res = GetLoaderInstance()->sha256(&kcfDataMsg, &kcfDataPeer);
636 ClearFreeUint8Buff(&kcfDataMsg);
637 if (res != HC_SUCCESS) {
638 LOGE("Sha256 for kcfDataPeer failed, res: %x", res);
639 return res;
640 }
641 if (memcmp(kcfDataPeer.val, impl->params.kcfDataPeer.val, kcfDataPeer.length) != 0) {
642 LOGE("verify kcfData fail.");
643 (void)memset_s(kcfDataPeer.val, kcfDataPeer.length, 0, kcfDataPeer.length);
644 return PROOF_MISMATCH;
645 }
646 return HC_SUCCESS;
647 }
648
CalSessionKey(DlSpekeProtocol * impl)649 static int32_t CalSessionKey(DlSpekeProtocol *impl)
650 {
651 if (InitUint8Buff(&impl->base.sessionKey, DL_SPEKE_SESSION_KEY_LEN) != HC_SUCCESS) {
652 LOGE("allocate sessionKey memory fail.");
653 return HC_ERR_ALLOC_MEMORY;
654 }
655 Uint8Buff keyInfo = { (uint8_t *)HICHAIN_SPEKE_SESSIONKEY_INFO, HcStrlen(HICHAIN_SPEKE_SESSIONKEY_INFO) };
656 KeyParams keyParams = {
657 { impl->params.sharedSecret.val, impl->params.sharedSecret.length, false },
658 false,
659 impl->params.osAccountId
660 };
661 int32_t res = GetLoaderInstance()->computeHkdf(&keyParams, &impl->params.salt, &keyInfo,
662 &impl->base.sessionKey);
663 ClearFreeUint8Buff(&impl->params.salt);
664 ClearFreeUint8Buff(&impl->params.sharedSecret);
665 if (res != HC_SUCCESS) {
666 LOGE("ComputeHkdf for sessionKey failed, res: %x", res);
667 }
668 return res;
669 }
670
DlSpekeServerStartRspProcEvent(DlSpekeProtocol * impl)671 static int32_t DlSpekeServerStartRspProcEvent(DlSpekeProtocol *impl)
672 {
673 int32_t res = CalSalt(&impl->params);
674 if (res != HC_SUCCESS) {
675 return res;
676 }
677 uint8_t secretVal[DL_SPEKE_SECRET_LEN] = { 0 };
678 Uint8Buff secret = { secretVal, DL_SPEKE_SECRET_LEN };
679 res = CalSecret(&impl->params, &secret);
680 if (res != HC_SUCCESS) {
681 return res;
682 }
683 res = DlSpekeCalBase(&impl->params, &secret);
684 if (res != HC_SUCCESS) {
685 return res;
686 }
687 res = DlSpekeCalEskSelf(&impl->params);
688 if (res != HC_SUCCESS) {
689 return res;
690 }
691 return DlSpekeCalEpkSelf(&impl->params);
692 }
693
DlSpekeServerStartRspBuildEvent(const DlSpekeParams * params,CJson ** outputData)694 static int32_t DlSpekeServerStartRspBuildEvent(const DlSpekeParams *params, CJson **outputData)
695 {
696 CJson *json = CreateJson();
697 if (json == NULL) {
698 LOGE("create json failed.");
699 return HC_ERR_JSON_CREATE;
700 }
701 if (AddIntToJson(json, FIELD_EVENT, SERVER_START_RSP_EVENT) != HC_SUCCESS) {
702 LOGE("add eventName to json fail.");
703 FreeJson(json);
704 return HC_ERR_JSON_ADD;
705 }
706 if (AddByteToJson(json, FIELD_SALT, params->salt.val, params->salt.length) != HC_SUCCESS) {
707 LOGE("add salt to json fail.");
708 FreeJson(json);
709 return HC_ERR_JSON_ADD;
710 }
711 if (AddByteToJson(json, FIELD_EPK_SERVER, params->epkSelf.val, params->epkSelf.length) != HC_SUCCESS) {
712 LOGE("add epkS to json fail.");
713 FreeJson(json);
714 return HC_ERR_JSON_ADD;
715 }
716 if (AddByteToJson(json, FIELD_AUTH_ID_SERVER, params->authIdSelf.val,
717 params->authIdSelf.length) != HC_SUCCESS) {
718 LOGE("add authIdS to json fail.");
719 FreeJson(json);
720 return HC_ERR_JSON_ADD;
721 }
722 *outputData = json;
723 return HC_SUCCESS;
724 }
725
DlSpekeServerStartRsp(DlSpekeProtocol * impl,const CJson * inputData,CJson ** outputData)726 static int32_t DlSpekeServerStartRsp(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData)
727 {
728 int32_t res = DlSpekeServerStartRspParseEvent(inputData, &impl->params);
729 if (res != HC_SUCCESS) {
730 return res;
731 }
732 res = DlSpekeServerStartRspProcEvent(impl);
733 if (res != HC_SUCCESS) {
734 return res;
735 }
736 return DlSpekeServerStartRspBuildEvent(&impl->params, outputData);
737 }
738
DlSpekeClientFinishReqParseEvent(const CJson * inputData,DlSpekeParams * params)739 static int32_t DlSpekeClientFinishReqParseEvent(const CJson *inputData, DlSpekeParams *params)
740 {
741 int32_t res = GetSaltFromInput(inputData, params);
742 if (res != HC_SUCCESS) {
743 return res;
744 }
745 res = GetEpkPeerFromInput(inputData, params, true);
746 if (res != HC_SUCCESS) {
747 return res;
748 }
749 return GetAuthIdPeerFromInput(inputData, params, true);
750 }
751
DlSpekeClientFinishReqProcEvent(DlSpekeProtocol * impl)752 static int32_t DlSpekeClientFinishReqProcEvent(DlSpekeProtocol *impl)
753 {
754 uint8_t secretVal[DL_SPEKE_SECRET_LEN] = { 0 };
755 Uint8Buff secret = { secretVal, DL_SPEKE_SECRET_LEN };
756 int32_t res = CalSecret(&impl->params, &secret);
757 if (res != HC_SUCCESS) {
758 return res;
759 }
760 res = DlSpekeCalBase(&impl->params, &secret);
761 (void)memset_s(secret.val, secret.length, 0, secret.length);
762 if (res != HC_SUCCESS) {
763 return res;
764 }
765 res = DlSpekeCalEskSelf(&impl->params);
766 if (res != HC_SUCCESS) {
767 return res;
768 }
769 res = DlSpekeCalEpkSelf(&impl->params);
770 if (res != HC_SUCCESS) {
771 return res;
772 }
773 res = CheckEpkPeerValid(&impl->params);
774 if (res != HC_SUCCESS) {
775 return res;
776 }
777 res = CalSharedSecret(&impl->params);
778 if (res != HC_SUCCESS) {
779 return res;
780 }
781 return CalKcfDataSelf(impl, true);
782 }
783
DlSpekeClientFinishReqBuildEvent(DlSpekeParams * params,CJson ** outputData)784 static int32_t DlSpekeClientFinishReqBuildEvent(DlSpekeParams *params, CJson **outputData)
785 {
786 CJson *json = CreateJson();
787 if (json == NULL) {
788 LOGE("create json failed.");
789 return HC_ERR_JSON_CREATE;
790 }
791 if (AddIntToJson(json, FIELD_EVENT, CLEINT_FINISH_REQ_EVENT) != HC_SUCCESS) {
792 LOGE("add eventName to json fail.");
793 FreeJson(json);
794 return HC_ERR_JSON_ADD;
795 }
796 if (AddByteToJson(json, FIELD_EPK_CLIENT, params->epkSelf.val, params->epkSelf.length) != HC_SUCCESS) {
797 LOGE("add epkC to json fail.");
798 FreeJson(json);
799 return HC_ERR_JSON_ADD;
800 }
801 if (AddByteToJson(json, FIELD_KCF_DATA_CLIENT, params->kcfDataSelf.val,
802 params->kcfDataSelf.length) != HC_SUCCESS) {
803 LOGE("add kcfDataC to json fail.");
804 FreeJson(json);
805 return HC_ERR_JSON_ADD;
806 }
807 *outputData = json;
808 return HC_SUCCESS;
809 }
810
DlSpekeClientFinishReq(DlSpekeProtocol * impl,const CJson * inputData,CJson ** outputData)811 static int32_t DlSpekeClientFinishReq(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData)
812 {
813 int32_t res = DlSpekeClientFinishReqParseEvent(inputData, &impl->params);
814 if (res != HC_SUCCESS) {
815 return res;
816 }
817 res = SetSelfKeyLenByEpkPeerAndMod(&impl->params);
818 if (res != HC_SUCCESS) {
819 return res;
820 }
821 res = DlSpekeClientFinishReqProcEvent(impl);
822 if (res != HC_SUCCESS) {
823 return res;
824 }
825 return DlSpekeClientFinishReqBuildEvent(&impl->params, outputData);
826 }
827
DlSpekeServerFinishRspParseEvent(const CJson * inputData,DlSpekeParams * params)828 static int32_t DlSpekeServerFinishRspParseEvent(const CJson *inputData, DlSpekeParams *params)
829 {
830 int32_t res = GetEpkPeerFromInput(inputData, params, false);
831 if (res != HC_SUCCESS) {
832 return res;
833 }
834 return GetKcfDataPeerFromInput(inputData, params, false);
835 }
836
DlSpekeServerFinishRspProcEvent(DlSpekeProtocol * impl)837 static int32_t DlSpekeServerFinishRspProcEvent(DlSpekeProtocol *impl)
838 {
839 int32_t res = CheckEpkPeerValid(&impl->params);
840 if (res != HC_SUCCESS) {
841 return res;
842 }
843 res = CalSharedSecret(&impl->params);
844 if (res != HC_SUCCESS) {
845 return res;
846 }
847 res = VerifyKcfDataPeer(impl, false);
848 if (res != HC_SUCCESS) {
849 return res;
850 }
851 res = CalKcfDataSelf(impl, false);
852 if (res != HC_SUCCESS) {
853 return res;
854 }
855 return CalSessionKey(impl);
856 }
857
DlSpekeServerFinishRspBuildEvent(DlSpekeParams * params,CJson ** outputData)858 static int32_t DlSpekeServerFinishRspBuildEvent(DlSpekeParams *params, CJson **outputData)
859 {
860 CJson *json = CreateJson();
861 if (json == NULL) {
862 LOGE("create json failed.");
863 return HC_ERR_JSON_CREATE;
864 }
865 if (AddIntToJson(json, FIELD_EVENT, SERVER_FINISH_RSP_EVENT) != HC_SUCCESS) {
866 LOGE("add eventName to json fail.");
867 FreeJson(json);
868 return HC_ERR_JSON_ADD;
869 }
870 if (AddByteToJson(json, FIELD_KCF_DATA_SERVER, params->kcfDataSelf.val,
871 params->kcfDataSelf.length) != HC_SUCCESS) {
872 LOGE("add kcfDataS to json fail.");
873 FreeJson(json);
874 return HC_ERR_JSON_ADD;
875 }
876 *outputData = json;
877 return HC_SUCCESS;
878 }
879
DlSpekeServerFinishRsp(DlSpekeProtocol * impl,const CJson * inputData,CJson ** outputData)880 static int32_t DlSpekeServerFinishRsp(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData)
881 {
882 int32_t res = DlSpekeServerFinishRspParseEvent(inputData, &impl->params);
883 if (res != HC_SUCCESS) {
884 return res;
885 }
886 res = DlSpekeServerFinishRspProcEvent(impl);
887 if (res != HC_SUCCESS) {
888 return res;
889 }
890 return DlSpekeServerFinishRspBuildEvent(&impl->params, outputData);
891 }
892
DlSpekeClientFinishParseEvent(const CJson * inputData,DlSpekeParams * params)893 static int32_t DlSpekeClientFinishParseEvent(const CJson *inputData, DlSpekeParams *params)
894 {
895 return GetKcfDataPeerFromInput(inputData, params, true);
896 }
897
DlSpekeClientFinishProcEvent(DlSpekeProtocol * impl)898 static int32_t DlSpekeClientFinishProcEvent(DlSpekeProtocol *impl)
899 {
900 int32_t res = VerifyKcfDataPeer(impl, true);
901 if (res != HC_SUCCESS) {
902 return res;
903 }
904 return CalSessionKey(impl);
905 }
906
DlSpekeClientFinish(DlSpekeProtocol * impl,const CJson * inputData,CJson ** outputData)907 static int32_t DlSpekeClientFinish(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData)
908 {
909 (void)outputData;
910 int32_t res = DlSpekeClientFinishParseEvent(inputData, &impl->params);
911 if (res != HC_SUCCESS) {
912 return res;
913 }
914 return DlSpekeClientFinishProcEvent(impl);
915 }
916
ReturnError(int32_t errorCode,CJson ** outputData)917 static void ReturnError(int32_t errorCode, CJson **outputData)
918 {
919 (void)errorCode;
920 (void)outputData;
921 return;
922 }
923
NotifyPeerError(int32_t errorCode,CJson ** outputData)924 static void NotifyPeerError(int32_t errorCode, CJson **outputData)
925 {
926 CJson *json = CreateJson();
927 if (json == NULL) {
928 LOGE("create json failed.");
929 return;
930 }
931 if (AddIntToJson(json, FIELD_EVENT, FAIL_EVENT) != HC_SUCCESS) {
932 LOGE("add eventName to json fail.");
933 FreeJson(json);
934 return;
935 }
936 if (AddIntToJson(json, FIELD_ERR_CODE, errorCode) != HC_SUCCESS) {
937 LOGE("add errorCode to json fail.");
938 FreeJson(json);
939 return;
940 }
941 *outputData = json;
942 return;
943 }
944
ThrowException(DlSpekeProtocol * impl,const CJson * inputData,CJson ** outputData)945 static int32_t ThrowException(DlSpekeProtocol *impl, const CJson *inputData, CJson **outputData)
946 {
947 (void)impl;
948 (void)outputData;
949 int32_t peerErrorCode = HC_ERR_PEER_ERROR;
950 (void)GetIntFromJson(inputData, FIELD_ERR_CODE, &peerErrorCode);
951 LOGE("An exception occurred in the peer protocol. [Code]: %d", peerErrorCode);
952 return peerErrorCode;
953 }
954
955 static const ProtocolStateNode STATE_MACHINE[] = {
956 { CREATE_AS_CLIENT_STATE, START_AUTH_EVENT, DlSpekeClientStartReq, ReturnError, CLIENT_REQ_STATE },
957 { CREATE_AS_SERVER_STATE, CLEINT_START_REQ_EVENT, DlSpekeServerStartRsp, NotifyPeerError, SERVER_RSP_STATE },
958 { CLIENT_REQ_STATE, SERVER_START_RSP_EVENT, DlSpekeClientFinishReq, NotifyPeerError, CLIENT_FINISH_REQ_STATE },
959 { CLIENT_REQ_STATE, FAIL_EVENT, ThrowException, ReturnError, FAIL_STATE },
960 { SERVER_RSP_STATE, CLEINT_FINISH_REQ_EVENT, DlSpekeServerFinishRsp, NotifyPeerError, SERVER_FINISH_STATE },
961 { SERVER_RSP_STATE, FAIL_EVENT, ThrowException, ReturnError, FAIL_STATE },
962 { CLIENT_FINISH_REQ_STATE, SERVER_FINISH_RSP_EVENT, DlSpekeClientFinish, NotifyPeerError, CLIENT_FINISH_STATE },
963 { CLIENT_FINISH_REQ_STATE, FAIL_EVENT, ThrowException, ReturnError, FAIL_STATE },
964 };
965
DecodeEvent(const CJson * receviedMsg)966 static int32_t DecodeEvent(const CJson *receviedMsg)
967 {
968 if (receviedMsg == NULL) {
969 return START_AUTH_EVENT;
970 }
971 int32_t event;
972 if (GetIntFromJson(receviedMsg, FIELD_EVENT, &event) != HC_SUCCESS) {
973 LOGE("get event from receviedMsg fail.");
974 return UNKNOWN_EVENT;
975 }
976 if (START_AUTH_EVENT <= event && event <= UNKNOWN_EVENT) {
977 return event;
978 }
979 LOGE("unknown event.");
980 return UNKNOWN_EVENT;
981 }
982
DlSpekeProtocolSwitchState(BaseProtocol * self,const CJson * receviedMsg,CJson ** returnSendMsg)983 static int32_t DlSpekeProtocolSwitchState(BaseProtocol *self, const CJson *receviedMsg, CJson **returnSendMsg)
984 {
985 int32_t eventType = DecodeEvent(receviedMsg);
986 for (uint32_t i = 0; i < sizeof(STATE_MACHINE) / sizeof(STATE_MACHINE[0]); i++) {
987 if ((STATE_MACHINE[i].curState == self->curState) && (STATE_MACHINE[i].eventType == eventType)) {
988 int32_t res = STATE_MACHINE[i].stateProcessFunc((DlSpekeProtocol *)self, receviedMsg, returnSendMsg);
989 if (res != HC_SUCCESS) {
990 STATE_MACHINE[i].exceptionHandleFunc(res, returnSendMsg);
991 self->curState = self->failState;
992 return res;
993 }
994 LOGI("event: %d, curState: %d, nextState: %d", eventType, self->curState, STATE_MACHINE[i].nextState);
995 self->curState = STATE_MACHINE[i].nextState;
996 return HC_SUCCESS;
997 }
998 }
999 LOGI("Unsupported event type. Ignore process. [Event]: %d, [CurState]: %d", eventType, self->curState);
1000 return HC_SUCCESS;
1001 }
1002
StartDlSpekeProtocol(BaseProtocol * self,CJson ** returnSendMsg)1003 static int32_t StartDlSpekeProtocol(BaseProtocol *self, CJson **returnSendMsg)
1004 {
1005 if ((self == NULL) || (returnSendMsg == NULL)) {
1006 LOGE("invalid params.");
1007 return HC_ERR_INVALID_PARAMS;
1008 }
1009 if ((self->curState == self->finishState) || (self->curState == self->failState)) {
1010 LOGE("The protocol has ended, and the state switch cannot continue!");
1011 return HC_ERR_UNSUPPORTED_OPCODE;
1012 }
1013 return DlSpekeProtocolSwitchState(self, NULL, returnSendMsg);
1014 }
1015
ProcessDlSpekeProtocol(BaseProtocol * self,const CJson * receviedMsg,CJson ** returnSendMsg)1016 static int32_t ProcessDlSpekeProtocol(BaseProtocol *self, const CJson *receviedMsg, CJson **returnSendMsg)
1017 {
1018 if ((self == NULL) || (receviedMsg == NULL) || (returnSendMsg == NULL)) {
1019 LOGE("invalid params.");
1020 return HC_ERR_INVALID_PARAMS;
1021 }
1022 if ((self->curState == self->finishState) || (self->curState == self->failState)) {
1023 LOGE("The protocol has ended, and the state switch cannot continue!");
1024 return HC_ERR_UNSUPPORTED_OPCODE;
1025 }
1026 return DlSpekeProtocolSwitchState(self, receviedMsg, returnSendMsg);
1027 }
1028
SetDlSpekePsk(BaseProtocol * self,const Uint8Buff * psk)1029 static int32_t SetDlSpekePsk(BaseProtocol *self, const Uint8Buff *psk)
1030 {
1031 if ((self == NULL) || (psk == NULL) || (psk->val == NULL) || (psk->length == 0)) {
1032 LOGE("invalid params.");
1033 return HC_ERR_INVALID_PARAMS;
1034 }
1035 DlSpekeProtocol *impl = (DlSpekeProtocol *)self;
1036 if (DeepCopyUint8Buff(psk, &impl->params.psk) != HC_SUCCESS) {
1037 LOGE("copy psk fail.");
1038 return HC_ERR_ALLOC_MEMORY;
1039 }
1040 LOGI("set psk success.");
1041 return HC_SUCCESS;
1042 }
1043
SetDlSpekeSelfProtectedMsg(BaseProtocol * self,const Uint8Buff * selfMsg)1044 static int32_t SetDlSpekeSelfProtectedMsg(BaseProtocol *self, const Uint8Buff *selfMsg)
1045 {
1046 if ((self == NULL) || !IsUint8BuffValid(selfMsg, PROTECTED_MSG_MAX_LEN)) {
1047 LOGE("invalid params.");
1048 return HC_ERR_INVALID_PARAMS;
1049 }
1050 if (DeepCopyUint8Buff(selfMsg, &self->protectedMsg.selfMsg) != HC_SUCCESS) {
1051 LOGE("copy protected self msg fail.");
1052 return HC_ERR_ALLOC_MEMORY;
1053 }
1054 return HC_SUCCESS;
1055 }
1056
SetDlSpekePeerProtectedMsg(BaseProtocol * self,const Uint8Buff * peerMsg)1057 static int32_t SetDlSpekePeerProtectedMsg(BaseProtocol *self, const Uint8Buff *peerMsg)
1058 {
1059 if ((self == NULL) || !IsUint8BuffValid(peerMsg, PROTECTED_MSG_MAX_LEN)) {
1060 LOGE("invalid params.");
1061 return HC_ERR_INVALID_PARAMS;
1062 }
1063 if (DeepCopyUint8Buff(peerMsg, &self->protectedMsg.peerMsg) != HC_SUCCESS) {
1064 LOGE("copy protected peer msg fail.");
1065 return HC_ERR_ALLOC_MEMORY;
1066 }
1067 return HC_SUCCESS;
1068 }
1069
GetDlSpekeSessionKey(BaseProtocol * self,Uint8Buff * returnSessionKey)1070 static int32_t GetDlSpekeSessionKey(BaseProtocol *self, Uint8Buff *returnSessionKey)
1071 {
1072 if ((self == NULL) || (returnSessionKey == NULL)) {
1073 LOGE("invalid params.");
1074 return HC_ERR_INVALID_PARAMS;
1075 }
1076 if (self->curState != self->finishState) {
1077 LOGE("The protocol has not been completed, unable to obtain the protocol result!");
1078 return HC_ERR_UNSUPPORTED_OPCODE;
1079 }
1080 return DeepCopyUint8Buff(&self->sessionKey, returnSessionKey);
1081 }
1082
DestroyDlSpekeProtocol(BaseProtocol * self)1083 static void DestroyDlSpekeProtocol(BaseProtocol *self)
1084 {
1085 if (self == NULL) {
1086 LOGD("self is null.");
1087 return;
1088 }
1089 DlSpekeProtocol *impl = (DlSpekeProtocol *)self;
1090 ClearFreeUint8Buff(&impl->base.protectedMsg.selfMsg);
1091 ClearFreeUint8Buff(&impl->base.protectedMsg.peerMsg);
1092 ClearFreeUint8Buff(&impl->base.sessionKey);
1093 ClearFreeUint8Buff(&impl->params.psk);
1094 ClearFreeUint8Buff(&impl->params.salt);
1095 ClearFreeUint8Buff(&impl->params.base);
1096 ClearFreeUint8Buff(&impl->params.eskSelf);
1097 ClearFreeUint8Buff(&impl->params.epkSelf);
1098 ClearFreeUint8Buff(&impl->params.epkPeer);
1099 ClearFreeUint8Buff(&impl->params.authIdSelf);
1100 ClearFreeUint8Buff(&impl->params.authIdPeer);
1101 ClearFreeUint8Buff(&impl->params.kcfDataSelf);
1102 ClearFreeUint8Buff(&impl->params.kcfDataPeer);
1103 ClearFreeUint8Buff(&impl->params.sharedSecret);
1104 HcFree(impl);
1105 }
1106
BuildDlSpekeProtocolObj(const DlSpekeInitParams * params,bool isClient,DlSpekeProtocol * instance)1107 static int32_t BuildDlSpekeProtocolObj(const DlSpekeInitParams *params, bool isClient, DlSpekeProtocol *instance)
1108 {
1109 if (DeepCopyUint8Buff(¶ms->authId, &instance->params.authIdSelf) != HC_SUCCESS) {
1110 LOGE("Failed to set self authId!");
1111 return HC_ERR_ALLOC_MEMORY;
1112 }
1113 instance->params.osAccountId = params->osAccountId;
1114 instance->params.primeMod = params->primeMod;
1115 instance->base.name = PROTOCOL_TYPE_DL_SPEKE;
1116 instance->base.beginState = isClient ? CREATE_AS_CLIENT_STATE : CREATE_AS_SERVER_STATE;
1117 instance->base.finishState = isClient ? CLIENT_FINISH_STATE : SERVER_FINISH_STATE;
1118 instance->base.failState = FAIL_STATE;
1119 instance->base.curState = instance->base.beginState;
1120 instance->base.start = StartDlSpekeProtocol;
1121 instance->base.process = ProcessDlSpekeProtocol;
1122 instance->base.setPsk = SetDlSpekePsk;
1123 instance->base.setSelfProtectedMsg = SetDlSpekeSelfProtectedMsg;
1124 instance->base.setPeerProtectedMsg = SetDlSpekePeerProtectedMsg;
1125 instance->base.getSessionKey = GetDlSpekeSessionKey;
1126 instance->base.destroy = DestroyDlSpekeProtocol;
1127 return HC_SUCCESS;
1128 }
1129
CreateDlSpekeProtocol(const void * baseParams,bool isClient,BaseProtocol ** returnObj)1130 int32_t CreateDlSpekeProtocol(const void *baseParams, bool isClient, BaseProtocol **returnObj)
1131 {
1132 if (baseParams == NULL || returnObj == NULL) {
1133 LOGE("null input params!");
1134 return HC_ERR_INVALID_PARAMS;
1135 }
1136 const DlSpekeInitParams *params = (const DlSpekeInitParams *)baseParams;
1137 if (!IsUint8BuffValid(¶ms->authId, DL_SPEKE_AUTH_ID_MAX_LEN)) {
1138 LOGE("Invalid authId!");
1139 return HC_ERR_INVALID_PARAMS;
1140 }
1141 DlSpekeProtocol *instance = (DlSpekeProtocol *)HcMalloc(sizeof(DlSpekeProtocol), 0);
1142 if (instance == NULL) {
1143 LOGE("Failed to alloc memory for protocol instance!");
1144 return HC_ERR_ALLOC_MEMORY;
1145 }
1146 int32_t res = BuildDlSpekeProtocolObj(params, isClient, instance);
1147 if (res != HC_SUCCESS) {
1148 DestroyDlSpekeProtocol((BaseProtocol *)instance);
1149 return res;
1150 }
1151 *returnObj = (BaseProtocol *)instance;
1152 return HC_SUCCESS;
1153 }
1154