1 /*
2    Copyright (c) 2022 Eriptic Technologies. See the COPYRIGHT
3    file at the top-level directory of this distribution.
4 
5    Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6    http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7    <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8    option. This file may not be copied, modified, or distributed
9    except according to those terms.
10 */
11 #include <inttypes.h>
12 
13 #include "edhoc.h"
14 #include "oscore.h"
15 
16 #include "common/oscore_edhoc_error.h"
17 #include "common/print_util.h"
18 
19 #ifdef OSCORE_NVM_SUPPORT
nvm_write_ssn(const struct nvm_key_t * nvm_key,uint64_t ssn)20 enum err WEAK nvm_write_ssn(const struct nvm_key_t *nvm_key, uint64_t ssn)
21 {
22 	PRINT_MSG(
23 		"The nvm_write_ssn() function MUST be overwritten by user!!!\n");
24 	return not_implemented;
25 }
26 
nvm_read_ssn(const struct nvm_key_t * nvm_key,uint64_t * ssn)27 enum err WEAK nvm_read_ssn(const struct nvm_key_t *nvm_key, uint64_t *ssn)
28 {
29 	PRINT_MSG(
30 		"The nvm_read_ssn() function MUST be overwritten by user!!!\n");
31 	if (NULL != ssn) {
32 		*ssn = 0;
33 	}
34 	return not_implemented;
35 }
36 
ssn_store_in_nvm(const struct nvm_key_t * nvm_key,uint64_t ssn,bool echo_sync_in_progress)37 enum err ssn_store_in_nvm(const struct nvm_key_t *nvm_key, uint64_t ssn,
38 			  bool echo_sync_in_progress)
39 {
40 	bool cyclic_write = (0 == ssn % K_SSN_NVM_STORE_INTERVAL);
41 
42 	/* While the device is still in the ECHO synchronization mode (after device reboot or other context reinitialization)
43 	   SSN has to be written immediately, in case of uncontrolled reboot before first cyclic write happens. */
44 	if (cyclic_write || echo_sync_in_progress) {
45 		TRY(nvm_write_ssn(nvm_key, ssn));
46 	}
47 	return ok;
48 }
49 #endif
50 
ssn_init(const struct nvm_key_t * nvm_key,uint64_t * ssn,bool is_context_fresh)51 enum err ssn_init(const struct nvm_key_t *nvm_key, uint64_t *ssn,
52 		  bool is_context_fresh)
53 {
54 	if ((NULL == nvm_key) || (NULL == ssn)) {
55 		return wrong_parameter;
56 	}
57 
58 	if (is_context_fresh) {
59 		*ssn = 0;
60 		PRINTF("Security context is fresh, SSN initialized to %" PRIu64
61 		       "\n",
62 		       *ssn);
63 	} else {
64 		#ifdef OSCORE_NVM_SUPPORT
65 			TRY(nvm_read_ssn(nvm_key, ssn));
66 			*ssn += K_SSN_NVM_STORE_INTERVAL + F_NVM_MAX_WRITE_FAILURE;
67 			PRINTF("SSN initialized from NMV. SSN = %" PRIu64 "\n", *ssn);
68 		#else
69 			PRINT_MSG("OSCORE_NVM_SUPPORT flag must be defined for handling non-fresh (stored) contexts.");
70 			return not_implemented;
71 		#endif
72 	}
73 	return ok;
74 }