Uniot Core
0.9.0
Loading...
Searching...
No Matches
Credentials.h
Go to the documentation of this file.
1/*
2 * This is a part of the Uniot project.
3 * Copyright (C) 2016-2020 Uniot <contact@uniot.io>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
28
29#pragma once
30
31#include <Arduino.h>
32#include <CBORStorage.h>
33#include <Crypto.h>
34#include <Ed25519.h>
35#include <ICOSESigner.h>
36#include <RNG.h>
37
38#if defined(ESP8266)
39 #include <user_interface.h>
40#elif defined(ESP32)
41 #include <esp_wifi.h>
42 #include <esp_system.h>
43#endif
44
45namespace uniot {
61class Credentials : public CBORStorage, public ICOSESigner {
62 public:
63 static constexpr size_t PRIVATE_KEY_SIZE = 32;
64 static constexpr size_t PUBLIC_KEY_SIZE = 32;
65 static constexpr size_t SIGNATURE_SIZE = 64;
66
73 Credentials() : CBORStorage("credentials.cbor"), mOnwerChanged(false) {
74 mCreatorId = UNIOT_CREATOR_ID;
75 mDeviceId = _calcDeviceId();
77
78 if (mPrivateKey.size() != PRIVATE_KEY_SIZE) {
79 _generatePrivateKey();
81 }
82 _derivePublicKey();
83 }
84
93 virtual bool store() override {
94 object().put("account", mOwnerId.c_str());
95 object().put("private_key", mPrivateKey.raw(), mPrivateKey.size());
96 return CBORStorage::store();
97 }
98
107 virtual bool restore() override {
108 if (CBORStorage::restore()) {
109 mOwnerId = object().getString("account");
110 mPrivateKey = object().getBytes("private_key");
111
112 // Every use of the key reads exactly PRIVATE_KEY_SIZE bytes from it, so a stored key of
113 // any other length is dropped rather than read past. The constructor then generates a
114 // new one, which gives the device a new identity: the platform sees a new public key.
115 if (mPrivateKey.size() && mPrivateKey.size() != PRIVATE_KEY_SIZE) {
116 UNIOT_LOG_ERROR("stored private key is %u bytes, expected %u, discarding it",
117 mPrivateKey.size(), PRIVATE_KEY_SIZE);
118 mPrivateKey.clean();
119 }
120 return true;
121 }
122 UNIOT_LOG_ERROR("%s", "credentials not restored");
123 return false;
124 }
125
131 void setOwnerId(const String &id) {
132 if (mOwnerId != id) {
133 mOnwerChanged = true;
134 }
135 mOwnerId = id;
136 }
137
143 const String &getOwnerId() const {
144 return mOwnerId;
145 }
146
147 bool isOwnerChanged() const {
148 return mOnwerChanged;
149 }
150
152 mOnwerChanged = false;
153 }
154
160 const String &getCreatorId() const {
161 return mCreatorId;
162 }
163
169 const String &getDeviceId() const {
170 return mDeviceId;
171 }
172
178 const String &getPublicKey() const {
179 return mPublicKey;
180 }
181
189 uint32_t getShortDeviceId() const {
190#if defined(ESP8266)
191 return ESP.getChipId();
192#elif defined(ESP32)
193 uint64_t mac = ESP.getEfuseMac();
194 return (uint32_t)(mac >> 32); // Use the higher 32 bits of the MAC as the Chip ID
195#endif
196 }
197
203 virtual Bytes keyId() const override {
204 return mPublicKeyRaw;
205 }
206
215 virtual Bytes sign(const Bytes &data) const override {
216 if (mPrivateKey.size() != PRIVATE_KEY_SIZE || mPublicKeyRaw.size() != PUBLIC_KEY_SIZE) {
217 UNIOT_LOG_ERROR("%s", "cannot sign without a valid key pair");
218 return Bytes();
219 }
220
221 // The public key is the one derived at startup. Deriving it again here would repeat the
222 // scalar multiplication that is the expensive half of Ed25519, on every signature.
223 uint8_t signature[SIGNATURE_SIZE];
224 Ed25519::sign(signature, mPrivateKey.raw(), mPublicKeyRaw.raw(), data.raw(), data.size());
225 return Bytes(signature, sizeof(signature));
226 }
227
233 virtual COSEAlgorithm signerAlgorithm() const override {
234 return COSEAlgorithm::EdDSA;
235 }
236
237 private:
245 String _calcDeviceId() {
246 uint8_t mac[6];
247 char macStr[13] = {0};
248#if defined(ESP8266)
249 wifi_get_macaddr(STATION_IF, mac);
250#elif defined(ESP32)
251 esp_read_mac(mac, ESP_MAC_WIFI_STA);
252#endif
253 for (uint8_t i = 0; i < 6; i++)
254 sprintf(macStr + i * 2, "%02x", mac[i]);
255
256 return String(macStr);
257 }
258
264 void _generatePrivateKey() {
265 // Initialize the random number generator with device-specific entropy
266 RNG.begin(String("uniot::entropy::" + mCreatorId + "::" + mDeviceId).c_str());
267
268 uint8_t privateKey[PRIVATE_KEY_SIZE];
269 Ed25519::generatePrivateKey(privateKey);
270 mPrivateKey = Bytes(privateKey, sizeof(privateKey));
271 }
272
278 void _derivePublicKey() {
279 if (mPrivateKey.size() != PRIVATE_KEY_SIZE) {
280 UNIOT_LOG_ERROR("%s", "no valid private key to derive from");
281 return;
282 }
283
284 uint8_t publicKey[PUBLIC_KEY_SIZE];
285 Ed25519::derivePublicKey(publicKey, mPrivateKey.raw());
286 mPublicKeyRaw = Bytes(publicKey, sizeof(publicKey));
287 mPublicKey = mPublicKeyRaw.toHexString();
288 }
289
290 String mOwnerId;
291 String mCreatorId;
292 String mDeviceId;
293 Bytes mPrivateKey;
294 Bytes mPublicKeyRaw;
295 String mPublicKey;
296
297 bool mOnwerChanged;
298};
299
300} // namespace uniot
Definition Bytes.h:38
const uint8_t * raw() const
Gets a const pointer to the raw byte array.
Definition Bytes.h:270
size_t size() const
Gets the size of the byte array.
Definition Bytes.h:343
Bytes getBytes(int key) const
Get binary data at a specific integer key.
Definition CBORObject.h:471
CBORObject & put(int key, int value)
Put an integer value at a specific integer key.
Definition CBORObject.h:180
String getString(int key) const
Get a string value at a specific integer key.
Definition CBORObject.h:429
virtual bool restore() override
Restore the CBOR object from the filesystem.
Definition CBORStorage.h:102
virtual bool store() override
Store the CBOR object to the filesystem.
Definition CBORStorage.h:74
CBORStorage(const String &path)
Constructs a new CBORStorage object.
Definition CBORStorage.h:46
CBORObject & object()
Get access to the underlying CBORObject.
Definition CBORStorage.h:60
const String & getCreatorId() const
Gets the creator ID.
Definition Credentials.h:160
const String & getPublicKey() const
Gets the device's public key as a hexadecimal string.
Definition Credentials.h:178
const String & getDeviceId() const
Gets the unique device ID.
Definition Credentials.h:169
static constexpr size_t SIGNATURE_SIZE
Size of an Ed25519 signature.
Definition Credentials.h:65
Credentials()
Constructor that initializes device credentials.
Definition Credentials.h:73
const String & getOwnerId() const
Gets the current owner ID.
Definition Credentials.h:143
static constexpr size_t PRIVATE_KEY_SIZE
Size of an Ed25519 private key.
Definition Credentials.h:63
uint32_t getShortDeviceId() const
Gets a shorter unique identifier for the device.
Definition Credentials.h:189
virtual Bytes sign(const Bytes &data) const override
Implements ICOSESigner interface to sign data.
Definition Credentials.h:215
void resetOwnerChanged()
Definition Credentials.h:151
static constexpr size_t PUBLIC_KEY_SIZE
Size of an Ed25519 public key.
Definition Credentials.h:64
bool isOwnerChanged() const
Definition Credentials.h:147
virtual bool store() override
Stores credentials to persistent storage.
Definition Credentials.h:93
virtual bool restore() override
Restores credentials from persistent storage.
Definition Credentials.h:107
virtual Bytes keyId() const override
Implements ICOSESigner interface to provide key ID.
Definition Credentials.h:203
virtual COSEAlgorithm signerAlgorithm() const override
Implements ICOSESigner interface to specify the signing algorithm.
Definition Credentials.h:233
void setOwnerId(const String &id)
Sets the owner ID of the device.
Definition Credentials.h:131
Interface for CBOR Object Signing and Encryption (COSE) signing operations.
Definition ICOSESigner.h:35
#define UNIOT_LOG_ERROR(...)
Log an ERROR level message Used for critical errors that may prevent normal operation....
Definition Logger.h:273
COSEAlgorithm
Cryptographic algorithm identifiers for COSE.
Definition COSE.h:84
Contains all classes and functions related to the Uniot Core.