diff options
author | Sara Golemon <sara.golemon@mongodb.com> | 2020-01-13 20:38:27 +0000 |
---|---|---|
committer | Evergreen Agent <no-reply@evergreen.mongodb.com> | 2020-02-04 19:03:40 +0000 |
commit | 3ca76fd569c94de72c4daf6eef27fbf9bf51233b (patch) | |
tree | df08c2e3416475ea70867eb64673ce210ffef150 /src | |
parent | d3262e58c914fd0b5689069c7e8950c508cf1b4a (diff) | |
download | mongo-3ca76fd569c94de72c4daf6eef27fbf9bf51233b.tar.gz |
SERVER-44435 Allow selective whitelisting of X509 based role authorizations
(cherry picked from commit b99fbe5f80f4368e1916e1bfbf3d195276ace5c7)
create mode 100644 jstests/libs/client_roles.pem
create mode 100644 jstests/ssl/tlsCATrusts.js
create mode 100644 jstests/ssl/x509/root-and-trusted-ca.pem
create mode 100644 jstests/ssl/x509/trusted-client-testdb-roles.pem
create mode 100644 src/mongo/db/auth/auth_types.idl
create mode 100644 src/mongo/util/net/ssl_parameters.cpp
create mode 100644 src/mongo/util/net/ssl_parameters.idl
Diffstat (limited to 'src')
-rw-r--r-- | src/mongo/bson/json.cpp | 7 | ||||
-rw-r--r-- | src/mongo/bson/oid.cpp | 2 | ||||
-rw-r--r-- | src/mongo/client/mongo_uri.cpp | 6 | ||||
-rw-r--r-- | src/mongo/crypto/sha1_block.idl | 7 | ||||
-rw-r--r-- | src/mongo/crypto/sha256_block.idl | 7 | ||||
-rw-r--r-- | src/mongo/crypto/sha_block.h | 27 | ||||
-rw-r--r-- | src/mongo/db/auth/auth_types.idl | 44 | ||||
-rw-r--r-- | src/mongo/db/auth/role_name.cpp | 34 | ||||
-rw-r--r-- | src/mongo/db/auth/role_name.h | 9 | ||||
-rw-r--r-- | src/mongo/db/storage/key_string_test.cpp | 2 | ||||
-rw-r--r-- | src/mongo/platform/decimal128_bson_test.cpp | 2 | ||||
-rw-r--r-- | src/mongo/scripting/mozjs/bindata.cpp | 2 | ||||
-rw-r--r-- | src/mongo/util/hex.h | 47 | ||||
-rw-r--r-- | src/mongo/util/net/SConscript | 5 | ||||
-rw-r--r-- | src/mongo/util/net/ssl_manager.cpp | 71 | ||||
-rw-r--r-- | src/mongo/util/net/ssl_options.h | 20 | ||||
-rw-r--r-- | src/mongo/util/net/ssl_parameters.cpp | 151 | ||||
-rw-r--r-- | src/mongo/util/net/ssl_parameters.idl | 44 | ||||
-rw-r--r-- | src/mongo/util/uuid.cpp | 6 |
19 files changed, 470 insertions, 23 deletions
diff --git a/src/mongo/bson/json.cpp b/src/mongo/bson/json.cpp index 55ac254fa09..8f6653f3b29 100644 --- a/src/mongo/bson/json.cpp +++ b/src/mongo/bson/json.cpp @@ -403,7 +403,8 @@ Status JParse::binaryObject(StringData fieldName, BSONObjBuilder& builder) { // unsigned char. If we don't coerce it to an unsigned char before // wrapping it in a BinDataType (currently implicitly a signed // integer), we get undefined behavior. - const auto binDataTypeNumeric = static_cast<unsigned char>(fromHex(binDataType)); + const auto binDataTypeSigned = uassertStatusOK(fromHex(binDataType)); + const auto binDataTypeNumeric = static_cast<unsigned char>(binDataTypeSigned); builder.appendBinData( fieldName, binData.length(), BinDataType(binDataTypeNumeric), binData.data()); @@ -1153,8 +1154,8 @@ Status JParse::chars(std::string* result, const char* terminalSet, const char* a if (!isHexString(StringData(q, 4))) { return parseError("Expecting 4 hex digits"); } - unsigned char first = fromHex(q); - unsigned char second = fromHex(q += 2); + unsigned char first = uassertStatusOK(fromHex(q)); + unsigned char second = uassertStatusOK(fromHex(q += 2)); const std::string& utf8str = encodeUTF8(first, second); for (unsigned int i = 0; i < utf8str.size(); i++) { result->push_back(utf8str[i]); diff --git a/src/mongo/bson/oid.cpp b/src/mongo/bson/oid.cpp index 55e5cffdf21..b309f59639c 100644 --- a/src/mongo/bson/oid.cpp +++ b/src/mongo/bson/oid.cpp @@ -154,7 +154,7 @@ void OID::init(const std::string& s) { verify(s.size() == 24); const char* p = s.c_str(); for (std::size_t i = 0; i < kOIDSize; i++) { - _data[i] = fromHex(p); + _data[i] = uassertStatusOK(fromHex(p)); p += 2; } } diff --git a/src/mongo/client/mongo_uri.cpp b/src/mongo/client/mongo_uri.cpp index f85ea5482a3..6ddd6f7b940 100644 --- a/src/mongo/client/mongo_uri.cpp +++ b/src/mongo/client/mongo_uri.cpp @@ -92,7 +92,11 @@ mongo::StatusWith<std::string> mongo::uriDecode(StringData toDecode) { return Status(ErrorCodes::FailedToParse, "Encountered partial escape sequence at end of string"); } - out << fromHex(toDecode.substr(i + 1, 2)); + auto swHex = fromHex(toDecode.substr(i + 1, 2)); + if (!swHex.isOK()) { + return swHex.getStatus(); + } + out << swHex.getValue(); i += 2; } else { out << c; diff --git a/src/mongo/crypto/sha1_block.idl b/src/mongo/crypto/sha1_block.idl index d6054d9e3f6..59ddbbeca61 100644 --- a/src/mongo/crypto/sha1_block.idl +++ b/src/mongo/crypto/sha1_block.idl @@ -44,3 +44,10 @@ types: cpp_type: mongo::SHA1Block serializer: "mongo::SHA1Block::toCDR" deserializer: "mongo::SHA1Block::fromBinData" + + sha1BlockHex: + bson_serialization_type: string + description: "A fixed size hex string representing a SHA1 computation" + cpp_type: mongo::SHA1Block + serializer: "mongo::SHA1Block::toHexString" + deserializer: "mongo::SHA1Block::fromHexString" diff --git a/src/mongo/crypto/sha256_block.idl b/src/mongo/crypto/sha256_block.idl index 734983f286a..a5b4a1cef41 100644 --- a/src/mongo/crypto/sha256_block.idl +++ b/src/mongo/crypto/sha256_block.idl @@ -44,3 +44,10 @@ types: cpp_type: mongo::SHA256Block serializer: "mongo::SHA256Block::toCDR" deserializer: "mongo::SHA256Block::fromBinData" + + sha256BlockHex: + bson_serialization_type: string + description: "A fixed size hex string representing a SHA256 computation" + cpp_type: mongo::SHA256Block + serializer: "mongo::SHA256Block::toHexString" + deserializer: "mongo::SHA256Block::fromHexString" diff --git a/src/mongo/crypto/sha_block.h b/src/mongo/crypto/sha_block.h index 2860fe7fb1d..267d71cb163 100644 --- a/src/mongo/crypto/sha_block.h +++ b/src/mongo/crypto/sha_block.h @@ -40,7 +40,9 @@ #include "mongo/base/status_with.h" #include "mongo/bson/bsonmisc.h" #include "mongo/bson/bsonobjbuilder.h" +#include "mongo/bson/util/builder.h" #include "mongo/util/base64.h" +#include "mongo/util/hex.h" #include "mongo/util/secure_compare_memory.h" namespace mongo { @@ -77,6 +79,20 @@ public: return SHABlock(newHash); } + static StatusWith<SHABlock> fromHexStringNoThrow(StringData hex) { + if (!isValidHex(hex)) { + return {ErrorCodes::BadValue, "Hash input is not a hex string"}; + } + + BufBuilder buf; + mongo::fromHexString(hex, &buf); + return fromBuffer(reinterpret_cast<const uint8_t*>(buf.buf()), buf.len()); + } + + static SHABlock fromHexString(StringData hex) { + return uassertStatusOK(fromHexStringNoThrow(hex)); + } + /** * Computes a hash of 'input' from multiple contigous buffers. */ @@ -187,6 +203,13 @@ public: return base64::encode(reinterpret_cast<const char*>(_hash.data()), _hash.size()); } + /** + * Hex encoded hash block. + */ + std::string toHexString() const { + return toHex(_hash.data(), _hash.size()); + } + bool operator==(const SHABlock& other) const { return consttimeMemEqual(this->_hash.data(), other._hash.data(), kHashLength); } @@ -195,6 +218,10 @@ public: return !(*this == other); } + bool operator<(const SHABlock& other) const { + return this->_hash < other._hash; + } + /** * Custom hasher so SHABlocks can be used in unordered data structures. * diff --git a/src/mongo/db/auth/auth_types.idl b/src/mongo/db/auth/auth_types.idl new file mode 100644 index 00000000000..aae786f5b53 --- /dev/null +++ b/src/mongo/db/auth/auth_types.idl @@ -0,0 +1,44 @@ +# Copyright (C) 2020-present MongoDB, Inc. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the Server Side Public License, version 1, +# as published by MongoDB, Inc. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# Server Side Public License for more details. +# +# You should have received a copy of the Server Side Public License +# along with this program. If not, see +# <http://www.mongodb.com/licensing/server-side-public-license>. +# +# As a special exception, the copyright holders give permission to link the +# code of portions of this program with the OpenSSL library under certain +# conditions as described in each individual source file and distribute +# linked combinations including the program with the OpenSSL library. You +# must comply with the Server Side Public License in all respects for +# all of the code used other than as permitted herein. If you modify file(s) +# with this exception, you may extend this exception to your version of the +# file(s), but you are not obligated to do so. If you do not wish to do so, +# delete this exception statement from your version. If you delete this +# exception statement from all source files in the program, then also delete +# it in the license file. +# + +global: + cpp_namespace: "mongo" + cpp_includes: + - "mongo/db/auth/role_name.h" + +imports: + - "mongo/idl/basic_types.idl" + +types: + + RoleName: + bson_serialization_type: any + description: "A struct representing a Role" + cpp_type: "RoleName" + deserializer: "mongo::RoleName::parseFromBSON" + serializer: "mongo::RoleName::serializeToBSON" diff --git a/src/mongo/db/auth/role_name.cpp b/src/mongo/db/auth/role_name.cpp index d05c623463a..d3c16e771bb 100644 --- a/src/mongo/db/auth/role_name.cpp +++ b/src/mongo/db/auth/role_name.cpp @@ -35,6 +35,7 @@ #include <string> #include "mongo/base/string_data.h" +#include "mongo/db/auth/authorization_manager.h" #include "mongo/util/assert_util.h" namespace mongo { @@ -54,4 +55,37 @@ std::ostream& operator<<(std::ostream& os, const RoleName& name) { return os << name.getFullName(); } +RoleName RoleName::parseFromBSON(const BSONElement& elem) { + auto obj = elem.embeddedObjectUserCheck(); + std::array<BSONElement, 2> fields; + obj.getFields({"role", "db"}, &fields); + const auto& nameField = fields[0]; + uassert(ErrorCodes::BadValue, + "user name must contain a string field named: role", + nameField.type() == String); + + const auto& dbField = fields[1]; + uassert(ErrorCodes::BadValue, + "role name must contain a string field named: db", + nameField.type() == String); + + return RoleName(nameField.valueStringData(), dbField.valueStringData()); +} + +void RoleName::serializeToBSON(StringData fieldName, BSONObjBuilder* bob) const { + BSONObjBuilder sub(bob->subobjStart(fieldName)); + _serializeToSubObj(&sub); +} + +void RoleName::serializeToBSON(BSONArrayBuilder* bob) const { + BSONObjBuilder sub(bob->subobjStart()); + _serializeToSubObj(&sub); +} + +void RoleName::_serializeToSubObj(BSONObjBuilder* sub) const { + sub->append("role", getRole()); + sub->append("db", getDB()); +} + + } // namespace mongo diff --git a/src/mongo/db/auth/role_name.h b/src/mongo/db/auth/role_name.h index 99fdeee9489..d335998c9e0 100644 --- a/src/mongo/db/auth/role_name.h +++ b/src/mongo/db/auth/role_name.h @@ -38,6 +38,8 @@ #include "mongo/base/disallow_copying.h" #include "mongo/base/string_data.h" +#include "mongo/bson/bsonelement.h" +#include "mongo/bson/bsonobjbuilder.h" #include "mongo/platform/hash_namespace.h" #include "mongo/util/assert_util.h" @@ -53,6 +55,11 @@ public: RoleName() : _splitPoint(0) {} RoleName(StringData role, StringData dbname); + // Added for IDL support + static RoleName parseFromBSON(const BSONElement& elem); + void serializeToBSON(StringData fieldName, BSONObjBuilder* bob) const; + void serializeToBSON(BSONArrayBuilder* bob) const; + /** * Gets the name of the role excluding the "@dbname" component. */ @@ -90,6 +97,8 @@ public: private: std::string _fullName; // The full name, stored as a string. "role@db". size_t _splitPoint; // The index of the "@" separating the role and db name parts. + + void _serializeToSubObj(BSONObjBuilder* sub) const; }; static inline bool operator==(const RoleName& lhs, const RoleName& rhs) { diff --git a/src/mongo/db/storage/key_string_test.cpp b/src/mongo/db/storage/key_string_test.cpp index 6ac51bfd191..444608e2477 100644 --- a/src/mongo/db/storage/key_string_test.cpp +++ b/src/mongo/db/storage/key_string_test.cpp @@ -167,7 +167,7 @@ TEST_F(KeyStringTest, ActualBytesDouble) { // last byte (kEnd) doesn't get flipped string hexFlipped; for (size_t i = 0; i < hex.size() - 2; i += 2) { - char c = fromHex(hex.c_str() + i); + char c = uassertStatusOK(fromHex(hex.c_str() + i)); c = ~c; hexFlipped += toHex(&c, 1); } diff --git a/src/mongo/platform/decimal128_bson_test.cpp b/src/mongo/platform/decimal128_bson_test.cpp index aac4ab22283..24bbef73836 100644 --- a/src/mongo/platform/decimal128_bson_test.cpp +++ b/src/mongo/platform/decimal128_bson_test.cpp @@ -58,7 +58,7 @@ BSONObj convertHexStringToBsonObj(StringData hexString) { auto buffer = SharedBuffer::allocate(bufferSize); for (unsigned int i = 0; i < bufferSize; i++) { - buffer.get()[i] = fromHex(p); + buffer.get()[i] = uassertStatusOK(fromHex(p)); p += 2; } diff --git a/src/mongo/scripting/mozjs/bindata.cpp b/src/mongo/scripting/mozjs/bindata.cpp index 26d2371609f..ddf5df2ba1d 100644 --- a/src/mongo/scripting/mozjs/bindata.cpp +++ b/src/mongo/scripting/mozjs/bindata.cpp @@ -88,7 +88,7 @@ void hexToBinData(JSContext* cx, int src_index = i * 2; if (!std::isxdigit(src[src_index]) || !std::isxdigit(src[src_index + 1])) uasserted(ErrorCodes::BadValue, "Invalid hex character in string"); - data[i] = fromHex(src + src_index); + data[i] = uassertStatusOK(fromHex(src + src_index)); } std::string encoded = base64::encode(data.get(), len); diff --git a/src/mongo/util/hex.h b/src/mongo/util/hex.h index 322d02d5be3..6a89388a245 100644 --- a/src/mongo/util/hex.h +++ b/src/mongo/util/hex.h @@ -32,28 +32,61 @@ #pragma once +#include <cctype> #include <string> #include "mongo/base/string_data.h" #include "mongo/bson/util/builder.h" +#include "mongo/util/mongoutils/str.h" namespace mongo { // can't use hex namespace because it conflicts with hex iostream function -inline int fromHex(char c) { +inline StatusWith<char> fromHex(char c) { if ('0' <= c && c <= '9') return c - '0'; if ('a' <= c && c <= 'f') return c - 'a' + 10; if ('A' <= c && c <= 'F') return c - 'A' + 10; - verify(false); - return 0xff; + return Status(ErrorCodes::FailedToParse, + str::stream() << "The character " << c << " failed to parse from hex."); } -inline char fromHex(const char* c) { - return (char)((fromHex(c[0]) << 4) | fromHex(c[1])); +inline StatusWith<char> fromHex(const char* c) { + if (fromHex(c[0]).isOK() && fromHex(c[1]).isOK()) { + return (char)((fromHex(c[0]).getValue() << 4) | fromHex(c[1]).getValue()); + } + return Status(ErrorCodes::FailedToParse, + str::stream() << "The character " << c[0] << c[1] + << " failed to parse from hex."); +} +inline StatusWith<char> fromHex(StringData c) { + if (fromHex(c[0]).isOK() && fromHex(c[1]).isOK()) { + return (char)((fromHex(c[0]).getValue() << 4) | fromHex(c[1]).getValue()); + } + return Status(ErrorCodes::FailedToParse, + str::stream() << "The character " << c[0] << c[1] + << " failed to parse from hex."); } -inline char fromHex(StringData c) { - return (char)((fromHex(c[0]) << 4) | fromHex(c[1])); + +/** + * Decodes 'hexString' into raw bytes, appended to the out parameter 'buf'. Callers must first + * ensure that 'hexString' is a valid hex encoding. + */ +inline void fromHexString(StringData hexString, BufBuilder* buf) { + invariant(hexString.size() % 2 == 0); + // Combine every pair of two characters into one byte. + for (std::size_t i = 0; i < hexString.size(); i += 2) { + buf->appendChar(uassertStatusOK(fromHex(StringData(&hexString.rawData()[i], 2)))); + } +} + +/** + * Returns true if 'hexString' is a valid hexadecimal encoding. + */ +inline bool isValidHex(StringData hexString) { + // There must be an even number of characters, since each pair encodes a single byte. + return hexString.size() % 2 == 0 && + std::all_of(hexString.begin(), hexString.end(), [](char c) { return std::isxdigit(c); }); } inline std::string toHex(const void* inRaw, int len) { diff --git a/src/mongo/util/net/SConscript b/src/mongo/util/net/SConscript index c120b65990f..b80beed6dc6 100644 --- a/src/mongo/util/net/SConscript +++ b/src/mongo/util/net/SConscript @@ -22,7 +22,9 @@ env.Library( "socket_exception.cpp", "ssl_manager.cpp", "ssl_options.cpp", + "ssl_parameters.cpp", "thread_idle_callback.cpp", + env.Idlc('ssl_parameters.idl')[0], ], LIBDEPS=[ '$BUILD_DIR/mongo/base', @@ -33,6 +35,9 @@ env.Library( LIBDEPS_PRIVATE=[ '$BUILD_DIR/mongo/db/bson/dotted_path_support', '$BUILD_DIR/mongo/db/server_options_core', + '$BUILD_DIR/mongo/db/server_parameters', + '$BUILD_DIR/mongo/crypto/sha256_block', + '$BUILD_DIR/mongo/idl/idl_parser', '$BUILD_DIR/mongo/util/background_job', '$BUILD_DIR/mongo/util/fail_point', '$BUILD_DIR/mongo/util/options_parser/options_parser', diff --git a/src/mongo/util/net/ssl_manager.cpp b/src/mongo/util/net/ssl_manager.cpp index 70854fd0a50..3ad394a05f1 100644 --- a/src/mongo/util/net/ssl_manager.cpp +++ b/src/mongo/util/net/ssl_manager.cpp @@ -88,6 +88,7 @@ std::string removeFQDNRoot(std::string name) { return name; }; +#ifdef MONGO_CONFIG_SSL struct UniqueX509StoreCtxDeleter { void operator()(X509_STORE_CTX* ctx) { if (ctx) { @@ -96,6 +97,7 @@ struct UniqueX509StoreCtxDeleter { } }; using UniqueX509StoreCtx = std::unique_ptr<X509_STORE_CTX, UniqueX509StoreCtxDeleter>; +#endif // Because the hostname having a slash is used by `mongo::SockAddr` to determine if a hostname is a // Unix Domain Socket endpoint, this function uses the same logic. (See @@ -1582,6 +1584,68 @@ StatusWith<TLSVersion> mapTLSVersion(const SSL* conn) { } } +namespace { +Status _validatePeerRoles(const stdx::unordered_set<RoleName>& embeddedRoles, SSL* conn) { + if (embeddedRoles.empty()) { + // Nothing offered, nothing to restrict. + return Status::OK(); + } + + if (!sslGlobalParams.tlsCATrusts) { + // Nothing restricted. + return Status::OK(); + } + + const auto& tlsCATrusts = sslGlobalParams.tlsCATrusts.get(); + if (tlsCATrusts.empty()) { + // Nothing permitted. + return {ErrorCodes::BadValue, + "tlsCATrusts parameter prohibits role based authorization via X509 certificates"}; + } + + auto stack = SSLgetVerifiedChain(conn); + if (!stack || !sk_X509_num(stack.get())) { + return {ErrorCodes::BadValue, "Unable to obtain certificate chain"}; + } + + auto root = sk_X509_value(stack.get(), sk_X509_num(stack.get()) - 1); + SHA256Block::HashType digest; + if (!X509_digest(root, EVP_sha256(), digest.data(), nullptr)) { + return {ErrorCodes::BadValue, "Unable to digest root certificate"}; + } + + SHA256Block sha256(digest); + auto it = tlsCATrusts.find(sha256); + if (it == tlsCATrusts.end()) { + return { + ErrorCodes::BadValue, + str::stream() << "CA: " << sha256.toHexString() + << " is not authorized to grant any roles due to tlsCATrusts parameter"}; + } + + auto allowedRoles = it->second; + // See TLSCATrustsSetParameter::set() for a description of tlsCATrusts format. + if (allowedRoles.count(RoleName("", ""))) { + // CA is authorized for all role assignments. + return Status::OK(); + } + + for (const auto& role : embeddedRoles) { + // Check for exact match or wildcard matches. + if (!allowedRoles.count(role) && !allowedRoles.count(RoleName(role.getRole(), "")) && + !allowedRoles.count(RoleName("", role.getDB()))) { + return {ErrorCodes::BadValue, + str::stream() << "CA: " << sha256.toHexString() + << " is not authorized to grant role " + << role.toString() + << " due to tlsCATrusts parameter"}; + } + } + + return Status::OK(); +} +} // namespace + StatusWith<SSLPeerInfo> SSLManager::parseAndValidatePeerCertificate( SSL* conn, const std::string& remoteHost, const HostAndPort& hostForLogging) { auto sniName = getRawSNIServerName(conn); @@ -1639,6 +1703,13 @@ StatusWith<SSLPeerInfo> SSLManager::parseAndValidatePeerCertificate( return swPeerCertificateRoles.getStatus(); } + { + auto status = _validatePeerRoles(swPeerCertificateRoles.getValue(), conn); + if (!status.isOK()) { + return status; + } + } + // If this is an SSL client context (on a MongoDB server or client) // perform hostname validation of the remote server if (remoteHost.empty()) { diff --git a/src/mongo/util/net/ssl_options.h b/src/mongo/util/net/ssl_options.h index 5684e37636e..c95a3e728ad 100644 --- a/src/mongo/util/net/ssl_options.h +++ b/src/mongo/util/net/ssl_options.h @@ -32,9 +32,14 @@ #include "mongo/util/net/ssl_manager.h" +#include <boost/optional.hpp> +#include <map> +#include <set> #include <vector> #include "mongo/base/status.h" +#include "mongo/crypto/sha256_block.h" +#include "mongo/db/auth/role_name.h" namespace mongo { @@ -44,6 +49,8 @@ class Environment; } // namespace optionenvironment struct SSLParams { + using TLSCATrusts = std::map<SHA256Block, std::set<RoleName>>; + enum class Protocols { TLS1_0, TLS1_1, TLS1_2, TLS1_3 }; AtomicInt32 sslMode; // --sslMode - the TLS operation mode, see enum SSLModes std::string sslPEMTempDHParam; // --setParameter OpenSSLDiffieHellmanParameters=file : PEM file @@ -51,11 +58,14 @@ struct SSLParams { std::string sslPEMKeyFile; // --sslPEMKeyFile std::string sslPEMKeyPassword; // --sslPEMKeyPassword std::string sslClusterFile; // --sslInternalKeyFile - std::string sslClusterPassword; // --sslInternalKeyPassword - std::string sslCAFile; // --sslCAFile - std::string sslClusterCAFile; // --sslClusterCAFile - std::string sslCRLFile; // --sslCRLFile - std::string sslCipherConfig; // --sslCipherConfig + std::string sslClusterPassword; // --sslInternalKeyPassword + std::string sslCAFile; // --sslCAFile + std::string sslClusterCAFile; // --sslClusterCAFile + std::string sslCRLFile; // --sslCRLFile + std::string sslCipherConfig; // --sslCipherConfig + + boost::optional<TLSCATrusts> tlsCATrusts; // --setParameter tlsCATrusts + std::vector<Protocols> sslDisabledProtocols; // --sslDisabledProtocols std::vector<Protocols> tlsLogVersions; // --tlsLogVersion bool sslWeakCertificateValidation = false; // --sslWeakCertificateValidation diff --git a/src/mongo/util/net/ssl_parameters.cpp b/src/mongo/util/net/ssl_parameters.cpp new file mode 100644 index 00000000000..ed1d4c64fe8 --- /dev/null +++ b/src/mongo/util/net/ssl_parameters.cpp @@ -0,0 +1,151 @@ + +/** + * Copyright (C) 2018-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#include "mongo/platform/basic.h" + +#include "mongo/bson/json.h" +#include "mongo/config.h" +#include "mongo/db/server_options.h" +#include "mongo/db/server_parameters.h" +#include "mongo/util/net/ssl_manager.h" +#include "mongo/util/net/ssl_options.h" +#include "mongo/util/net/ssl_parameters_gen.h" + +namespace mongo { + +namespace { + +class TLSCATrustsSetParameter : public ServerParameter { +public: + TLSCATrustsSetParameter() + : ServerParameter(ServerParameterSet::getGlobal(), + "tlsCATrusts", + true, // allowedToChangeAtStartup + false // allowedToChangeAtRuntime + ) {} + + void append(OperationContext*, BSONObjBuilder&, const std::string&) final; + Status set(const BSONElement&) final; + Status setFromString(const std::string&) final; +} tlsCATrustsSetParameter; + +void TLSCATrustsSetParameter::append(OperationContext*, + BSONObjBuilder& b, + const std::string& name) { + if (!sslGlobalParams.tlsCATrusts) { + b.appendNull(name); + return; + } + + BSONArrayBuilder trusts; + + for (const auto& cait : sslGlobalParams.tlsCATrusts.get()) { + BSONArrayBuilder roles; + + for (const auto& rolename : cait.second) { + BSONObjBuilder role; + role.append("role", rolename.getRole()); + role.append("db", rolename.getDB()); + roles.append(role.obj()); + } + + BSONObjBuilder ca; + ca.append("sha256", cait.first.toHexString()); + ca.append("roles", roles.arr()); + + trusts.append(ca.obj()); + } + + b.append(name, trusts.arr()); +} + +/** + * tlsCATrusts takes the form of an array of documents describing + * a set of roles which a given certificate authority may grant. + * + * [ + * { + * "sha256": "0123456789abcdef...", // SHA256 digest of a CA, as hex. + * "roles": [ // Array of grantable RoleNames + * { role: "read", db: "foo" }, + * { role: "readWrite", "db: "bar" }, + * // etc... + * ], + * }, + * // { "sha256": "...", roles: [...]}, // Additional documents... + * ] + * + * If this list has been set, and a client connects with a certificate + * containing roles which it has not been authorized to grant, + * then the connection will be refused. + * + * Wilcard roles may be defined by omitting the role and/or db portions: + * + * { role: "", db: "foo" } // May grant any role on the 'foo' DB. + * { role: "read", db: "" } // May grant 'read' role on any DB. + * { role: "", db: "" } // May grant any role on any DB. + */ +Status TLSCATrustsSetParameter::set(const BSONElement& element) try { + if ((element.type() != Object) || !element.Obj().couldBeArray()) { + return {ErrorCodes::BadValue, "Value must be an array"}; + } + + SSLParams::TLSCATrusts trusts; + for (const auto& trustElement : BSONArray(element.Obj())) { + if (trustElement.type() != Object) { + return {ErrorCodes::BadValue, "Value must be an array of trust definitions"}; + } + + IDLParserErrorContext ctx("tlsCATrusts"); + auto trust = TLSCATrust::parse(ctx, trustElement.Obj()); + + if (trusts.find(trust.getSha256()) != trusts.end()) { + return {ErrorCodes::BadValue, + str::stream() << "Duplicate thumbprint: " << trust.getSha256().toString()}; + } + + const auto& roles = trust.getRoles(); + trusts[std::move(trust.getSha256())] = std::set<RoleName>(roles.begin(), roles.end()); + } + + sslGlobalParams.tlsCATrusts = std::move(trusts); + return Status::OK(); +} catch (...) { + return exceptionToStatus(); +} + +Status TLSCATrustsSetParameter::setFromString(const std::string& json) try { + return set(BSON("" << fromjson(json)).firstElement()); +} catch (...) { + return exceptionToStatus(); +} + +} // namespace +} // namespace mongo diff --git a/src/mongo/util/net/ssl_parameters.idl b/src/mongo/util/net/ssl_parameters.idl new file mode 100644 index 00000000000..21d376a7bc2 --- /dev/null +++ b/src/mongo/util/net/ssl_parameters.idl @@ -0,0 +1,44 @@ +# Copyright (C) 2020-present MongoDB, Inc. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the Server Side Public License, version 1, +# as published by MongoDB, Inc. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# Server Side Public License for more details. +# +# You should have received a copy of the Server Side Public License +# along with this program. If not, see +# <http://www.mongodb.com/licensing/server-side-public-license>. +# +# As a special exception, the copyright holders give permission to link the +# code of portions of this program with the OpenSSL library under certain +# conditions as described in each individual source file and distribute +# linked combinations including the program with the OpenSSL library. You +# must comply with the Server Side Public License in all respects for +# all of the code used other than as permitted herein. If you modify file(s) +# with this exception, you may extend this exception to your version of the +# file(s), but you are not obligated to do so. If you do not wish to do so, +# delete this exception statement from your version. If you delete this +# exception statement from all source files in the program, then also delete +# it in the license file. +# + +global: + cpp_namespace: "mongo" + cpp_includes: + - "mongo/util/net/ssl_options.h" + +imports: + - "mongo/crypto/sha256_block.idl" + - "mongo/db/auth/auth_types.idl" + +structs: + TLSCATrust: + description: + strict: true + fields: + sha256: sha256BlockHex + roles: array<RoleName> diff --git a/src/mongo/util/uuid.cpp b/src/mongo/util/uuid.cpp index 208688ddcce..99109a630d7 100644 --- a/src/mongo/util/uuid.cpp +++ b/src/mongo/util/uuid.cpp @@ -74,10 +74,10 @@ StatusWith<UUID> UUID::parse(const std::string& s) { if (s[j] == '-') j++; - char high = s[j++]; - char low = s[j++]; + auto high = uassertStatusOK(fromHex(s[j++])); + auto low = uassertStatusOK(fromHex(s[j++])); - uuid[i] = ((fromHex(high) << 4) | fromHex(low)); + uuid[i] = ((high << 4) | low); } return UUID{std::move(uuid)}; |