DeepCover Embedded Security in IoT: Public-key Secured Data Paths
Dependencies: MaximInterface
The MAXREFDES155# is an internet-of-things (IoT) embedded-security reference design, built to authenticate and control a sensing node using elliptic-curve-based public-key cryptography with control and notification from a web server.
The hardware includes an ARM® mbed™ shield and attached sensor endpoint. The shield contains a DS2476 DeepCover® ECDSA/SHA-2 coprocessor, Wifi communication, LCD push-button controls, and status LEDs. The sensor endpoint is attached to the shield using a 300mm cable and contains a DS28C36 DeepCover ECDSA/SHA-2 authenticator, IR-thermal sensor, and aiming laser for the IR sensor. The MAXREFDES155# is equipped with a standard Arduino® form-factor shield connector for immediate testing using an mbed board such as the MAX32600MBED#. The combination of these two devices represent an IoT device. Communication to the web server is accomplished with the shield Wifi circuitry. Communication from the shield to the attached sensor module is accomplished over I2C . The sensor module represents an IoT endpoint that generates small data with a requirement for message authenticity/integrity and secure on/off operational control.
The design is hierarchical with each mbed platform and shield communicating data from the sensor node to a web server that maintains a centralized log and dispatches notifications as necessary. The simplicity of this design enables rapid integration into any star-topology IoT network to provide security with the low overhead and cost provided by the ECDSA-P256 asymmetric-key and SHA-256 symmetric-key algorithms.
More information about the MAXREFDES155# is available on the Maxim Integrated website.
NormalOperationWindow.cpp
- Committer:
- IanBenzMaxim
- Date:
- 2017-02-24
- Revision:
- 0:33d4e66780c0
- Child:
- 3:d2799d8497c0
File content as of revision 0:33d4e66780c0:
/******************************************************************************* * Copyright (C) 2017 Maxim Integrated Products, Inc., All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL MAXIM INTEGRATED BE LIABLE FOR ANY CLAIM, DAMAGES * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Except as contained in this notice, the name of Maxim Integrated * Products, Inc. shall not be used except as stated in the Maxim Integrated * Products, Inc. Branding Policy. * * The mere transfer of this software does not imply any licenses * of trade secrets, proprietary technology, copyrights, patents, * trademarks, maskwork rights, or any other form of intellectual * property whatsoever. Maxim Integrated Products, Inc. retains all * ownership rights. *******************************************************************************/ #define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/stringbuffer.h> #include <stdint.h> #include <cassert> #include <iostream> #include <string> #include <utility> #include "Image.hpp" #include "Text.hpp" #include "WindowManager.hpp" #include "ErrorWindow.hpp" #include "DisplayIdWindow.hpp" #include "NormalOperationWindow.hpp" #include "DisplayGraphicWindow.hpp" #include "HexConversions.hpp" #include "DS2476.hpp" #include "SensorNode.hpp" extern DS2476 coproc; extern SensorNode sensorNode; extern std::string webId; extern "C" { void ComputeSHA256(unsigned char* message, short length, unsigned short skipconst, unsigned short reverse, unsigned char* digest); } static const size_t defaultChunkSize = 256; // Default allocation size for rapidjson. static const int jsonMaxDecimalPlaces = 2; // Number of decimal places to use when writing JSON. // Separate multiple JSON commands received on the socket. // Returns a list of begin and end iterators within the input message. static std::vector<std::pair<const char *, const char *> > separateCommands(const char * receivedData, size_t receivedDataSize) { std::vector<std::pair<const char *, const char *> > commands; unsigned int counter = 0; size_t beginIdx; for (size_t i = 0; i < receivedDataSize; i++) { if (receivedData[i] == '{') { if (counter == 0) { beginIdx = i; } counter++; } else if (receivedData[i] == '}') { if (counter > 0) { counter--; if (counter == 0) { commands.push_back(std::make_pair(&receivedData[beginIdx], &receivedData[i + 1])); } } } } return commands; } // Adds signature information to an existing JSON document. static DS2476::CmdResult signData(bool validSignature, const std::vector<uint8_t> & challenge, rapidjson::Document & document) { // Move contents of document to a new location and create an empty object in document. rapidjson::Value data(rapidjson::kObjectType); data.Swap(document); // Convert data to a string and generate a signature from that string. rapidjson::StringBuffer dataBuffer; rapidjson::Writer<rapidjson::StringBuffer> writer(dataBuffer); writer.SetMaxDecimalPlaces(jsonMaxDecimalPlaces); data.Accept(writer); std::vector<uint8_t> signDataBuffer(dataBuffer.GetString(), dataBuffer.GetString() + dataBuffer.GetLength()); signDataBuffer.insert(signDataBuffer.end(), challenge.begin(), challenge.end()); DS2476::Buffer ds2476Buffer(32); ComputeSHA256(&signDataBuffer[0], signDataBuffer.size(), false, false, &ds2476Buffer[0]); DS2476::CmdResult result = coproc.writeBuffer(ds2476Buffer); if (result == DS2476::Success) { DS2476::Signature signatureBuffer; result = coproc.generateEcdsaSignature(DS2476::KeyNumA, signatureBuffer); if (result == DS2476::Success) { if (!validSignature) signatureBuffer.r[0]++; // Construct the final document with the original data and the generated signature. rapidjson::Value signature(rapidjson::kObjectType); signature.AddMember("r", rapidjson::Value(byteArrayToHexString(signatureBuffer.r.data(), signatureBuffer.r.size()).c_str(), document.GetAllocator()).Move(), document.GetAllocator()); signature.AddMember("s", rapidjson::Value(byteArrayToHexString(signatureBuffer.s.data(), signatureBuffer.s.size()).c_str(), document.GetAllocator()).Move(), document.GetAllocator()); document.AddMember("data", data, document.GetAllocator()); document.AddMember("signature", signature, document.GetAllocator()); } } return result; } // Parse and verify a signed JSON string. static DS2476::CmdResult verifySignedData(const std::string & verifyData, rapidjson::Document & signedData) { using rapidjson::Value; using std::string; // Parse string and validate object schema. signedData.Parse(verifyData.c_str()); if (!(signedData.IsObject() && signedData.HasMember("data") && signedData.HasMember("signature"))) { signedData.RemoveAllMembers(); return DS2476::AuthenticationError; } Value & data = signedData["data"]; const Value & signature = signedData["signature"]; if (!(data.IsObject() && signature.IsObject() && signature.HasMember("r") && signature.HasMember("s"))) { signedData.RemoveAllMembers(); return DS2476::AuthenticationError; } const Value & signatureR = signature["r"]; const Value & signatureS = signature["s"]; if (!(signatureR.IsString() && signatureS.IsString())) { signedData.RemoveAllMembers(); return DS2476::AuthenticationError; } // Parse signature. std::vector<uint8_t> parsedBytes = hexStringToByteArray(std::string(signatureR.GetString(), signatureR.GetStringLength())); DS2476::Signature signatureBuffer; if (parsedBytes.size() != signatureBuffer.r.size()) { signedData.RemoveAllMembers(); return DS2476::AuthenticationError; } std::copy(parsedBytes.begin(), parsedBytes.end(), signatureBuffer.r.begin()); parsedBytes = hexStringToByteArray(std::string(signatureS.GetString(), signatureS.GetStringLength())); if (parsedBytes.size() != signatureBuffer.s.size()) { signedData.RemoveAllMembers(); return DS2476::AuthenticationError; } std::copy(parsedBytes.begin(), parsedBytes.end(), signatureBuffer.s.begin()); // Compute hash of the data. // Need to use string searching here since there isn't currently a way to access raw elements // in rapidjson, and creating another copy of the data might consume too much memory. const string rawDataSearch("\"data\":"); string::size_type rawDataBegin = verifyData.find(rawDataSearch); if ((rawDataBegin == string::npos) || ((rawDataBegin + rawDataSearch.size()) >= verifyData.size())) { signedData.RemoveAllMembers(); return DS2476::AuthenticationError; } rawDataBegin += rawDataSearch.size(); string::size_type rawDataEnd = verifyData.find(",\"signature\"", rawDataBegin); if (rawDataEnd == string::npos) { signedData.RemoveAllMembers(); return DS2476::AuthenticationError; } const string::size_type chunkSize = 64; for (string::size_type i = rawDataBegin; i < rawDataEnd; i += chunkSize) { const string::size_type remainingLength = rawDataEnd - i; DS2476::CmdResult result = coproc.computeMultiblockHash(i == 0, remainingLength < chunkSize, DS2476::Buffer(verifyData.c_str() + i, verifyData.c_str() + i + std::min(remainingLength, chunkSize))); if (result != DS2476::Success) { signedData.RemoveAllMembers(); return result; } } // Verify signature. DS2476::CmdResult result = coproc.verifyEcdsaSignature(DS2476::KeyNumC, DS2476::THASH, signatureBuffer); if (result != DS2476::Success) { signedData.RemoveAllMembers(); return result; } // Strip signing information from document. rapidjson::Value swapObject(rapidjson::kObjectType); swapObject.Swap(data); swapObject.Swap(signedData); return result; } // Send a JSON document to the server. static void sendJson(const rapidjson::Value & document, TCPSocket & socket) { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); writer.SetMaxDecimalPlaces(jsonMaxDecimalPlaces); document.Accept(writer); socket.send(buffer.GetString(), buffer.GetLength()); } void NormalOperationWindow::sendMessage(const char * message) { rapidjson::MemoryPoolAllocator<> allocator(defaultChunkSize); rapidjson::Document document(rapidjson::kObjectType, &allocator); document.AddMember("message", rapidjson::StringRef(message), document.GetAllocator()); sendJson(document, *socket); } static std::string getValidSignatureButtonText(bool validSignature) { return validSignature ? "Use invalid sig." : "Use valid sig."; } void NormalOperationWindow::showWebId() { if (windowManager() != NULL) { windowManager()->push(new DisplayIdWindow(DisplayIdWindow::PopupMode)); } } void NormalOperationWindow::toggleValidSignature() { validSignature = !validSignature; validSignatureButton.setText(getValidSignatureButtonText(validSignature)); } NormalOperationWindow::NormalOperationWindow(TCPSocket * socket, Graphic * parent) : Window(parent), socket(socket), validSignature(true), lastSensorNodeState(Disconnected), lastObjectTemp(0), lastAmbientTemp(0), validSignatureButton(getValidSignatureButtonText(validSignature), this), showWebIdButton("Show web ID", this) { assert(socket != NULL); validSignatureButton.setClickedHandler(Button::EventHandler(this, &NormalOperationWindow::toggleValidSignature)); showWebIdButton.setClickedHandler(Button::EventHandler(this, &NormalOperationWindow::showWebId)); validSignatureButton.setFocused(); } NormalOperationWindow::SensorNodeState NormalOperationWindow::detectSensorNode() { SensorNodeState sensorNodeState; if (sensorNode.detect()) { bool provisioned; if (sensorNode.getProvisioned(provisioned)) { if (provisioned) { if (sensorNode.authenticate()) { bool laserEnabled; if (sensorNode.getLaserEnabled(laserEnabled)) { sensorNodeState = (laserEnabled ? ValidLaserEnabled : ValidLaserDisabled); } else { sensorNodeState = Disconnected; } } else { sensorNodeState = Invalid; } } else { bool provisionResult = sensorNode.provision(); if (provisionResult) { // Detect the new state after provisioning. sensorNodeState = detectSensorNode(); } else { sensorNodeState = FailedProvision; } } } else { sensorNodeState = Disconnected; } } else { sensorNodeState = Disconnected; } return sensorNodeState; } NormalOperationWindow::Result NormalOperationWindow::sendStatus(const std::vector<uint8_t> & challenge) { rapidjson::MemoryPoolAllocator<> allocator(defaultChunkSize); rapidjson::Document document(rapidjson::kObjectType, &allocator); // Insert Web ID. document.AddMember("id", rapidjson::StringRef(webId.c_str()), document.GetAllocator()); // Insert device public key. rapidjson::Value publicKey(rapidjson::kObjectType); DS2476::Page page; DS2476::CmdResult result = coproc.readMemory(DS2476::PublicKeyAX, page); if (result != DS2476::Success) { if (windowManager() != NULL) { windowManager()->pop(); windowManager()->push(new ErrorWindow("Failed to read PublicKeyAX")); } return WindowsChanged; } publicKey.AddMember("x", rapidjson::Value(byteArrayToHexString(page.data(), page.size()).c_str(), document.GetAllocator()).Move(), document.GetAllocator()); result = coproc.readMemory(DS2476::PublicKeyAY, page); if (result != DS2476::Success) { if (windowManager() != NULL) { windowManager()->pop(); windowManager()->push(new ErrorWindow("Failed to read PublicKeyAY")); } return WindowsChanged; } publicKey.AddMember("y", rapidjson::Value(byteArrayToHexString(page.data(), page.size()).c_str(), document.GetAllocator()).Move(), document.GetAllocator()); document.AddMember("publicKey", publicKey, document.GetAllocator()); // Insert device certificate. rapidjson::Value certificate(rapidjson::kObjectType); result = coproc.readMemory(DS2476::UserData14, page); if (result != DS2476::Success) { if (windowManager() != NULL) { windowManager()->pop(); windowManager()->push(new ErrorWindow("Failed to read UserData14")); } return WindowsChanged; } certificate.AddMember("r", rapidjson::Value(byteArrayToHexString(page.data(), page.size()).c_str(), document.GetAllocator()).Move(), document.GetAllocator()); result = coproc.readMemory(DS2476::UserData15, page); if (result != DS2476::Success) { if (windowManager() != NULL) { windowManager()->pop(); windowManager()->push(new ErrorWindow("Failed to read UserData15")); } return WindowsChanged; } certificate.AddMember("s", rapidjson::Value(byteArrayToHexString(page.data(), page.size()).c_str(), document.GetAllocator()).Move(), document.GetAllocator()); document.AddMember("certificate", certificate, document.GetAllocator()); // Sign data and transmit to server. result = signData(validSignature, challenge, document); if (result != DS2476::Success) { if (windowManager() != NULL) { windowManager()->pop(); windowManager()->push(new ErrorWindow("Failed to sign data")); } return WindowsChanged; } sendJson(document, *socket); return NoChange; } NormalOperationWindow::Result NormalOperationWindow::sendObjectTemp(const std::vector<uint8_t> & challenge) { rapidjson::MemoryPoolAllocator<> allocator(defaultChunkSize); rapidjson::Document document(rapidjson::kObjectType, &allocator); // Read object temperatue and add to document. double objectTemp; bool sensorResult = sensorNode.readTemp(SensorNode::ObjectTemp, objectTemp); if (!sensorResult) { if (windowManager() != NULL) { windowManager()->pop(); windowManager()->push(new ErrorWindow("Failed to read object temperature")); } return WindowsChanged; } document.AddMember("objectTemp", objectTemp, document.GetAllocator()); // Sign data and transmit to server. DS2476::CmdResult coprocResult = signData(validSignature, challenge, document); if (coprocResult != DS2476::Success) { if (windowManager() != NULL) { windowManager()->pop(); windowManager()->push(new ErrorWindow("Failed to sign data")); } return WindowsChanged; } sendJson(document, *socket); lastObjectTemp = objectTemp; return NoChange; } NormalOperationWindow::Result NormalOperationWindow::sendAmbientTemp(const std::vector<uint8_t> & challenge) { rapidjson::MemoryPoolAllocator<> allocator(defaultChunkSize); rapidjson::Document document(rapidjson::kObjectType, &allocator); // Read ambient temperatue and add to document. double ambientTemp; bool sensorResult = sensorNode.readTemp(SensorNode::AmbientTemp, ambientTemp); if (!sensorResult) { if (windowManager() != NULL) { windowManager()->pop(); windowManager()->push(new ErrorWindow("Failed to read ambient temperature")); } return WindowsChanged; } document.AddMember("ambientTemp", ambientTemp, document.GetAllocator()); // Sign data and transmit to server. DS2476::CmdResult coprocResult = signData(validSignature, challenge, document); if (coprocResult != DS2476::Success) { if (windowManager() != NULL) { windowManager()->pop(); windowManager()->push(new ErrorWindow("Failed to sign data")); } return WindowsChanged; } sendJson(document, *socket); lastAmbientTemp = ambientTemp; return NoChange; } void NormalOperationWindow::displayImage(const std::vector<uint8_t> & imageData) { const unsigned int width = 64; const unsigned int height = imageData.size() / (width / Bitmap::pixelsPerSegment); if (windowManager() != NULL) { windowManager()->push( new DisplayGraphicWindow( new Image(Bitmap(width, height, &imageData[0], Bitmap::ScanLineFormat)) ) ); } } NormalOperationWindow::Result NormalOperationWindow::processReceivedData(size_t recvBufSize) { // Separate commands and process each one. std::vector<std::pair<const char *, const char *> > commands = separateCommands(recvBuf, recvBufSize); for (std::vector<std::pair<const char *, const char *> >::const_iterator it = commands.begin(); it != commands.end(); it++) { rapidjson::MemoryPoolAllocator<> allocator(defaultChunkSize); rapidjson::Document data(&allocator); // Verify command signature. DS2476::CmdResult verifySignedResult = verifySignedData(std::string(it->first, it->second), data); switch (verifySignedResult) { case DS2476::Success: // Command passed authentication. { // Verify command schema. sendMessage("Received data is authentic"); if (data.IsObject() && data.HasMember("command")) { const rapidjson::Value & command = data["command"]; if (command.IsString()) { // Parse challenge if included. std::vector<uint8_t> challengeData; if (data.HasMember("challenge")) { const rapidjson::Value & challenge = data["challenge"]; if (challenge.IsString()) { challengeData = hexStringToByteArray(std::string(challenge.GetString(), challenge.GetStringLength())); } } // Execute the command. if (command == "getStatus") { Result result = sendStatus(challengeData); if (result != NoChange) return result; } else if (command == "readObjectTemp") { if ((lastSensorNodeState == ValidLaserDisabled) || (lastSensorNodeState == ValidLaserEnabled)) { Result result = sendObjectTemp(challengeData); if (result != NoChange) return result; invalidateRegion(); } } else if (command == "readAmbientTemp") { if ((lastSensorNodeState == ValidLaserDisabled) || (lastSensorNodeState == ValidLaserEnabled)) { Result result = sendAmbientTemp(challengeData); if (result != NoChange) return result; invalidateRegion(); } } else if (command == "enableModule") { if (lastSensorNodeState == ValidLaserDisabled) { if (sensorNode.setLaserEnabled(true, SensorNode::PrintHandler(this, &NormalOperationWindow::sendMessage))) { lastSensorNodeState = ValidLaserEnabled; invalidateRegion(); } } } else if (command == "disableModule") { if (lastSensorNodeState == ValidLaserEnabled) { if (sensorNode.setLaserEnabled(false, SensorNode::PrintHandler(this, &NormalOperationWindow::sendMessage))) { lastSensorNodeState = ValidLaserDisabled; invalidateRegion(); } } } else if (command == "displayImage") { if (data.HasMember("image")) { const rapidjson::Value & image = data["image"]; if (image.IsString()) { displayImage( hexStringToByteArray( std::string(image.GetString(), image.GetStringLength()) ) ); return WindowsChanged; } } } } } } break; case DS2476::AuthenticationError: // Command failed authentication. { const char message[] = "Received data is not authentic"; sendMessage(message); Text * messageText = new Text(message); messageText->setWordWrap(true); if (windowManager() != NULL) { windowManager()->push(new DisplayGraphicWindow(messageText)); } } return WindowsChanged; default: // Hardware error occurred. { const char message[] = "Unable to veify received data"; sendMessage(message); if (windowManager() != NULL) { windowManager()->push(new ErrorWindow(message)); } } return WindowsChanged; } } return NoChange; } void NormalOperationWindow::doLayout() { showWebIdButton.setWidth(width()); showWebIdButton.setHeight(showWebIdButton.preferredHeight()); showWebIdButton.setX(0); showWebIdButton.setY(height() - showWebIdButton.height()); validSignatureButton.setWidth(width()); validSignatureButton.setHeight(validSignatureButton.preferredHeight()); validSignatureButton.setX(0); validSignatureButton.setY(showWebIdButton.y() - validSignatureButton.height() - 1); } Bitmap NormalOperationWindow::render() const { // Format current status text. std::string sensorNodeStateText; switch (lastSensorNodeState) { case Disconnected: sensorNodeStateText = "Disconnected"; break; case Invalid: sensorNodeStateText = "Invalid"; break; case ValidLaserDisabled: case ValidLaserEnabled: sensorNodeStateText = "Valid"; break; } char displayString[100]; std::snprintf(displayString, sizeof(displayString) / sizeof(displayString[0]), "Object temp: %.2f\nAmbient temp: %.2f\nSensor node: %s", lastObjectTemp, lastAmbientTemp, sensorNodeStateText.c_str()); Bitmap bitmap(width(), height()); Text description((std::string(displayString))); description.update(); bitmap.overlay(description.render(), description.x(), description.y()); bitmap.overlay(validSignatureButton.render(), validSignatureButton.x(), validSignatureButton.y()); bitmap.overlay(showWebIdButton.render(), showWebIdButton.x(), showWebIdButton.y()); return bitmap; } void NormalOperationWindow::doPostLayout() { // Detect sensor node. SensorNodeState sensorNodeState = detectSensorNode(); if (sensorNodeState == FailedProvision) { if (windowManager() != NULL) { windowManager()->pop(); windowManager()->push(new ErrorWindow("Sensor node provision failed")); } return; } if (sensorNodeState != lastSensorNodeState) { lastSensorNodeState = sensorNodeState; invalidateRegion(); } // Process socket data. int recvResult = socket->recv(recvBuf, sizeof(recvBuf) / sizeof(recvBuf[0])); if (recvResult > 0) { std::cout.write(recvBuf, recvResult) << std::endl; Result result = processReceivedData(recvResult); if (result != NoChange) return; } else if (recvResult != NSAPI_ERROR_WOULD_BLOCK) { if (windowManager() != NULL) { windowManager()->pop(); windowManager()->push(new ErrorWindow("Socket recieve failed")); } return; } } bool NormalOperationWindow::doProcessKey(Key key) { bool handled; switch (key) { case UpKey: validSignatureButton.setFocused(); handled = true; break; case DownKey: showWebIdButton.setFocused(); handled = true; break; default: handled = false; break; } return handled; }