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:
2018-01-19
Revision:
15:75404fab3615
Parent:
14:dc839a69379b

File content as of revision 15:75404fab3615:

/*******************************************************************************
* 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 <stdio.h>
#include <cassert>
#include <cstdio>
#include <string>
#include <utility>
#include <MaximInterface/Devices/DS28C36_DS2476.hpp>
#include <MaximInterface/Utilities/HexConversions.hpp>
#include "DisplayGraphicWindow.hpp"
#include "DisplayIdWindow.hpp"
#include "ErrorWindow.hpp"
#include "Image.hpp"
#include "MakeFunction.hpp"
#include "NormalOperationWindow.hpp"
#include "Text.hpp"
#include "WindowManager.hpp"

using namespace MaximInterface;

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);
}

// Default allocation size for rapidjson.
static const size_t defaultChunkSize = 256;
// Number of decimal places to use when writing JSON.
static const int jsonMaxDecimalPlaces = 2;

// 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;
  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;
}

// Creates a new command challenge, and adds it to an existing JSON document.
static error_code addCommandChallenge(rapidjson::Document & document,
                                      CommandChallenge & commandChallenge) {
  error_code result =
      coproc.readRng(commandChallenge.data(), commandChallenge.size());
  if (!result) {
    document.AddMember(
        "challenge",
        rapidjson::Value(byteArrayToHexString(commandChallenge.data(),
                                              commandChallenge.size()).c_str(),
                         document.GetAllocator()).Move(),
        document.GetAllocator());
  }
  return result;
}

// Adds signature information to an existing JSON document.
static error_code signData(bool validSignature,
                           const ResponseChallenge & challenge,
                           rapidjson::Document & document) {
  // Move contents of the document to a new location, and create an empty object
  // in the 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());
  Sha256::Hash hash;
  ComputeSHA256(&signDataBuffer[0], signDataBuffer.size(), false, false,
                hash.data());
  error_code result = coproc.writeBuffer(hash.data(), hash.size());
  if (!result) {
    Ecc256::Signature signatureBuffer;
    result = coproc.generateEcdsaSignature(DS2476::KeyNumA, signatureBuffer);
    if (!result) {
      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;
}

// Finalizes a command response to the server by adding the next command
// challenge and signing the data.
static error_code finalizeResponse(bool validSignature,
                                   const ResponseChallenge & responseChallenge,
                                   rapidjson::Document & document,
                                   CommandChallenge & commandChallenge) {
  error_code result = addCommandChallenge(document, commandChallenge);
  if (!result) {
    result = signData(validSignature, responseChallenge, document);
  }
  return result;
}

// Parse and verify a signed JSON string.
template <typename VerifyDataIt>
static error_code verifySignedData(VerifyDataIt verifyDataBegin,
                                   VerifyDataIt verifyDataEnd,
                                   const CommandChallenge & commandChallenge,
                                   rapidjson::Document & signedData) {
  using rapidjson::Value;
  using std::string;

  // Parse string and validate object schema.
  string verifyData(verifyDataBegin, verifyDataEnd);
  signedData.Parse(verifyData.c_str());
  if (!(signedData.IsObject() && signedData.HasMember("data") &&
        signedData.HasMember("signature"))) {
    signedData.RemoveAllMembers();
    return make_error_code(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 make_error_code(DS2476::AuthenticationError);
  }
  const Value & signatureR = signature["r"];
  const Value & signatureS = signature["s"];
  if (!(signatureR.IsString() && signatureS.IsString())) {
    signedData.RemoveAllMembers();
    return make_error_code(DS2476::AuthenticationError);
  }

  // Parse signature.
  std::vector<uint8_t> parsedBytes = hexStringToByteArray(
      string(signatureR.GetString(), signatureR.GetStringLength()));
  Ecc256::Signature signatureBuffer;
  if (parsedBytes.size() != signatureBuffer.r.size()) {
    signedData.RemoveAllMembers();
    return make_error_code(DS2476::AuthenticationError);
  }
  std::copy(parsedBytes.begin(), parsedBytes.end(), signatureBuffer.r.begin());
  parsedBytes = hexStringToByteArray(
      string(signatureS.GetString(), signatureS.GetStringLength()));
  if (parsedBytes.size() != signatureBuffer.s.size()) {
    signedData.RemoveAllMembers();
    return make_error_code(DS2476::AuthenticationError);
  }
  std::copy(parsedBytes.begin(), parsedBytes.end(), signatureBuffer.s.begin());

  // Get data to hash.
  // 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 make_error_code(DS2476::AuthenticationError);
  }
  rawDataBegin += rawDataSearch.size();
  string::size_type rawDataEnd =
      verifyData.find(",\"signature\"", rawDataBegin);
  if (rawDataEnd == string::npos) {
    signedData.RemoveAllMembers();
    return make_error_code(DS2476::AuthenticationError);
  }
  verifyData.erase(rawDataEnd);
  verifyData.erase(0, rawDataBegin);
  // Add in command challenge to data that will be verified.
  verifyData.append(commandChallenge.begin(), commandChallenge.end());

  // Compute hash of the data.
  error_code result = computeMultiblockHash(
      coproc, reinterpret_cast<const uint_least8_t *>(verifyData.data()),
      verifyData.size());
  if (result) {
    signedData.RemoveAllMembers();
    return result;
  }
  // Verify signature.
  result = coproc.verifyEcdsaSignature(DS2476::KeyNumC, DS2476::THASH,
                                       signatureBuffer);
  if (result) {
    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(Button *) {
  if (windowManager() != NULL) {
    std::auto_ptr<Window> window(
        new DisplayIdWindow(DisplayIdWindow::PopupMode));
    windowManager()->push(window);
  }
}

void NormalOperationWindow::toggleValidSignature(Button *) {
  validSignature = !validSignature;
  validSignatureButton.setText(getValidSignatureButtonText(validSignature));
}

NormalOperationWindow::NormalOperationWindow(std::auto_ptr<TCPSocket> & socket)
    : socket(socket) /* Move construct */, sendChallenge(true),
      validSignature(true), lastSensorNodeState(SensorNode::Disconnected),
      lastObjectTemp(0), lastAmbientTemp(0) {
  assert(this->socket.get() != NULL);

  validSignatureButton.setParent(this);
  validSignatureButton.setText(getValidSignatureButtonText(validSignature));
  validSignatureButton.setClickedHandler(
      makeFunction(this, &NormalOperationWindow::toggleValidSignature));
  showWebIdButton.setParent(this);
  showWebIdButton.setText("Show web ID");
  showWebIdButton.setClickedHandler(
      makeFunction(this, &NormalOperationWindow::showWebId));
  validSignatureButton.setFocused();
}

