diff --git a/services/tunnelbroker/docker-server/contents/server/src/Constants.h b/services/tunnelbroker/docker-server/contents/server/src/Constants.h index 49d91b9e8..22b4d0502 100644 --- a/services/tunnelbroker/docker-server/contents/server/src/Constants.h +++ b/services/tunnelbroker/docker-server/contents/server/src/Constants.h @@ -1,41 +1,49 @@ #pragma once +#include #include namespace comm { namespace network { // Tunnelbroker server Identification const std::string TUNNELBROKER_ID = "tunnel1"; // AWS const std::string DEVICE_SESSIONS_TABLE_NAME = "tunnelbroker-device-session"; const std::string DEVICE_SESSIONS_VERIFICATION_MESSAGES_TABLE_NAME = "tunnelbroker-verification-message"; const std::string DEVICE_PUBLIC_KEY_TABLE_NAME = "tunnelbroker-public-key"; // Sessions const size_t SIGNATURE_REQUEST_LENGTH = 64; const size_t SESSION_ID_LENGTH = 64; const size_t SESSION_RECORD_TTL = 30 * 24 * 3600; // 30 days const size_t SESSION_SIGN_RECORD_TTL = 24 * 3600; // 24 hours // gRPC Server const std::string SERVER_LISTEN_ADDRESS = "0.0.0.0:50051"; // AMQP (RabbitMQ) const std::string AMQP_URI = "amqp://guest:guest@0.0.0.0/vhost"; const std::string AMQP_FANOUT_EXCHANGE_NAME = "allBrokers"; // message TTL const size_t AMQP_MESSAGE_TTL = 300 * 1000; // 5 min // queue TTL in case of no consumers (tunnelbroker is down) const size_t AMQP_QUEUE_TTL = 24 * 3600 * 1000; // 24 hours // routing message headers name const std::string AMQP_HEADER_FROM_DEVICEID = "fromDeviceid"; const std::string AMQP_HEADER_TO_DEVICEID = "toDeviceid"; const long long AMQP_SHORTEST_RECONNECTION_ATTEMPT_INTERVAL = 1000 * 60; // 1 min +// DeviceID +const std::string DEVICEID_DEFAULT_KEYSERVER_ID = "ks:256"; +const size_t DEVICEID_CHAR_LENGTH = 64; +const std::regex DEVICEID_FORMAT_REGEX( + "^(ks|mobile|web):[a-zA-Z0-9]{" + std::to_string(DEVICEID_CHAR_LENGTH) + + "}$"); + } // namespace network } // namespace comm diff --git a/services/tunnelbroker/docker-server/contents/server/src/Service/TunnelbrokerServiceImpl.cpp b/services/tunnelbroker/docker-server/contents/server/src/Service/TunnelbrokerServiceImpl.cpp index 5df48eceb..747f9b784 100644 --- a/services/tunnelbroker/docker-server/contents/server/src/Service/TunnelbrokerServiceImpl.cpp +++ b/services/tunnelbroker/docker-server/contents/server/src/Service/TunnelbrokerServiceImpl.cpp @@ -1,207 +1,222 @@ #include "TunnelbrokerServiceImpl.h" #include "AmqpManager.h" #include "AwsTools.h" #include "Constants.h" #include "CryptoTools.h" #include "DatabaseManager.h" #include "DeliveryBroker.h" #include "Tools.h" #include #include #include #include namespace comm { namespace network { TunnelBrokerServiceImpl::TunnelBrokerServiceImpl() { Aws::InitAPI({}); // List of AWS DynamoDB tables to check if they are created and can be // accessed before any AWS API methods const std::list tablesList = { DEVICE_SESSIONS_TABLE_NAME, DEVICE_SESSIONS_VERIFICATION_MESSAGES_TABLE_NAME}; for (const std::string &table : tablesList) { if (!database::DatabaseManager::getInstance().isTableAvailable(table)) { throw std::runtime_error( "Error: AWS DynamoDB table '" + table + "' is not available"); } }; }; TunnelBrokerServiceImpl::~TunnelBrokerServiceImpl() { Aws::ShutdownAPI({}); }; grpc::Status TunnelBrokerServiceImpl::SessionSignature( grpc::ServerContext *context, const tunnelbroker::SessionSignatureRequest *request, tunnelbroker::SessionSignatureResponse *reply) { + const std::string deviceId = request->deviceid(); + if (!validateDeviceId(deviceId)) { + std::cout << "gRPC: " + << "Format validation failed for " << deviceId << std::endl; + return grpc::Status( + grpc::StatusCode::INVALID_ARGUMENT, + "Format validation failed for deviceID"); + } const std::string toSign = generateRandomString(SIGNATURE_REQUEST_LENGTH); std::shared_ptr SessionSignItem = - std::make_shared(toSign, request->deviceid()); + std::make_shared(toSign, deviceId); database::DatabaseManager::getInstance().putSessionSignItem(*SessionSignItem); reply->set_tosign(toSign); return grpc::Status::OK; }; grpc::Status TunnelBrokerServiceImpl::NewSession( grpc::ServerContext *context, const tunnelbroker::NewSessionRequest *request, tunnelbroker::NewSessionResponse *reply) { std::shared_ptr deviceSessionItem; std::shared_ptr sessionSignItem; std::shared_ptr publicKeyItem; const std::string deviceId = request->deviceid(); + if (!validateDeviceId(deviceId)) { + std::cout << "gRPC: " + << "Format validation failed for " << deviceId << std::endl; + return grpc::Status( + grpc::StatusCode::INVALID_ARGUMENT, + "Format validation failed for deviceID"); + } const std::string signature = request->signature(); const std::string publicKey = request->publickey(); const boost::uuids::uuid uuid = boost::uuids::random_generator()(); const std::string newSessionId = boost::lexical_cast(uuid); try { deviceSessionItem = database::DatabaseManager::getInstance().findSessionItem(newSessionId); if (deviceSessionItem != nullptr) { std::cout << "gRPC: " << "Session unique ID " << newSessionId << " already used" << std::endl; return grpc::Status( grpc::StatusCode::INTERNAL, "Session unique ID already used"); } sessionSignItem = database::DatabaseManager::getInstance().findSessionSignItem(deviceId); if (sessionSignItem == nullptr) { std::cout << "gRPC: " << "Session sign request not found for deviceId: " << deviceId << std::endl; return grpc::Status( grpc::StatusCode::NOT_FOUND, "Session sign request not found"); } publicKeyItem = database::DatabaseManager::getInstance().findPublicKeyItem(deviceId); if (publicKeyItem == nullptr) { std::shared_ptr newPublicKeyItem = std::make_shared(deviceId, publicKey); database::DatabaseManager::getInstance().putPublicKeyItem( *newPublicKeyItem); } else if (publicKey != publicKeyItem->getPublicKey()) { std::cout << "gRPC: " << "The public key doesn't match for deviceId" << std::endl; return grpc::Status( grpc::StatusCode::PERMISSION_DENIED, "The public key doesn't match for deviceId"); } const std::string verificationMessage = sessionSignItem->getSign(); if (!comm::network::crypto::rsaVerifyString( publicKey, verificationMessage, signature)) { std::cout << "gRPC: " << "Signature for the verification message is not valid" << std::endl; return grpc::Status( grpc::StatusCode::PERMISSION_DENIED, "Signature for the verification message is not valid"); } database::DatabaseManager::getInstance().removeSessionSignItem(deviceId); deviceSessionItem = std::make_shared( newSessionId, deviceId, request->publickey(), request->notifytoken(), tunnelbroker::NewSessionRequest_DeviceTypes_Name(request->devicetype()), request->deviceappversion(), request->deviceos()); database::DatabaseManager::getInstance().putSessionItem(*deviceSessionItem); } catch (std::runtime_error &e) { std::cout << "gRPC: " << "Error while processing 'NewSession' request: " << e.what() << std::endl; return grpc::Status(grpc::StatusCode::INTERNAL, e.what()); } reply->set_sessionid(newSessionId); return grpc::Status::OK; }; grpc::Status TunnelBrokerServiceImpl::Send( grpc::ServerContext *context, const tunnelbroker::SendRequest *request, google::protobuf::Empty *reply) { try { const std::string sessionId = request->sessionid(); std::shared_ptr sessionItem = database::DatabaseManager::getInstance().findSessionItem(sessionId); if (sessionItem == nullptr) { std::cout << "gRPC: " << "Session " << sessionId << " not found" << std::endl; return grpc::Status( grpc::StatusCode::PERMISSION_DENIED, "No such session found. SessionId: " + sessionId); } const std::string clientDeviceId = sessionItem->getDeviceId(); if (!AMQPSend( request->todeviceid(), clientDeviceId, std::string(request->payload()))) { std::cout << "gRPC: " << "Error while publish the message to AMQP" << std::endl; return grpc::Status( grpc::StatusCode::INTERNAL, "Error while publish the message to AMQP"); } } catch (std::runtime_error &e) { std::cout << "gRPC: " << "Error while processing 'Send' request: " << e.what() << std::endl; return grpc::Status(grpc::StatusCode::INTERNAL, e.what()); } return grpc::Status::OK; }; grpc::Status TunnelBrokerServiceImpl::Get( grpc::ServerContext *context, const tunnelbroker::GetRequest *request, grpc::ServerWriter *writer) { try { const std::string sessionId = request->sessionid(); std::shared_ptr sessionItem = database::DatabaseManager::getInstance().findSessionItem(sessionId); if (sessionItem == nullptr) { std::cout << "gRPC: " << "Session " << sessionId << " not found" << std::endl; return grpc::Status( grpc::StatusCode::PERMISSION_DENIED, "No such session found. SessionId: " + sessionId); } const std::string clientDeviceId = sessionItem->getDeviceId(); std::vector messagesToDeliver; while (1) { messagesToDeliver = DeliveryBroker::getInstance().get(clientDeviceId); for (auto const &message : messagesToDeliver) { tunnelbroker::GetResponse response; response.set_fromdeviceid(message.fromDeviceID); response.set_payload(message.payload); if (!writer->Write(response)) { throw std::runtime_error( "gRPC: 'Get' writer error on sending data to the client"); } AMQPAck(message.deliveryTag); } if (!DeliveryBroker::getInstance().isEmpty(clientDeviceId)) { DeliveryBroker::getInstance().remove(clientDeviceId); } DeliveryBroker::getInstance().wait(clientDeviceId); } } catch (std::runtime_error &e) { std::cout << "gRPC: " << "Error while processing 'Get' request: " << e.what() << std::endl; return grpc::Status(grpc::StatusCode::INTERNAL, e.what()); } return grpc::Status::OK; }; } // namespace network } // namespace comm diff --git a/services/tunnelbroker/docker-server/contents/server/src/Tools/Tools.cpp b/services/tunnelbroker/docker-server/contents/server/src/Tools/Tools.cpp index 745db592d..910ff404f 100644 --- a/services/tunnelbroker/docker-server/contents/server/src/Tools/Tools.cpp +++ b/services/tunnelbroker/docker-server/contents/server/src/Tools/Tools.cpp @@ -1,28 +1,46 @@ #include "Tools.h" +#include "Constants.h" #include +#include +#include namespace comm { namespace network { std::string generateRandomString(std::size_t length) { const std::string CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; std::random_device random_device; std::mt19937 generator(random_device()); std::uniform_int_distribution<> distribution(0, CHARACTERS.size() - 1); std::string random_string; for (std::size_t i = 0; i < length; ++i) { random_string += CHARACTERS[distribution(generator)]; } return random_string; } long long getCurrentTimestamp() { using namespace std::chrono; return duration_cast(system_clock::now().time_since_epoch()) .count(); } +bool validateDeviceId(std::string deviceId) { + try { + static const std::regex deviceIdKeyserverRegexp("^ks:.*"); + if (std::regex_match(deviceId, deviceIdKeyserverRegexp)) { + return (deviceId == DEVICEID_DEFAULT_KEYSERVER_ID); + } + return std::regex_match(deviceId, DEVICEID_FORMAT_REGEX); + } catch (const std::exception &e) { + std::cout << "Tools: " + << "Got an exception at `validateDeviceId`: " << e.what() + << std::endl; + return false; + } +} + } // namespace network } // namespace comm diff --git a/services/tunnelbroker/docker-server/contents/server/src/Tools/Tools.h b/services/tunnelbroker/docker-server/contents/server/src/Tools/Tools.h index 8a86f2bb0..0b40f5553 100644 --- a/services/tunnelbroker/docker-server/contents/server/src/Tools/Tools.h +++ b/services/tunnelbroker/docker-server/contents/server/src/Tools/Tools.h @@ -1,14 +1,14 @@ #pragma once #include #include namespace comm { namespace network { std::string generateRandomString(std::size_t length); - long long getCurrentTimestamp(); +bool validateDeviceId(std::string deviceId); } // namespace network } // namespace comm