size_t cbor_serialize_array(const cbor_item_t *item, unsigned char *buffer, size_t buffer_size) { assert(cbor_isa_array(item)); size_t size = cbor_array_size(item), written = 0; cbor_item_t **handle = cbor_array_handle(item); if (cbor_array_is_definite(item)) { written = cbor_encode_array_start(size, buffer, buffer_size); } else { assert(cbor_array_is_indefinite(item)); written = cbor_encode_indef_array_start(buffer, buffer_size); } if (written == 0) return 0; size_t item_written; for (size_t i = 0; i < size; i++) { item_written = cbor_serialize(*(handle++), buffer + written, buffer_size - written); if (item_written == 0) return 0; else written += item_written; } if (cbor_array_is_definite(item)) { return written; } else { assert(cbor_array_is_indefinite(item)); item_written = cbor_encode_break(buffer + written, buffer_size - written); if (item_written == 0) return 0; else return written + 1; } }
void DynamicConfigurationServer::handleRequestReceived(const boost::system::error_code& error, size_t bytes_transferred) { LOG(INFO) << "Request received from " << remote_endpoint_; LOG(INFO) << "Begin CBOR decoding"; struct cbor_load_result result; cbor_item_t* item = cbor_load((uint8_t*)recv_buffer_.data(), bytes_transferred, &result); size_t items = cbor_array_size(item); assert(items == 2); cbor_item_t* nonceItem = cbor_array_get(item, 0); cbor_item_t* ciphertextItem = cbor_array_get(item, 1); //cbor_describe(item, stdout); //fflush(stdout); std::array<uint8_t, 16> nonce; memcpy(nonce.data(), cbor_bytestring_handle(nonceItem), 16); std::vector<uint8_t> ciphertext; ciphertext.resize(cbor_bytestring_length(ciphertextItem)); memcpy(ciphertext.data(), cbor_bytestring_handle(ciphertextItem), ciphertext.size()); std::array<uint8_t, 16> requestKey; memcpy(requestKey.data(), confRequestKey, 16); LOG(INFO) << "End CBOR decoding"; LOG(INFO) << "Begin NORX decryption"; std::tuple<bool, std::vector<uint8_t> > plaintext = NORX::decrypt( std::vector<uint8_t>(), ciphertext, std::vector<uint8_t>(), nonce, requestKey); LOG(INFO) << "END NORX decryption"; cbor_decref(&item); if (std::get<0>(plaintext)) { LOG(INFO) << "decryption successful"; item = cbor_load((uint8_t*)std::get<1>(plaintext).data(), std::get<1>(plaintext).size(), &result); //LOG(INFO) << "plaintext: " << byteVecToStr(std::get<1>(plaintext)); if (strncmp("REQ", (const char*)cbor_string_handle(item), 3) == 0) { LOG(INFO) << "received correct request"; generateCredentialsAndSendResponse(nonce); } else { cbor_describe(item, stdout); } fflush(stdout); /* Deallocate the result */ cbor_decref(&item); } else { LOG(ERROR) << "failed decrypting dynamic initialisation request."; LOG(ERROR) << "ciphertext: " << byteVecToStr(ciphertext); LOG(ERROR) << "nonce: " << byteVecToStr(std::vector<uint8_t>(nonce.begin(), nonce.end())); } startReceive(); }