NormalOperationWindow::Result
NormalOperationWindow::sendStatus(const ResponseChallenge & responseChallenge) {
  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;
  error_code result = coproc.readMemory(DS2476::PublicKeyAX, page);
  if (result) {
    if (windowManager() != NULL) {
      windowManager()->pop();
      std::auto_ptr<Window> window(
          new ErrorWindow("Failed to read PublicKeyAX"));
      windowManager()->push(window);
    }
    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) {
    if (windowManager() != NULL) {
      windowManager()->pop();
      std::auto_ptr<Window> window(
          new ErrorWindow("Failed to read PublicKeyAY"));
      windowManager()->push(window);
    }
    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) {
    if (windowManager() != NULL) {
      windowManager()->pop();
      std::auto_ptr<Window> window(
          new ErrorWindow("Failed to read UserData14"));
      windowManager()->push(window);
    }
    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) {
    if (windowManager() != NULL) {
      windowManager()->pop();
      std::auto_ptr<Window> window(
          new ErrorWindow("Failed to read UserData15"));
      windowManager()->push(window);
    }
    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 = finalizeResponse(validSignature, responseChallenge, document,
                            commandChallenge);
  if (result) {
    if (windowManager() != NULL) {
      windowManager()->pop();
      std::auto_ptr<Window> window(new ErrorWindow("Failed to sign data"));
      windowManager()->push(window);
    }
    return WindowsChanged;
  }
  sendJson(document, *socket);
  return NoChange;
}

NormalOperationWindow::Result NormalOperationWindow::sendObjectTemp(
    const ResponseChallenge & responseChallenge) {
  rapidjson::MemoryPoolAllocator<> allocator(defaultChunkSize);
  rapidjson::Document document(rapidjson::kObjectType, &allocator);

  // Read object temperature and add to document.
  double objectTemp;
  bool sensorResult = sensorNode.readTemp(SensorNode::ObjectTemp, objectTemp);
  if (!sensorResult) {
    if (windowManager() != NULL) {
      windowManager()->pop();
      std::auto_ptr<Window> window(
          new ErrorWindow("Failed to read object temperature"));
      windowManager()->push(window);
    }
    return WindowsChanged;
  }
  document.AddMember("objectTemp", objectTemp, document.GetAllocator());

  // Sign data and transmit to server.
  error_code coprocResult = finalizeResponse(validSignature, responseChallenge,
                                             document, commandChallenge);
  if (coprocResult) {
    if (windowManager() != NULL) {
      windowManager()->pop();
      std::auto_ptr<Window> window(new ErrorWindow("Failed to sign data"));
      windowManager()->push(window);
    }
    return WindowsChanged;
  }
  sendJson(document, *socket);

  lastObjectTemp = objectTemp;
  return NoChange;
}

NormalOperationWindow::Result NormalOperationWindow::sendAmbientTemp(
    const ResponseChallenge & responseChallenge) {
  rapidjson::MemoryPoolAllocator<> allocator(defaultChunkSize);
  rapidjson::Document document(rapidjson::kObjectType, &allocator);

  // Read ambient temperature and add to document.
  double ambientTemp;
  bool sensorResult = sensorNode.readTemp(SensorNode::AmbientTemp, ambientTemp);
  if (!sensorResult) {
    if (windowManager() != NULL) {
      windowManager()->pop();
      std::auto_ptr<Window> window(
          new ErrorWindow("Failed to read ambient temperature"));
      windowManager()->push(window);
    }
    return WindowsChanged;
  }
  document.AddMember("ambientTemp", ambientTemp, document.GetAllocator());

  // Sign data and transmit to server.
  error_code coprocResult = finalizeResponse(validSignature, responseChallenge,
                                             document, commandChallenge);
  if (coprocResult) {
    if (windowManager() != NULL) {
      windowManager()->pop();
      std::auto_ptr<Window> window(new ErrorWindow("Failed to sign data"));
      windowManager()->push(window);
    }
    return WindowsChanged;
  }
  sendJson(document, *socket);

  lastAmbientTemp = ambientTemp;
  return NoChange;
}

void NormalOperationWindow::displayImage(
    const std::vector<uint8_t> & imageData) {
  if (windowManager() != NULL) {
    std::auto_ptr<Graphic> image(
        new Image(Bitmap(&imageData[0], imageData.size(), 64)));
    std::auto_ptr<Window> window(new DisplayGraphicWindow(image));
    windowManager()->push(window);
  }
}

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.
    error_code verifySignedResult =
        verifySignedData(it->first, it->second, commandChallenge, data);
    if (!verifySignedResult) {
      // 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.
          ResponseChallenge responseChallenge;
          if (data.HasMember("challenge")) {
            const rapidjson::Value & challenge = data["challenge"];
            if (challenge.IsString()) {
              responseChallenge = hexStringToByteArray(std::string(
                  challenge.GetString(), challenge.GetStringLength()));
            }
          }

          // Execute the command.
          if (command == "getStatus") {
            Result result = sendStatus(responseChallenge);
            if (result != NoChange)
              return result;
          } else if (command == "readObjectTemp") {
            if ((lastSensorNodeState == SensorNode::ValidLaserDisabled) ||
                (lastSensorNodeState == SensorNode::ValidLaserEnabled)) {
              Result result = sendObjectTemp(responseChallenge);
              if (result != NoChange)
                return result;
              invalidate();
            }
          } else if (command == "readAmbientTemp") {
            if ((lastSensorNodeState == SensorNode::ValidLaserDisabled) ||
                (lastSensorNodeState == SensorNode::ValidLaserEnabled)) {
              Result result = sendAmbientTemp(responseChallenge);
              if (result != NoChange)
                return result;
              invalidate();
            }
          } else if (command == "enableModule") {
            if (lastSensorNodeState == SensorNode::ValidLaserDisabled) {
              const error_code result = sensorNode.setLaserEnabled(
                  true,
                  makeFunction(this, &NormalOperationWindow::sendMessage));
              if (!result) {
                lastSensorNodeState = SensorNode::ValidLaserEnabled;
                invalidate();
              }
            }
          } else if (command == "disableModule") {
            if (lastSensorNodeState == SensorNode::ValidLaserEnabled) {
              const error_code result = sensorNode.setLaserEnabled(
                  false,
                  makeFunction(this, &NormalOperationWindow::sendMessage));
              if (!result) {
                lastSensorNodeState = SensorNode::ValidLaserDisabled;
                invalidate();
              }
            }
          } 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;
              }
            }
          }
        }
      }
    } else if (verifySignedResult ==
               make_error_code(DS2476::AuthenticationError)) {
      const char message[] = "Received data is not authentic";
      sendMessage(message);
      std::auto_ptr<Graphic> messageText(new Text);
      Text & messageTextRef = *static_cast<Text *>(messageText.get());
      messageTextRef.setText(message);
      messageTextRef.setWordWrap(true);
      if (windowManager() != NULL) {
        std::auto_ptr<Window> window(new DisplayGraphicWindow(messageText));
        windowManager()->push(window);
      }
      return WindowsChanged;
    } else {
      const char message[] = "Unable to verify received data";
      sendMessage(message);
      if (windowManager() != NULL) {
        std::auto_ptr<Window> window(new ErrorWindow(message));
        windowManager()->push(window);
      }
      return WindowsChanged;
    }
  }
  return NoChange;
}

