From 587c42a7f74e36887d949bf1d1d510d0e20990e2 Mon Sep 17 00:00:00 2001 From: Gus Grubba Date: Wed, 15 Aug 2018 17:39:32 -0400 Subject: [PATCH] Decode anonymous pilot ID off the JSON Web Token returned by the anonymous login. --- qgroundcontrol.pro | 2 + src/Airmap/AirMapFlightManager.h | 1 - src/Airmap/AirMapFlightPlanManager.cc | 25 +- src/Airmap/AirMapFlightPlanManager.h | 1 - src/Airmap/AirMapSharedState.cc | 15 +- src/Airmap/AirMapSharedState.h | 4 + src/Airmap/QJsonWebToken/README.md | 47 ++ .../QJsonWebToken/src/qjsonwebtoken.cpp | 337 +++++++++++++++ src/Airmap/QJsonWebToken/src/qjsonwebtoken.h | 404 ++++++++++++++++++ .../QJsonWebToken/src/qjsonwebtoken.pri | 7 + 10 files changed, 828 insertions(+), 15 deletions(-) create mode 100644 src/Airmap/QJsonWebToken/README.md create mode 100644 src/Airmap/QJsonWebToken/src/qjsonwebtoken.cpp create mode 100644 src/Airmap/QJsonWebToken/src/qjsonwebtoken.h create mode 100644 src/Airmap/QJsonWebToken/src/qjsonwebtoken.pri diff --git a/qgroundcontrol.pro b/qgroundcontrol.pro index 37829134a..3e4c367df 100644 --- a/qgroundcontrol.pro +++ b/qgroundcontrol.pro @@ -1161,6 +1161,8 @@ contains (DEFINES, QGC_AIRMAP_ENABLED) { DEFINES += QGC_AIRMAP_KEY_AVAILABLE } + include(src/Airmap/QJsonWebToken/src/qjsonwebtoken.pri) + } else { #-- Dummies INCLUDEPATH += \ diff --git a/src/Airmap/AirMapFlightManager.h b/src/Airmap/AirMapFlightManager.h index e34725f33..fb17cdfd9 100644 --- a/src/Airmap/AirMapFlightManager.h +++ b/src/Airmap/AirMapFlightManager.h @@ -48,7 +48,6 @@ private: State _state = State::Idle; AirMapSharedState& _shared; QString _flightID; - QString _pilotID; ///< Pilot ID in the form "auth0|abc123" QGCGeoBoundingCube _searchArea; }; diff --git a/src/Airmap/AirMapFlightPlanManager.cc b/src/Airmap/AirMapFlightPlanManager.cc index bbc00373d..073e3b87b 100644 --- a/src/Airmap/AirMapFlightPlanManager.cc +++ b/src/Airmap/AirMapFlightPlanManager.cc @@ -270,7 +270,7 @@ AirMapFlightPlanManager::endFlight(QString flightID) { qCDebug(AirMapManagerLog) << "End flight"; _flightToEnd = flightID; - if (_pilotID == "") { + if (_shared.pilotID().isEmpty()) { //-- Need to get the pilot id qCDebug(AirMapManagerLog) << "Getting pilot ID"; _state = State::GetPilotID; @@ -283,8 +283,9 @@ AirMapFlightPlanManager::endFlight(QString flightID) if (!isAlive.lock()) return; if (_state != State::GetPilotID) return; if (result) { - _pilotID = QString::fromStdString(result.value().id); - qCDebug(AirMapManagerLog) << "Got Pilot ID:"<<_pilotID; + QString pilotID = QString::fromStdString(result.value().id); + _shared.setPilotID(pilotID); + qCDebug(AirMapManagerLog) << "Got Pilot ID:" << pilotID; _state = State::Idle; _endFlight(); } else { @@ -380,7 +381,7 @@ AirMapFlightPlanManager::_createFlightPlan() qCDebug(AirMapManagerLog) << "Flight Start:" << flightStartTime().toString(); qCDebug(AirMapManagerLog) << "Flight Duration: " << flightDuration(); - if (_pilotID == "" && !_shared.settings().userName.isEmpty() && !_shared.settings().password.isEmpty()) { + if (_shared.pilotID().isEmpty() && !_shared.settings().userName.isEmpty() && !_shared.settings().password.isEmpty()) { //-- Need to get the pilot id before uploading the flight plan qCDebug(AirMapManagerLog) << "Getting pilot ID"; _state = State::GetPilotID; @@ -393,8 +394,9 @@ AirMapFlightPlanManager::_createFlightPlan() if (!isAlive.lock()) return; if (_state != State::GetPilotID) return; if (result) { - _pilotID = QString::fromStdString(result.value().id); - qCDebug(AirMapManagerLog) << "Got Pilot ID:"<<_pilotID; + QString pilotID = QString::fromStdString(result.value().id); + _shared.setPilotID(pilotID); + qCDebug(AirMapManagerLog) << "Got Pilot ID:" << pilotID; _state = State::Idle; _uploadFlightPlan(); } else { @@ -513,7 +515,7 @@ AirMapFlightPlanManager::_uploadFlightPlan() params.buffer = 10.f; params.latitude = static_cast(_flight.takeoffCoord.latitude()); params.longitude = static_cast(_flight.takeoffCoord.longitude()); - params.pilot.id = _pilotID.toStdString(); + params.pilot.id = _shared.pilotID().toStdString(); //-- Handle flight start/end _updateFlightStartEndTime(params.start_time, params.end_time); //-- Rules & Features @@ -838,7 +840,7 @@ AirMapFlightPlanManager::loadFlightList(QDateTime startTime, QDateTime endTime) _rangeStart = startTime; _rangeEnd = endTime; qCDebug(AirMapManagerLog) << "List flights from:" << _rangeStart.toString("yyyy MM dd - hh:mm:ss") << "to" << _rangeEnd.toString("yyyy MM dd - hh:mm:ss"); - if (_pilotID == "") { + if (_shared.pilotID().isEmpty()) { //-- Need to get the pilot id qCDebug(AirMapManagerLog) << "Getting pilot ID"; _state = State::GetPilotID; @@ -851,8 +853,9 @@ AirMapFlightPlanManager::loadFlightList(QDateTime startTime, QDateTime endTime) if (!isAlive.lock()) return; if (_state != State::GetPilotID) return; if (result) { - _pilotID = QString::fromStdString(result.value().id); - qCDebug(AirMapManagerLog) << "Got Pilot ID:"<<_pilotID; + QString pilotID = QString::fromStdString(result.value().id); + _shared.setPilotID(pilotID); + qCDebug(AirMapManagerLog) << "Got Pilot ID:" << pilotID; _state = State::Idle; _loadFlightList(); } else { @@ -893,7 +896,7 @@ AirMapFlightPlanManager::_loadFlightList() params.start_after = airmap::from_milliseconds_since_epoch(airmap::milliseconds(static_cast(start))); params.start_before = airmap::from_milliseconds_since_epoch(airmap::milliseconds(static_cast(end))); params.limit = 250; - params.pilot_id = _pilotID.toStdString(); + params.pilot_id = _shared.pilotID().toStdString(); _shared.client()->flights().search(params, [this, isAlive](const Flights::Search::Result& result) { if (!isAlive.lock()) return; if (_state != State::LoadFlightList) return; diff --git a/src/Airmap/AirMapFlightPlanManager.h b/src/Airmap/AirMapFlightPlanManager.h index 96ef1aeb3..51a35b9b9 100644 --- a/src/Airmap/AirMapFlightPlanManager.h +++ b/src/Airmap/AirMapFlightPlanManager.h @@ -152,7 +152,6 @@ private: AirMapSharedState& _shared; QTimer _pollTimer; ///< timer to poll for approval check QString _flightId; ///< Current flight ID, not necessarily accepted yet - QString _pilotID; ///< Pilot ID in the form "auth0|abc123" QString _flightToEnd; PlanMasterController* _planController = nullptr; bool _valid = false; diff --git a/src/Airmap/AirMapSharedState.cc b/src/Airmap/AirMapSharedState.cc index 265181231..d13d4e0e3 100644 --- a/src/Airmap/AirMapSharedState.cc +++ b/src/Airmap/AirMapSharedState.cc @@ -11,6 +11,7 @@ #include "AirMapManager.h" #include "airmap/authenticator.h" +#include "qjsonwebtoken.h" using namespace airmap; @@ -32,6 +33,11 @@ AirMapSharedState::doRequestWithLogin(const Callback& callback) } } +//-- TODO: +// For now, only anonymous login collects the (anonymous) pilot ID within login() +// For autheticated logins, we need to collect it here as opposed to spread all over +// the place as it is the case now. + void AirMapSharedState::login() { @@ -52,6 +58,11 @@ AirMapSharedState::login() qCDebug(AirMapManagerLog) << "Successfully authenticated with AirMap: id="<< result.value().id.c_str(); emit authStatus(AirspaceManager::AuthStatus::Anonymous); _loginToken = QString::fromStdString(result.value().id); + QJsonWebToken token = QJsonWebToken::fromTokenAndSecret(_loginToken, QString()); + QJsonDocument doc = token.getPayloadJDoc(); + QJsonObject json = doc.object(); + _pilotID = json.value("sub").toString(); + qCDebug(AirMapManagerLog) << "Anonymous pilot id:" << _pilotID; _processPendingRequests(); } else { _pendingRequests.clear(); @@ -105,9 +116,9 @@ AirMapSharedState::logout() if (!isLoggedIn()) { return; } - _loginToken = ""; + _pilotID.clear(); + _loginToken.clear(); _pendingRequests.clear(); - } diff --git a/src/Airmap/AirMapSharedState.h b/src/Airmap/AirMapSharedState.h index 95036fbdd..4b3278395 100644 --- a/src/Airmap/AirMapSharedState.h +++ b/src/Airmap/AirMapSharedState.h @@ -37,6 +37,9 @@ public: const Settings& settings () const { return _settings; } void setClient (airmap::qt::Client* client) { _client = client; } + QString pilotID () { return _pilotID; } + void setPilotID (const QString& pilotID) { _pilotID = pilotID; } + /** * Get the current client instance. It can be NULL. If not NULL, it implies * there's an API key set. @@ -66,6 +69,7 @@ private: private: bool _isLoginInProgress = false; QString _loginToken; ///< login token: empty when not logged in + QString _pilotID; airmap::qt::Client* _client = nullptr; Settings _settings; QQueue _pendingRequests; ///< pending requests that are processed after a successful login diff --git a/src/Airmap/QJsonWebToken/README.md b/src/Airmap/QJsonWebToken/README.md new file mode 100644 index 000000000..8dd2a037b --- /dev/null +++ b/src/Airmap/QJsonWebToken/README.md @@ -0,0 +1,47 @@ +## Introduction + +QJsonWebToken : JWT (JSON Web Token) Implementation in Qt C++ + +This class implements a subset of the [JSON Web Token](https://en.wikipedia.org/wiki/JSON_Web_Token) +open standard [RFC 7519](https://tools.ietf.org/html/rfc7519). + +Currently this implementation **only supports** the following algorithms: + +Alg | Parameter Value Algorithm +----- | ------------------------------------ +HS256 | HMAC using SHA-256 hash algorithm +HS384 | HMAC using SHA-384 hash algorithm +HS512 | HMAC using SHA-512 hash algorithm + +### Include + +In order to include this class in your project, in the qt project **.pro** file add the lines: + +```cmake +HEADERS += ./src/qjsonwebtoken.h +SOURCES += ./src/qjsonwebtoken.cpp +``` + +### Usage + +The repository of this project includes examples that demonstrate the use of this class: + +* ```./examples/jwtcreator/``` : Example that shows how to create a JWT with your custom *payload*. + +* ```./examples/jwtverifier/``` : Example that shows how to validate a JWT with a given *secret*. + +### Limitations + +Currently, `QJsonWebToken` validator, can **only** validate tokens created by `QJsonWebToken` itself. This limitation is due to the usage of Qt's [QJsonDocument API](http://doc.qt.io/qt-5/qjsondocument.html), see [this issue for further explanation](https://github.com/juangburgos/QJsonWebToken/issues/3#issuecomment-333056575). + +### License + +MIT + +``` +The MIT License(MIT) +Copyright(c) <2016> +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 THE AUTHORS OR COPYRIGHT HOLDERS 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. +``` diff --git a/src/Airmap/QJsonWebToken/src/qjsonwebtoken.cpp b/src/Airmap/QJsonWebToken/src/qjsonwebtoken.cpp new file mode 100644 index 000000000..7dd0bcc4b --- /dev/null +++ b/src/Airmap/QJsonWebToken/src/qjsonwebtoken.cpp @@ -0,0 +1,337 @@ +// The MIT License(MIT) +// Copyright(c) <2016> +// 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 THE AUTHORS OR COPYRIGHT HOLDERS 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. + +#include "qjsonwebtoken.h" + +#include + +QJsonWebToken::QJsonWebToken() +{ + // create the header with default algorithm + setAlgorithmStr("HS256"); + m_jdocPayload = QJsonDocument::fromJson("{}"); + // default for random generation + m_intRandLength = 10; + m_strRandAlphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; +} + +QJsonWebToken::QJsonWebToken(const QJsonWebToken &other) +{ + this->m_jdocHeader = other.m_jdocHeader; + this->m_jdocPayload = other.m_jdocPayload; + this->m_byteSignature = other.m_byteSignature; + this->m_strSecret = other.m_strSecret; + this->m_strAlgorithm = other.m_strAlgorithm; +} + +QJsonDocument QJsonWebToken::getHeaderJDoc() +{ + return m_jdocHeader; +} + +QString QJsonWebToken::getHeaderQStr(QJsonDocument::JsonFormat format /*= QJsonDocument::JsonFormat::Indented*/) +{ + return m_jdocHeader.toJson(format); +} + +bool QJsonWebToken::setHeaderJDoc(QJsonDocument jdocHeader) +{ + if (jdocHeader.isEmpty() || jdocHeader.isNull() || !jdocHeader.isObject()) + { + return false; + } + + // check if supported algorithm + QString strAlgorithm = jdocHeader.object().value("alg").toString(""); + if (!isAlgorithmSupported(strAlgorithm)) + { + return false; + } + + m_jdocHeader = jdocHeader; + + // set also new algorithm + m_strAlgorithm = strAlgorithm; + + return true; +} + +bool QJsonWebToken::setHeaderQStr(QString strHeader) +{ + QJsonParseError error; + QJsonDocument tmpHeader = QJsonDocument::fromJson(strHeader.toUtf8(), &error); + + // validate and set header + if (error.error != QJsonParseError::NoError || !setHeaderJDoc(tmpHeader)) + { + return false; + } + + return true; +} + +QJsonDocument QJsonWebToken::getPayloadJDoc() +{ + return m_jdocPayload; +} + +QString QJsonWebToken::getPayloadQStr(QJsonDocument::JsonFormat format /*= QJsonDocument::JsonFormat::Indented*/) +{ + return m_jdocPayload.toJson(format); +} + +bool QJsonWebToken::setPayloadJDoc(QJsonDocument jdocPayload) +{ + if (jdocPayload.isEmpty() || jdocPayload.isNull() || !jdocPayload.isObject()) + { + return false; + } + + m_jdocPayload = jdocPayload; + + return true; +} + +bool QJsonWebToken::setPayloadQStr(QString strPayload) +{ + QJsonParseError error; + QJsonDocument tmpPayload = QJsonDocument::fromJson(strPayload.toUtf8(), &error); + + // validate and set payload + if (error.error != QJsonParseError::NoError || !setPayloadJDoc(tmpPayload)) + { + return false; + } + + return true; +} + +QByteArray QJsonWebToken::getSignature() +{ + // recalculate + // get header in compact mode and base64 encoded + QByteArray byteHeaderBase64 = getHeaderQStr(QJsonDocument::JsonFormat::Compact).toUtf8().toBase64(); + // get payload in compact mode and base64 encoded + QByteArray bytePayloadBase64 = getPayloadQStr(QJsonDocument::JsonFormat::Compact).toUtf8().toBase64(); + // calculate signature based on chosen algorithm and secret + m_byteAllData = byteHeaderBase64 + "." + bytePayloadBase64; + if (m_strAlgorithm.compare("HS256", Qt::CaseInsensitive) == 0) // HMAC using SHA-256 hash algorithm + { + m_byteSignature = QMessageAuthenticationCode::hash(m_byteAllData, m_strSecret.toUtf8(), QCryptographicHash::Sha256); + } + else if (m_strAlgorithm.compare("HS384", Qt::CaseInsensitive) == 0) // HMAC using SHA-384 hash algorithm + { + m_byteSignature = QMessageAuthenticationCode::hash(m_byteAllData, m_strSecret.toUtf8(), QCryptographicHash::Sha384); + } + else if (m_strAlgorithm.compare("HS512", Qt::CaseInsensitive) == 0) // HMAC using SHA-512 hash algorithm + { + m_byteSignature = QMessageAuthenticationCode::hash(m_byteAllData, m_strSecret.toUtf8(), QCryptographicHash::Sha512); + } + // TODO : support other algorithms + else + { + m_byteSignature = QByteArray(); + } + // return recalculated + return m_byteSignature; +} + +QByteArray QJsonWebToken::getSignatureBase64() +{ + // note we return through getSignature() to force recalculation + return getSignature().toBase64(); +} + +QString QJsonWebToken::getSecret() +{ + return m_strSecret; +} + +bool QJsonWebToken::setSecret(QString strSecret) +{ + if (strSecret.isEmpty() || strSecret.isNull()) + { + return false; + } + + m_strSecret = strSecret; + + return true; +} + +void QJsonWebToken::setRandomSecret() +{ + m_strSecret.resize(m_intRandLength); + for (int i = 0; i < m_intRandLength; ++i) + { + m_strSecret[i] = m_strRandAlphanum.at(rand() % (m_strRandAlphanum.length() - 1)); + } +} + +QString QJsonWebToken::getAlgorithmStr() +{ + return m_strAlgorithm; +} + +bool QJsonWebToken::setAlgorithmStr(QString strAlgorithm) +{ + // check if supported algorithm + if (!isAlgorithmSupported(strAlgorithm)) + { + return false; + } + // set algorithm + m_strAlgorithm = strAlgorithm; + // modify header + m_jdocHeader = QJsonDocument::fromJson(QObject::trUtf8("{\"typ\": \"JWT\", \"alg\" : \"").toUtf8() + + m_strAlgorithm.toUtf8() + + QObject::trUtf8("\"}").toUtf8()); + + return true; +} + +QString QJsonWebToken::getToken() +{ + // important to execute first to update m_byteAllData which contains header + "." + payload in base64 + QByteArray byteSignatureBase64 = getSignatureBase64(); + // compose token and return it + return m_byteAllData + "." + byteSignatureBase64; +} + +bool QJsonWebToken::setToken(QString strToken) +{ + // assume base64 encoded at first, if not try decoding + bool isBase64Encoded = true; + QStringList listJwtParts = strToken.split("."); + // check correct size + if (listJwtParts.count() != 3) + { + return false; + } + // check all parts are valid using another instance, + // so we dont overwrite this instance in case of error + QJsonWebToken tempTokenObj; + if ( !tempTokenObj.setHeaderQStr(QByteArray::fromBase64(listJwtParts.at(0).toUtf8())) || + !tempTokenObj.setPayloadQStr(QByteArray::fromBase64(listJwtParts.at(1).toUtf8())) ) + { + // try unencoded + if (!tempTokenObj.setHeaderQStr(listJwtParts.at(0)) || + !tempTokenObj.setPayloadQStr(listJwtParts.at(1))) + { + return false; + } + else + { + isBase64Encoded = false; + } + } + // set parts on this instance + setHeaderQStr(tempTokenObj.getHeaderQStr()); + setPayloadQStr(tempTokenObj.getPayloadQStr()); + if (isBase64Encoded) + { // unencode + m_byteSignature = QByteArray::fromBase64(listJwtParts.at(2).toUtf8()); + } + else + { + m_byteSignature = listJwtParts.at(2).toUtf8(); + } + // allData not valid anymore + m_byteAllData.clear(); + // success + return true; +} + +QString QJsonWebToken::getRandAlphanum() +{ + return m_strRandAlphanum; +} + +void QJsonWebToken::setRandAlphanum(QString strRandAlphanum) +{ + if(strRandAlphanum.isNull()) + { + return; + } + m_strRandAlphanum = strRandAlphanum; +} + +int QJsonWebToken::getRandLength() +{ + return m_intRandLength; +} + +void QJsonWebToken::setRandLength(int intRandLength) +{ + if(intRandLength < 0 || intRandLength > 1e6) + { + return; + } + m_intRandLength = intRandLength; +} + +bool QJsonWebToken::isValid() +{ + // calculate token on other instance, + // so we dont overwrite this instance's signature + QJsonWebToken tempTokenObj = *this; + if (m_byteSignature != tempTokenObj.getSignature()) + { + return false; + } + return true; +} + +QJsonWebToken QJsonWebToken::fromTokenAndSecret(QString strToken, QString srtSecret) +{ + QJsonWebToken tempTokenObj; + // set Token + tempTokenObj.setToken(strToken); + // set Secret + tempTokenObj.setSecret(srtSecret); + // return + return tempTokenObj; +} + +void QJsonWebToken::appendClaim(QString strClaimType, QString strValue) +{ + // have to make a copy of the json object, modify the copy and then put it back, sigh + QJsonObject jObj = m_jdocPayload.object(); + jObj.insert(strClaimType, strValue); + m_jdocPayload = QJsonDocument(jObj); +} + +void QJsonWebToken::removeClaim(QString strClaimType) +{ + // have to make a copy of the json object, modify the copy and then put it back, sigh + QJsonObject jObj = m_jdocPayload.object(); + jObj.remove(strClaimType); + m_jdocPayload = QJsonDocument(jObj); +} + +bool QJsonWebToken::isAlgorithmSupported(QString strAlgorithm) +{ + // TODO : support other algorithms + if (strAlgorithm.compare("HS256", Qt::CaseInsensitive) != 0 && // HMAC using SHA-256 hash algorithm + strAlgorithm.compare("HS384", Qt::CaseInsensitive) != 0 && // HMAC using SHA-384 hash algorithm + strAlgorithm.compare("HS512", Qt::CaseInsensitive) != 0 /*&& // HMAC using SHA-512 hash algorithm + strAlgorithm.compare("RS256", Qt::CaseInsensitive) != 0 && // RSA using SHA-256 hash algorithm + strAlgorithm.compare("RS384", Qt::CaseInsensitive) != 0 && // RSA using SHA-384 hash algorithm + strAlgorithm.compare("RS512", Qt::CaseInsensitive) != 0 && // RSA using SHA-512 hash algorithm + strAlgorithm.compare("ES256", Qt::CaseInsensitive) != 0 && // ECDSA using P-256 curve and SHA-256 hash algorithm + strAlgorithm.compare("ES384", Qt::CaseInsensitive) != 0 && // ECDSA using P-384 curve and SHA-384 hash algorithm + strAlgorithm.compare("ES512", Qt::CaseInsensitive) != 0*/) // ECDSA using P-521 curve and SHA-512 hash algorithm + { + return false; + } + return true; +} + +QStringList QJsonWebToken::supportedAlgorithms() +{ + // TODO : support other algorithms + return QStringList() << "HS256" << "HS384" << "HS512"; +} diff --git a/src/Airmap/QJsonWebToken/src/qjsonwebtoken.h b/src/Airmap/QJsonWebToken/src/qjsonwebtoken.h new file mode 100644 index 000000000..63482c0b5 --- /dev/null +++ b/src/Airmap/QJsonWebToken/src/qjsonwebtoken.h @@ -0,0 +1,404 @@ +/** +\file +\version 1.0 +\date 22/06/2016 +\author JGB +\brief JWT (JSON Web Token) Implementation in Qt C++ +*/ + +// The MIT License(MIT) +// Copyright(c) <2016> +// 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 THE AUTHORS OR COPYRIGHT HOLDERS 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. + +#ifndef QJSONWEBTOKEN_H +#define QJSONWEBTOKEN_H + +#include +#include +#include +#include + +/** + +\brief QJsonWebToken : JWT (JSON Web Token) Implementation in Qt C++ + +## Introduction + +This class implements a subset of the [JSON Web Token](https://en.wikipedia.org/wiki/JSON_Web_Token) +open standard [RFC 7519](https://tools.ietf.org/html/rfc7519). + +Currently this implementation only supports the following algorithms: + +Alg | Parameter Value Algorithm +----- | ------------------------------------ +HS256 | HMAC using SHA-256 hash algorithm +HS384 | HMAC using SHA-384 hash algorithm +HS512 | HMAC using SHA-512 hash algorithm + +### Include + +In order to include this class in your project, in the qt project **.pro** file add the lines: + +``` +HEADERS += ./src/qjsonwebtoken.h +SOURCES += ./src/qjsonwebtoken.cpp +``` + +### Usage + +The repository of this project includes examples that demonstrate the use of this class: + +* ./examples/jwtcreator/ : Example that shows how to create a JWT with your custom *payload*. + +* ./examples/jwtverifier/ : Example that shows how to validate a JWT with a given *secret*. + +*/ +class QJsonWebToken +{ + +public: + + /** + + \brief Constructor. + \return A new instance of QJsonWebToken. + + Creates a default QJsonWebToken instance with *HS256 algorithm*, empty *payload* + and empty *secret*. + + */ + QJsonWebToken(); // TODO : improve with params + + /** + + \brief Copy Construtor. + \param other Other QJsonWebToken to copy from. + \return A new instance of QJsonWebToken with same contents as the *other* instance. + + Copies to the new instance the JWT *header*, *payload*, *signature*, *secret* and *algorithm*. + + */ + QJsonWebToken(const QJsonWebToken &other); + + /** + + \brief Returns the JWT *header* as a QJsonDocument. + \return JWT *header* as a QJsonDocument. + + */ + QJsonDocument getHeaderJDoc(); + + /** + + \brief Returns the JWT *header* as a QString. + \param format Defines the format of the JSON returned. + \return JWT *header* as a QString. + + Format can be *QJsonDocument::JsonFormat::Indented* or *QJsonDocument::JsonFormat::Compact* + + */ + QString getHeaderQStr(QJsonDocument::JsonFormat format = QJsonDocument::JsonFormat::Indented); + + /** + + \brief Sets the JWT *header* from a QJsonDocument. + \param jdocHeader JWT *header* as a QJsonDocument. + \return true if the header was set, false if the header was not set. + + This method checks for a valid header format and returns false if the header is invalid. + + */ + bool setHeaderJDoc(QJsonDocument jdocHeader); + + /** + + \brief Sets the JWT *header* from a QString. + \param jdocHeader JWT *header* as a QString. + \return true if the header was set, false if the header was not set. + + This method checks for a valid header format and returns false if the header is invalid. + + */ + bool setHeaderQStr(QString strHeader); + + /** + + \brief Returns the JWT *payload* as a QJsonDocument. + \return JWT *payload* as a QJsonDocument. + + */ + QJsonDocument getPayloadJDoc(); + + /** + + \brief Returns the JWT *payload* as a QString. + \param format Defines the format of the JSON returned. + \return JWT *payload* as a QString. + + Format can be *QJsonDocument::JsonFormat::Indented* or *QJsonDocument::JsonFormat::Compact* + + */ + QString getPayloadQStr(QJsonDocument::JsonFormat format = QJsonDocument::JsonFormat::Indented); + + /** + + \brief Sets the JWT *payload* from a QJsonDocument. + \param jdocHeader JWT *payload* as a QJsonDocument. + \return true if the payload was set, false if the payload was not set. + + This method checks for a valid payload format and returns false if the payload is invalid. + + */ + bool setPayloadJDoc(QJsonDocument jdocPayload); + + /** + + \brief Sets the JWT *payload* from a QString. + \param jdocHeader JWT *payload* as a QString. + \return true if the payload was set, false if the payload was not set. + + This method checks for a valid payload format and returns false if the payload is invalid. + + */ + bool setPayloadQStr(QString strPayload); + + /** + + \brief Returns the JWT *signature* as a QByteArray. + \return JWT *signature* as a decoded QByteArray. + + Recalculates the JWT signature given the current *header*, *payload*, *algorithm* and + *secret*. + + \warning This method overwrites the old signature internally. This could be undesired when + the signature was obtained by copying from another QJsonWebToken using the copy constructor. + + */ + QByteArray getSignature(); // WARNING overwrites signature + + /** + + \brief Returns the JWT *signature* as a QByteArray. + \return JWT *signature* as a **base64 encoded** QByteArray. + + Recalculates the JWT signature given the current *header*, *payload*, *algorithm* and + *secret*. Then encodes the calculated signature using base64 encoding. + + \warning This method overwrites the old signature internally. This could be undesired when + the signature was obtained by copying from another QJsonWebToken using the copy constructor. + + */ + QByteArray getSignatureBase64(); // WARNING overwrites signature + + /** + + \brief Returns the JWT *secret* as a QString. + \return JWT *secret* as a QString. + + */ + QString getSecret(); + + /** + + \brief Sets the JWT *secret* from a QString. + \param strSecret JWT *secret* as a QString. + \return true if the secret was set, false if the secret was not set. + + This method checks for a valid secret format and returns false if the secret is invalid. + + */ + bool setSecret(QString strSecret); + + /** + + \brief Creates and sets a random secret. + + This method creates a random secret with the length defined by QJsonWebToken::getRandLength(), + and the characters defined by QJsonWebToken::getRandAlphanum(). + + \sa QJsonWebToken::getRandLength(). + \sa QJsonWebToken::getRandAlphanum(). + + */ + void setRandomSecret(); + + /** + + \brief Returns the JWT *algorithm* as a QString. + \return JWT *algorithm* as a QString. + + */ + QString getAlgorithmStr(); + + /** + + \brief Sets the JWT *algorithm* from a QString. + \param strAlgorithm JWT *algorithm* as a QString. + \return true if the algorithm was set, false if the algorithm was not set. + + This method checks for a valid supported algorithm. Valid values are: + + "HS256", "HS384" and "HS512". + + \sa QJsonWebToken::supportedAlgorithms(). + + */ + bool setAlgorithmStr(QString strAlgorithm); + + /** + + \brief Returns the complete JWT as a QString. + \return Complete JWT as a QString. + + The token has the form: + + ``` + xxxxx.yyyyy.zzzzz + ``` + + where: + + - *xxxxx* is the *header* enconded in base64. + - *yyyyy* is the *payload* enconded in base64. + - *zzzzz* is the *signature* enconded in base64. + + */ + QString getToken(); + + /** + + \brief Sets the complete JWT as a QString. + \param strToken Complete JWT as a QString. + \return true if the complete JWT was set, false if not set. + + This method checks for a valid JWT format. It overwrites the *header*, + *payload* , *signature* and *algorithm*. It does **not** overwrite the secret. + + \sa QJsonWebToken::getToken(). + + */ + bool setToken(QString strToken); + + /** + + \brief Returns the current set of characters used to create random secrets. + \return Set of characters as a QString. + + The default value is "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + \sa QJsonWebToken::setRandomSecret() + \sa QJsonWebToken::setRandAlphanum() + + */ + QString getRandAlphanum(); + + /** + + \brief Sets the current set of characters used to create random secrets. + \param strRandAlphanum Set of characters as a QString. + + \sa QJsonWebToken::setRandomSecret() + \sa QJsonWebToken::getRandAlphanum() + + */ + void setRandAlphanum(QString strRandAlphanum); + + /** + + \brief Returns the current length used to create random secrets. + \return Length of random secret as a QString. + + The default value is 10; + + \sa QJsonWebToken::setRandomSecret() + \sa QJsonWebToken::setRandLength() + + */ + int getRandLength(); + + /** + + \brief Sets the current length used to create random secrets. + \param intRandLength Length of random secret. + + \sa QJsonWebToken::setRandomSecret() + \sa QJsonWebToken::getRandLength() + + */ + void setRandLength(int intRandLength); + + /** + + \brief Checks validity of current JWT with respect to secret. + \return true if the JWT is valid with respect to secret, else false. + + Uses the current *secret* to calculate a temporary *signature* and compares it to the + current signature to check if they are the same. If they are, true is returned, if not then + false is returned. + + */ + bool isValid(); + + /** + + \brief Creates a QJsonWebToken instance from the complete JWT and a secret. + \param strToken Complete JWT as a QString. + \param srtSecret Secret as a QString. + \return Instance of QJsonWebToken. + + The JWT provided must have a valid format, else a QJsonWebToken instance with default + values will be returned. + + */ + static QJsonWebToken fromTokenAndSecret(QString strToken, QString srtSecret); + + /** + + \brief Returns a list of the supported algorithms. + \return List of supported algorithms as a QStringList. + + */ + static QStringList supportedAlgorithms(); + + /** + + \brief Convenience method to append a claim to the *payload*. + \param strClaimType The claim type as a QString. + \param strValue The value type as a QString. + + Both parameters must be non-empty. If the claim type already exists, the current + claim value is updated. + + */ + void appendClaim(QString strClaimType, QString strValue); + + /** + + \brief Convenience method to remove a claim from the *payload*. + \param strClaimType The claim type as a QString. + + If the claim type does not exist in the *payload*, then this method does nothins. + + */ + void removeClaim(QString strClaimType); + +private: + // properties + QJsonDocument m_jdocHeader; // unencoded + QJsonDocument m_jdocPayload; // unencoded + QByteArray m_byteSignature; // unencoded + QString m_strSecret; + QString m_strAlgorithm; + + int m_intRandLength ; + QString m_strRandAlphanum; + + // helpers + QByteArray m_byteAllData; + + bool isAlgorithmSupported(QString strAlgorithm); +}; + +#endif // QJSONWEBTOKEN_H diff --git a/src/Airmap/QJsonWebToken/src/qjsonwebtoken.pri b/src/Airmap/QJsonWebToken/src/qjsonwebtoken.pri new file mode 100644 index 000000000..3efe5d61f --- /dev/null +++ b/src/Airmap/QJsonWebToken/src/qjsonwebtoken.pri @@ -0,0 +1,7 @@ +CONFIG -= flat + +INCLUDEPATH += $$PWD/ + +SOURCES += $$PWD/qjsonwebtoken.cpp + +HEADERS += $$PWD/qjsonwebtoken.h -- 2.22.0