void NormalOperationWindow::resized() {
  showWebIdButton.resize(width(), showWebIdButton.preferredHeight());
  showWebIdButton.move(0, height() - showWebIdButton.height());
  validSignatureButton.resize(width(), validSignatureButton.preferredHeight());
  validSignatureButton.move(0, showWebIdButton.y() -
                                   validSignatureButton.height() - 1);
}

static std::string doubleToString(double input) {
  char inputString[8];
  snprintf(inputString, sizeof(inputString) / sizeof(inputString[0]), "%.2f",
           input);
  return std::string(inputString);
}

void NormalOperationWindow::doRender(Bitmap & bitmap, int xOffset,
                                     int yOffset) const {
  // Format current status text.
  std::string sensorNodeStateText;
  switch (lastSensorNodeState) {
  case SensorNode::Disconnected:
    sensorNodeStateText = "Disconnected";
    break;

  case SensorNode::Invalid:
    sensorNodeStateText = "Invalid";
    break;

  case SensorNode::ValidLaserDisabled:
    sensorNodeStateText = "Valid, laser disabled";
    break;

  case SensorNode::ValidLaserEnabled:
    sensorNodeStateText = "Valid, laser enabled";
    break;

  case SensorNode::NotProvisioned:
    break;
  }

  Text description;
  description.setText("Object temp: " + doubleToString(lastObjectTemp) +
                      "\nAmbient temp: " + doubleToString(lastAmbientTemp) +
                      "\nSensor node: " + sensorNodeStateText);
  description.resize(width(), validSignatureButton.y());
  description.setWordWrap(true);
  description.render(bitmap, xOffset + x(), yOffset + y());
  validSignatureButton.render(bitmap, xOffset + x(), yOffset + y());
  showWebIdButton.render(bitmap, xOffset + x(), yOffset + y());
}

void NormalOperationWindow::updated() {
  // Detect sensor node.
  std::pair<SensorNode::State, error_code> sensorNodeState =
      sensorNode.detect();
  if (sensorNodeState.first == SensorNode::NotProvisioned) {
    const error_code result = sensorNode.provision();
    if (result) {
      if (windowManager() != NULL) {
        windowManager()->pop();
        std::auto_ptr<Window> window(
            new ErrorWindow("Sensor node provision failed"));
        windowManager()->push(window);
      }
      return;
    }
    sensorNodeState = sensorNode.detect();
  }
  if (sensorNodeState.first != lastSensorNodeState) {
    lastSensorNodeState = sensorNodeState.first;
    invalidate();
  }

  // Send challenge on first connection.
  if (sendChallenge) {
    rapidjson::MemoryPoolAllocator<> allocator(defaultChunkSize);
    rapidjson::Document document(rapidjson::kObjectType, &allocator);
    error_code result = addCommandChallenge(document, commandChallenge);
    if (!result) {
      sendJson(document, *socket);
      sendChallenge = false;
    }
  }
  // Process socket data.
  else {
    int recvResult =
        socket->recv(recvBuf, sizeof(recvBuf) / sizeof(recvBuf[0]));
    if (recvResult > 0) {
      std::printf("%*s\n", recvResult, recvBuf);
      Result result = processReceivedData(recvResult);
      if (result != NoChange)
        return;
    } else if (recvResult != NSAPI_ERROR_WOULD_BLOCK) {
      if (windowManager() != NULL) {
        windowManager()->pop();
        std::auto_ptr<Window> window(new ErrorWindow("Socket receive failed"));
        windowManager()->push(window);
      }
      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;
}