diff options
Diffstat (limited to 'src/mongo/util/net')
-rw-r--r-- | src/mongo/util/net/hostname_canonicalization.cpp | 14 | ||||
-rw-r--r-- | src/mongo/util/net/openssl_init.cpp | 12 | ||||
-rw-r--r-- | src/mongo/util/net/sock.cpp | 161 | ||||
-rw-r--r-- | src/mongo/util/net/sockaddr.cpp | 12 | ||||
-rw-r--r-- | src/mongo/util/net/socket_utils.cpp | 27 | ||||
-rw-r--r-- | src/mongo/util/net/ssl_manager.cpp | 46 | ||||
-rw-r--r-- | src/mongo/util/net/ssl_manager_apple.cpp | 21 | ||||
-rw-r--r-- | src/mongo/util/net/ssl_manager_openssl.cpp | 164 | ||||
-rw-r--r-- | src/mongo/util/net/ssl_manager_test.cpp | 18 | ||||
-rw-r--r-- | src/mongo/util/net/ssl_manager_windows.cpp | 56 | ||||
-rw-r--r-- | src/mongo/util/net/ssl_options_server.cpp | 11 |
11 files changed, 374 insertions, 168 deletions
diff --git a/src/mongo/util/net/hostname_canonicalization.cpp b/src/mongo/util/net/hostname_canonicalization.cpp index e3710912892..0e9f06d7e3c 100644 --- a/src/mongo/util/net/hostname_canonicalization.cpp +++ b/src/mongo/util/net/hostname_canonicalization.cpp @@ -41,6 +41,7 @@ #include <sys/types.h> #endif +#include "mongo/logv2/log.h" #include "mongo/util/log.h" #include "mongo/util/net/sockaddr.h" #include "mongo/util/scopeguard.h" @@ -90,8 +91,12 @@ std::vector<std::string> getHostFQDNs(std::string hostName, HostnameCanonicaliza int err; auto nativeHostName = shim_toNativeString(hostName.c_str()); if ((err = shim_getaddrinfo(nativeHostName.c_str(), nullptr, &hints, &info)) != 0) { - LOG(3) << "Failed to obtain address information for hostname " << hostName << ": " - << getAddrInfoStrError(err); + LOGV2_DEBUG(23170, + 3, + "Failed to obtain address information for hostname {hostName}: " + "{getAddrInfoStrError_err}", + "hostName"_attr = hostName, + "getAddrInfoStrError_err"_attr = getAddrInfoStrError(err)); return results; } const auto guard = makeGuard(shim_freeaddrinfo); @@ -141,7 +146,10 @@ std::vector<std::string> getHostFQDNs(std::string hostName, HostnameCanonicaliza } if (encounteredErrors) { - LOG(3) << getNameInfoErrors.str() << " ]"; + LOGV2_DEBUG(23171, + 3, + "{getNameInfoErrors_str} ]", + "getNameInfoErrors_str"_attr = getNameInfoErrors.str()); } // Deduplicate the results list diff --git a/src/mongo/util/net/openssl_init.cpp b/src/mongo/util/net/openssl_init.cpp index 8f05d3c877a..60096c06756 100644 --- a/src/mongo/util/net/openssl_init.cpp +++ b/src/mongo/util/net/openssl_init.cpp @@ -33,6 +33,7 @@ #include "mongo/base/init.h" #include "mongo/config.h" +#include "mongo/logv2/log.h" #include "mongo/util/log.h" #include "mongo/util/net/ssl_manager.h" #include "mongo/util/net/ssl_options.h" @@ -148,13 +149,16 @@ void setupFIPS() { #if defined(MONGO_CONFIG_HAVE_FIPS_MODE_SET) int status = FIPS_mode_set(1); if (!status) { - severe() << "can't activate FIPS mode: " - << SSLManagerInterface::getSSLErrorMessage(ERR_get_error()); + LOGV2_FATAL( + 23173, + "can't activate FIPS mode: {SSLManagerInterface_getSSLErrorMessage_ERR_get_error}", + "SSLManagerInterface_getSSLErrorMessage_ERR_get_error"_attr = + SSLManagerInterface::getSSLErrorMessage(ERR_get_error())); fassertFailedNoTrace(16703); } - log() << "FIPS 140-2 mode activated"; + LOGV2(23172, "FIPS 140-2 mode activated"); #else - severe() << "this version of mongodb was not compiled with FIPS support"; + LOGV2_FATAL(23174, "this version of mongodb was not compiled with FIPS support"); fassertFailedNoTrace(17089); #endif } diff --git a/src/mongo/util/net/sock.cpp b/src/mongo/util/net/sock.cpp index 03b626f4da1..fffe41871a3 100644 --- a/src/mongo/util/net/sock.cpp +++ b/src/mongo/util/net/sock.cpp @@ -57,6 +57,7 @@ #include "mongo/config.h" #include "mongo/db/server_options.h" +#include "mongo/logv2/log.h" #include "mongo/util/background.h" #include "mongo/util/concurrency/value.h" #include "mongo/util/debug_util.h" @@ -102,8 +103,13 @@ void networkWarnWithDescription(const Socket& socket, StringData call, int error } #endif auto ewd = errnoWithDescription(errorCode); - warning() << "Failed to connect to " << socket.remoteAddr().getAddr() << ":" - << socket.remoteAddr().getPort() << ", in(" << call << "), reason: " << ewd; + LOGV2_WARNING(23190, + "Failed to connect to {socket_remoteAddr_getAddr}:{socket_remoteAddr_getPort}, " + "in({call}), reason: {ewd}", + "socket_remoteAddr_getAddr"_attr = socket.remoteAddr().getAddr(), + "socket_remoteAddr_getPort"_attr = socket.remoteAddr().getPort(), + "call"_attr = call, + "ewd"_attr = ewd); } const double kMaxConnectTimeoutMS = 5000; @@ -115,21 +121,27 @@ void setSockTimeouts(int sock, double secs) { int status = setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<char*>(&timeout), sizeof(DWORD)); if (report && (status == SOCKET_ERROR)) - log() << "unable to set SO_RCVTIMEO: " << errnoWithDescription(WSAGetLastError()); + LOGV2(23177, + "unable to set SO_RCVTIMEO: {errnoWithDescription_WSAGetLastError}", + "errnoWithDescription_WSAGetLastError"_attr = + errnoWithDescription(WSAGetLastError())); status = setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<char*>(&timeout), sizeof(DWORD)); if (kDebugBuild && report && (status == SOCKET_ERROR)) - log() << "unable to set SO_SNDTIMEO: " << errnoWithDescription(WSAGetLastError()); + LOGV2(23178, + "unable to set SO_SNDTIMEO: {errnoWithDescription_WSAGetLastError}", + "errnoWithDescription_WSAGetLastError"_attr = + errnoWithDescription(WSAGetLastError())); #else struct timeval tv; tv.tv_sec = (int)secs; tv.tv_usec = (int)((long long)(secs * 1000 * 1000) % (1000 * 1000)); bool ok = setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv)) == 0; if (report && !ok) - log() << "unable to set SO_RCVTIMEO"; + LOGV2(23179, "unable to set SO_RCVTIMEO"); ok = setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(tv)) == 0; if (kDebugBuild && report && !ok) - log() << "unable to set SO_SNDTIMEO"; + LOGV2(23180, "unable to set SO_SNDTIMEO"); #endif } @@ -144,11 +156,15 @@ void disableNagle(int sock) { #endif if (setsockopt(sock, level, TCP_NODELAY, (char*)&x, sizeof(x))) - error() << "disableNagle failed: " << errnoWithDescription(); + LOGV2_ERROR(23195, + "disableNagle failed: {errnoWithDescription}", + "errnoWithDescription"_attr = errnoWithDescription()); #ifdef SO_KEEPALIVE if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&x, sizeof(x))) - error() << "SO_KEEPALIVE failed: " << errnoWithDescription(); + LOGV2_ERROR(23196, + "SO_KEEPALIVE failed: {errnoWithDescription}", + "errnoWithDescription"_attr = errnoWithDescription()); #endif setSocketKeepAliveParams(sock); @@ -166,8 +182,12 @@ SockAddr getLocalAddrForBoundSocketFd(int fd) { SockAddr result; int rc = getsockname(fd, result.raw(), &result.addressSize); if (rc != 0) { - warning() << "Could not resolve local address for socket with fd " << fd << ": " - << getAddrInfoStrError(socketGetLastError()); + LOGV2_WARNING(23191, + "Could not resolve local address for socket with fd {fd}: " + "{getAddrInfoStrError_socketGetLastError}", + "fd"_attr = fd, + "getAddrInfoStrError_socketGetLastError"_attr = + getAddrInfoStrError(socketGetLastError())); result = SockAddr(); } return result; @@ -337,9 +357,12 @@ bool Socket::connect(SockAddr& remote, Milliseconds connectTimeoutMillis) { #endif // No activity for the full duration of the timeout. if (pollReturn == 0) { - warning() << "Failed to connect to " << _remote.getAddr() << ":" - << _remote.getPort() << " after " << connectTimeoutMillis - << " milliseconds, giving up."; + LOGV2_WARNING(23192, + "Failed to connect to {remote_getAddr}:{remote_getPort} after " + "{connectTimeoutMillis} milliseconds, giving up.", + "remote_getAddr"_attr = _remote.getAddr(), + "remote_getPort"_attr = _remote.getPort(), + "connectTimeoutMillis"_attr = connectTimeoutMillis); return false; } @@ -549,18 +572,29 @@ void Socket::handleSendError(int ret, const char* context) { const int mongo_errno = errno; if ((mongo_errno == EAGAIN || mongo_errno == EWOULDBLOCK) && _timeout != 0) { #endif - LOG(_logLevel) << "Socket " << context << " send() timed out " << remoteString(); + LOGV2_DEBUG(23181, + logSeverityV1toV2(_logLevel).toInt(), + "Socket {context} send() timed out {remoteString}", + "context"_attr = context, + "remoteString"_attr = remoteString()); throwSocketError(SocketErrorKind::SEND_TIMEOUT, remoteString()); } else if (mongo_errno != EINTR) { - LOG(_logLevel) << "Socket " << context << " send() " << errnoWithDescription(mongo_errno) - << ' ' << remoteString(); + LOGV2_DEBUG(23182, + logSeverityV1toV2(_logLevel).toInt(), + "Socket {context} send() {errnoWithDescription_mongo_errno} {remoteString}", + "context"_attr = context, + "errnoWithDescription_mongo_errno"_attr = errnoWithDescription(mongo_errno), + "remoteString"_attr = remoteString()); throwSocketError(SocketErrorKind::SEND_ERROR, remoteString()); } } // namespace mongo void Socket::handleRecvError(int ret, int len) { if (ret == 0) { - LOG(3) << "Socket recv() conn closed? " << remoteString(); + LOGV2_DEBUG(23183, + 3, + "Socket recv() conn closed? {remoteString}", + "remoteString"_attr = remoteString()); throwSocketError(SocketErrorKind::CLOSED, remoteString()); } @@ -583,11 +617,18 @@ void Socket::handleRecvError(int ret, int len) { if (e == EAGAIN && _timeout > 0) { #endif // this is a timeout - LOG(_logLevel) << "Socket recv() timeout " << remoteString(); + LOGV2_DEBUG(23184, + logSeverityV1toV2(_logLevel).toInt(), + "Socket recv() timeout {remoteString}", + "remoteString"_attr = remoteString()); throwSocketError(SocketErrorKind::RECV_TIMEOUT, remoteString()); } - LOG(_logLevel) << "Socket recv() " << errnoWithDescription(e) << " " << remoteString(); + LOGV2_DEBUG(23185, + logSeverityV1toV2(_logLevel).toInt(), + "Socket recv() {errnoWithDescription_e} {remoteString}", + "errnoWithDescription_e"_attr = errnoWithDescription(e), + "remoteString"_attr = remoteString()); throwSocketError(SocketErrorKind::RECV_ERROR, remoteString()); } @@ -638,17 +679,26 @@ bool Socket::isStillConnected() { // Poll( info[], size, timeout ) - timeout == 0 => nonblocking int nEvents = socketPoll(&pollInfo, 1, 0); - LOG(2) << "polling for status of connection to " << remoteString() << ", " - << (nEvents == 0 ? "no events" : nEvents == -1 ? "error detected" : "event detected"); + LOGV2_DEBUG( + 23186, + 2, + "polling for status of connection to {remoteString}, " + "{nEvents_0_no_events_nEvents_1_error_detected_event_detected}", + "remoteString"_attr = remoteString(), + "nEvents_0_no_events_nEvents_1_error_detected_event_detected"_attr = + (nEvents == 0 ? "no events" : nEvents == -1 ? "error detected" : "event detected")); if (nEvents == 0) { // No events incoming, return still connected AFAWK return true; } else if (nEvents < 0) { // Poll itself failed, this is weird, warn and log errno - warning() << "Socket poll() failed during connectivity check" - << " (idle " << idleTimeSecs << " secs," - << " remote host " << remoteString() << ")" << causedBy(errnoWithDescription()); + LOGV2_WARNING(23193, + "Socket poll() failed during connectivity check (idle {idleTimeSecs} secs, " + "remote host {remoteString}){causedBy_errnoWithDescription}", + "idleTimeSecs"_attr = idleTimeSecs, + "remoteString"_attr = remoteString(), + "causedBy_errnoWithDescription"_attr = causedBy(errnoWithDescription())); // Return true since it's not clear that we're disconnected. return true; @@ -671,52 +721,67 @@ bool Socket::isStillConnected() { if (recvd < 0) { // An error occurred during recv, warn and log errno - warning() << "Socket recv() failed during connectivity check" - << " (idle " << idleTimeSecs << " secs," - << " remote host " << remoteString() << ")" - << causedBy(errnoWithDescription()); + LOGV2_WARNING(23194, + "Socket recv() failed during connectivity check (idle {idleTimeSecs} " + "secs, remote host {remoteString}){causedBy_errnoWithDescription}", + "idleTimeSecs"_attr = idleTimeSecs, + "remoteString"_attr = remoteString(), + "causedBy_errnoWithDescription"_attr = causedBy(errnoWithDescription())); } else if (recvd > 0) { // We got nonzero data from this socket, very weird? // Log and warn at runtime, log and abort at devtime // TODO: Dump the data to the log somehow? - error() << "Socket found pending " << recvd - << " bytes of data during connectivity check" - << " (idle " << idleTimeSecs << " secs," - << " remote host " << remoteString() << ")"; + LOGV2_ERROR(23197, + "Socket found pending {recvd} bytes of data during connectivity check " + "(idle {idleTimeSecs} secs, remote host {remoteString})", + "recvd"_attr = recvd, + "idleTimeSecs"_attr = idleTimeSecs, + "remoteString"_attr = remoteString()); if (kDebugBuild) { std::string hex = hexdump(testBuf, recvd); - error() << "Hex dump of stale log data: " << hex; + LOGV2_ERROR(23198, "Hex dump of stale log data: {hex}", "hex"_attr = hex); } dassert(false); } else { // recvd == 0, socket closed remotely, just return false - LOG(0) << "Socket closed remotely, no longer connected" - << " (idle " << idleTimeSecs << " secs," - << " remote host " << remoteString() << ")"; + LOGV2(23187, + "Socket closed remotely, no longer connected (idle {idleTimeSecs} secs, remote " + "host {remoteString})", + "idleTimeSecs"_attr = idleTimeSecs, + "remoteString"_attr = remoteString()); } } else if (pollInfo.revents & POLLHUP) { // A hangup has occurred on this socket - LOG(0) << "Socket hangup detected, no longer connected" - << " (idle " << idleTimeSecs << " secs," - << " remote host " << remoteString() << ")"; + LOGV2(23188, + "Socket hangup detected, no longer connected (idle {idleTimeSecs} secs, remote host " + "{remoteString})", + "idleTimeSecs"_attr = idleTimeSecs, + "remoteString"_attr = remoteString()); } else if (pollInfo.revents & POLLERR) { // An error has occurred on this socket - LOG(0) << "Socket error detected, no longer connected" - << " (idle " << idleTimeSecs << " secs," - << " remote host " << remoteString() << ")"; + LOGV2(23189, + "Socket error detected, no longer connected (idle {idleTimeSecs} secs, remote host " + "{remoteString})", + "idleTimeSecs"_attr = idleTimeSecs, + "remoteString"_attr = remoteString()); } else if (pollInfo.revents & POLLNVAL) { // Socket descriptor itself is weird // Log and warn at runtime, log and abort at devtime - error() << "Socket descriptor detected as invalid" - << " (idle " << idleTimeSecs << " secs," - << " remote host " << remoteString() << ")"; + LOGV2_ERROR(23199, + "Socket descriptor detected as invalid (idle {idleTimeSecs} secs, remote host " + "{remoteString})", + "idleTimeSecs"_attr = idleTimeSecs, + "remoteString"_attr = remoteString()); dassert(false); } else { // Don't know what poll is saying here // Log and warn at runtime, log and abort at devtime - error() << "Socket had unknown event (" << static_cast<int>(pollInfo.revents) << ")" - << " (idle " << idleTimeSecs << " secs," - << " remote host " << remoteString() << ")"; + LOGV2_ERROR(23200, + "Socket had unknown event ({static_cast_int_pollInfo_revents}) (idle " + "{idleTimeSecs} secs, remote host {remoteString})", + "static_cast_int_pollInfo_revents"_attr = static_cast<int>(pollInfo.revents), + "idleTimeSecs"_attr = idleTimeSecs, + "remoteString"_attr = remoteString()); dassert(false); } diff --git a/src/mongo/util/net/sockaddr.cpp b/src/mongo/util/net/sockaddr.cpp index ed4135d1eb7..9e2d81571f6 100644 --- a/src/mongo/util/net/sockaddr.cpp +++ b/src/mongo/util/net/sockaddr.cpp @@ -54,6 +54,7 @@ #endif #include "mongo/bson/util/builder.h" +#include "mongo/logv2/log.h" #include "mongo/util/itoa.h" #include "mongo/util/log.h" @@ -157,8 +158,10 @@ SockAddr::SockAddr(StringData target, int port, sa_family_t familyHint) // we were unsuccessful if (_hostOrIp != "0.0.0.0") { // don't log if this as it is a // CRT construction and log() may not work yet. - log() << "getaddrinfo(\"" << _hostOrIp - << "\") failed: " << getAddrInfoStrError(addrErr.err); + LOGV2(23175, + "getaddrinfo(\"{hostOrIp}\") failed: {getAddrInfoStrError_addrErr_err}", + "hostOrIp"_attr = _hostOrIp, + "getAddrInfoStrError_addrErr_err"_attr = getAddrInfoStrError(addrErr.err)); _isValid = false; return; } @@ -187,7 +190,10 @@ std::vector<SockAddr> SockAddr::createAll(StringData target, int port, sa_family auto addrErr = resolveAddrInfo(hostOrIp, port, familyHint); if (addrErr.err) { - log() << "getaddrinfo(\"" << hostOrIp << "\") failed: " << getAddrInfoStrError(addrErr.err); + LOGV2(23176, + "getaddrinfo(\"{hostOrIp}\") failed: {getAddrInfoStrError_addrErr_err}", + "hostOrIp"_attr = hostOrIp, + "getAddrInfoStrError_addrErr_err"_attr = getAddrInfoStrError(addrErr.err)); return {}; } diff --git a/src/mongo/util/net/socket_utils.cpp b/src/mongo/util/net/socket_utils.cpp index f58ff484ec7..42c2e38eac8 100644 --- a/src/mongo/util/net/socket_utils.cpp +++ b/src/mongo/util/net/socket_utils.cpp @@ -54,6 +54,7 @@ #endif #include "mongo/db/server_options.h" +#include "mongo/logv2/log.h" #include "mongo/util/concurrency/value.h" #include "mongo/util/errno_util.h" #include "mongo/util/log.h" @@ -69,7 +70,9 @@ const struct WinsockInit { WinsockInit() { WSADATA d; if (WSAStartup(MAKEWORD(2, 2), &d) != 0) { - log() << "ERROR: wsastartup failed " << errnoWithDescription(); + LOGV2(23201, + "ERROR: wsastartup failed {errnoWithDescription}", + "errnoWithDescription"_attr = errnoWithDescription()); quickExit(EXIT_NTSERVICE_ERROR); } } @@ -114,7 +117,9 @@ void setSocketKeepAliveParams(int sock, // Return seconds return val ? (val.get() / 1000) : default_value; } - error() << "can't get KeepAlive parameter: " << withval.getStatus(); + LOGV2_ERROR(23203, + "can't get KeepAlive parameter: {withval_getStatus}", + "withval_getStatus"_attr = withval.getStatus()); return default_value; }; @@ -136,7 +141,9 @@ void setSocketKeepAliveParams(int sock, &sent, nullptr, nullptr)) { - error() << "failed setting keepalive values: " << WSAGetLastError(); + LOGV2_ERROR(23204, + "failed setting keepalive values: {WSAGetLastError}", + "WSAGetLastError"_attr = WSAGetLastError()); } } #elif defined(__APPLE__) || defined(__linux__) @@ -146,13 +153,19 @@ void setSocketKeepAliveParams(int sock, socklen_t len = sizeof(optval); if (getsockopt(sock, level, optnum, (char*)&optval, &len)) { - error() << "can't get " << optname << ": " << errnoWithDescription(); + LOGV2_ERROR(23205, + "can't get {optname}: {errnoWithDescription}", + "optname"_attr = optname, + "errnoWithDescription"_attr = errnoWithDescription()); } if (optval > maxval) { optval = maxval; if (setsockopt(sock, level, optnum, (char*)&optval, sizeof(optval))) { - error() << "can't set " << optname << ": " << errnoWithDescription(); + LOGV2_ERROR(23206, + "can't set {optname}: {errnoWithDescription}", + "optname"_attr = optname, + "errnoWithDescription"_attr = errnoWithDescription()); } } }; @@ -196,7 +209,9 @@ std::string getHostName() { char buf[256]; int ec = gethostname(buf, 127); if (ec || *buf == 0) { - log() << "can't get this server's hostname " << errnoWithDescription(); + LOGV2(23202, + "can't get this server's hostname {errnoWithDescription}", + "errnoWithDescription"_attr = errnoWithDescription()); return ""; } return buf; diff --git a/src/mongo/util/net/ssl_manager.cpp b/src/mongo/util/net/ssl_manager.cpp index d0b6ae3988f..1fcc08f0205 100644 --- a/src/mongo/util/net/ssl_manager.cpp +++ b/src/mongo/util/net/ssl_manager.cpp @@ -42,6 +42,7 @@ #include "mongo/bson/bsonobjbuilder.h" #include "mongo/config.h" #include "mongo/db/commands/server_status.h" +#include "mongo/logv2/log.h" #include "mongo/platform/overflow_arithmetic.h" #include "mongo/transport/session.h" #include "mongo/util/hex.h" @@ -553,11 +554,21 @@ MONGO_INITIALIZER_WITH_PREREQUISITES(SSLManagerLogger, ("SSLManager", "GlobalLog if (!isSSLServer || (sslGlobalParams.sslMode.load() != SSLParams::SSLMode_disabled)) { const auto& config = theSSLManager->getSSLConfiguration(); if (!config.clientSubjectName.empty()) { - LOG(1) << "Client Certificate Name: " << config.clientSubjectName; + LOGV2_DEBUG(23214, + 1, + "Client Certificate Name: {config_clientSubjectName}", + "config_clientSubjectName"_attr = config.clientSubjectName); } if (!config.serverSubjectName().empty()) { - LOG(1) << "Server Certificate Name: " << config.serverSubjectName(); - LOG(1) << "Server Certificate Expiration: " << config.serverCertificateExpirationDate; + LOGV2_DEBUG(23215, + 1, + "Server Certificate Name: {config_serverSubjectName}", + "config_serverSubjectName"_attr = config.serverSubjectName()); + LOGV2_DEBUG(23216, + 1, + "Server Certificate Expiration: {config_serverCertificateExpirationDate}", + "config_serverCertificateExpirationDate"_attr = + config.serverCertificateExpirationDate); } } @@ -594,8 +605,12 @@ Status SSLX509Name::normalizeStrings() { break; } default: - LOG(1) << "Certificate subject name contains unknown string type: " - << entry.type << " (string value is \"" << entry.value << "\")"; + LOGV2_DEBUG(23217, + 1, + "Certificate subject name contains unknown string type: " + "{entry_type} (string value is \"{entry_value}\")", + "entry_type"_attr = entry.type, + "entry_value"_attr = entry.value); break; } } @@ -677,13 +692,16 @@ bool SSLConfiguration::isClusterMember(SSLX509Name subject) const { bool SSLConfiguration::isClusterMember(StringData subjectName) const { auto swClient = parseDN(subjectName); if (!swClient.isOK()) { - warning() << "Unable to parse client subject name: " << swClient.getStatus(); + LOGV2_WARNING(23219, + "Unable to parse client subject name: {swClient_getStatus}", + "swClient_getStatus"_attr = swClient.getStatus()); return false; } auto& client = swClient.getValue(); auto status = client.normalizeStrings(); if (!status.isOK()) { - warning() << "Unable to normalize client subject name: " << status; + LOGV2_WARNING( + 23220, "Unable to normalize client subject name: {status}", "status"_attr = status); return false; } @@ -1110,8 +1128,11 @@ void recordTLSVersion(TLSVersion version, const HostAndPort& hostForLogging) { } if (!versionString.empty()) { - log() << "Accepted connection with TLS Version " << versionString << " from connection " - << hostForLogging; + LOGV2( + 23218, + "Accepted connection with TLS Version {versionString} from connection {hostForLogging}", + "versionString"_attr = versionString, + "hostForLogging"_attr = hostForLogging); } } @@ -1139,11 +1160,14 @@ bool hostNameMatchForX509Certificates(std::string nameToMatch, std::string certH } void tlsEmitWarningExpiringClientCertificate(const SSLX509Name& peer) { - warning() << "Peer certificate '" << peer << "' expires soon"; + LOGV2_WARNING(23221, "Peer certificate '{peer}' expires soon", "peer"_attr = peer); } void tlsEmitWarningExpiringClientCertificate(const SSLX509Name& peer, Days days) { - warning() << "Peer certificate '" << peer << "' expires in " << days; + LOGV2_WARNING(23222, + "Peer certificate '{peer}' expires in {days}", + "peer"_attr = peer, + "days"_attr = days); } } // namespace mongo diff --git a/src/mongo/util/net/ssl_manager_apple.cpp b/src/mongo/util/net/ssl_manager_apple.cpp index 970db6c9d3b..3ae8a983904 100644 --- a/src/mongo/util/net/ssl_manager_apple.cpp +++ b/src/mongo/util/net/ssl_manager_apple.cpp @@ -43,6 +43,7 @@ #include "mongo/base/status_with.h" #include "mongo/crypto/sha1_block.h" #include "mongo/crypto/sha256_block.h" +#include "mongo/logv2/log.h" #include "mongo/platform/random.h" #include "mongo/util/base64.h" #include "mongo/util/concurrency/mutex.h" @@ -527,8 +528,9 @@ StatusWith<std::vector<std::string>> extractSubjectAlternateNames(::CFDictionary if (swCIDRValue.isOK()) { swNameStr = swCIDRValue.getValue().toString(); if (san == kDNS) { - warning() << "You have an IP Address in the DNS Name field on your " - "certificate. This formulation is deprecated."; + LOGV2_WARNING(23208, + "You have an IP Address in the DNS Name field on your " + "certificate. This formulation is deprecated."); } } ret.push_back(swNameStr.getValue()); @@ -1448,11 +1450,11 @@ Future<SSLPeerInfo> SSLManagerApple::parseAndValidatePeerCertificate( const auto badCert = [&](StringData msg, bool warn = false) -> Future<SSLPeerInfo> { constexpr StringData prefix = "SSL peer certificate validation failed: "_sd; if (warn) { - warning() << prefix << msg; + LOGV2_WARNING(23209, "{prefix}{msg}", "prefix"_attr = prefix, "msg"_attr = msg); return Future<SSLPeerInfo>::makeReady(SSLPeerInfo(sniName)); } else { std::string m = str::stream() << prefix << msg << "; connection rejected"; - error() << m; + LOGV2_ERROR(23212, "{m}", "m"_attr = m); return Status(ErrorCodes::SSLHandshakeFailed, m); } }; @@ -1540,7 +1542,10 @@ Future<SSLPeerInfo> SSLManagerApple::parseAndValidatePeerCertificate( return swPeerSubjectName.getStatus(); } const auto peerSubjectName = std::move(swPeerSubjectName.getValue()); - LOG(2) << "Accepted TLS connection from peer: " << peerSubjectName; + LOGV2_DEBUG(23207, + 2, + "Accepted TLS connection from peer: {peerSubjectName}", + "peerSubjectName"_attr = peerSubjectName); // Server side. if (remoteHost.empty()) { @@ -1563,7 +1568,7 @@ Future<SSLPeerInfo> SSLManagerApple::parseAndValidatePeerCertificate( // If client and server certificate are the same, log a warning. if (_sslConfiguration.serverSubjectName() == peerSubjectName) { - warning() << "Client connecting with server's own TLS certificate"; + LOGV2_WARNING(23210, "Client connecting with server's own TLS certificate"); } // If this is an SSL server context (on a mongod/mongos) @@ -1635,9 +1640,9 @@ Future<SSLPeerInfo> SSLManagerApple::parseAndValidatePeerCertificate( if (!sanMatch && !cnMatch) { const auto msg = certErr.str(); if (_allowInvalidCertificates || _allowInvalidHostnames || isUnixDomainSocket(remoteHost)) { - warning() << msg; + LOGV2_WARNING(23211, "{msg}", "msg"_attr = msg); } else { - error() << msg; + LOGV2_ERROR(23213, "{msg}", "msg"_attr = msg); return Status(ErrorCodes::SSLHandshakeFailed, msg); } } diff --git a/src/mongo/util/net/ssl_manager_openssl.cpp b/src/mongo/util/net/ssl_manager_openssl.cpp index 702ae32b4c3..bb709db0c79 100644 --- a/src/mongo/util/net/ssl_manager_openssl.cpp +++ b/src/mongo/util/net/ssl_manager_openssl.cpp @@ -48,6 +48,7 @@ #include "mongo/base/secure_allocator.h" #include "mongo/bson/bsonobjbuilder.h" #include "mongo/config.h" +#include "mongo/logv2/log.h" #include "mongo/platform/atomic_word.h" #include "mongo/transport/session.h" #include "mongo/util/concurrency/mutex.h" @@ -192,7 +193,8 @@ bool enableECDHE(SSL_CTX* const ctx) { if (SSL_CTX_ctrl(ctx, 94, 1, nullptr) != 1) { // If manually setting the configuration option failed, use a hard coded curve if (!useDefaultECKey(ctx)) { - warning() << "Failed to enable ECDHE due to a lack of support from system libraries."; + LOGV2_WARNING(23230, + "Failed to enable ECDHE due to a lack of support from system libraries."); return false; } } @@ -673,7 +675,7 @@ SSLConnectionOpenSSL::SSLConnectionOpenSSL(SSL_CTX* context, if (len > 0) { int toBIO = BIO_write(networkBIO, initialBytes, len); if (toBIO != len) { - LOG(3) << "Failed to write initial network data to the SSL BIO layer"; + LOGV2_DEBUG(23223, 3, "Failed to write initial network data to the SSL BIO layer"); throwSocketError(SocketErrorKind::RECV_ERROR, socket->remoteString()); } } @@ -750,7 +752,9 @@ int SSLManagerOpenSSL::password_cb(char* buf, int num, int rwflag, void* userdat auto pwFetcher = static_cast<PasswordFetcher*>(userdata); auto swPassword = pwFetcher->fetchPassword(); if (!swPassword.isOK()) { - error() << "Unable to fetch password: " << swPassword.getStatus(); + LOGV2_ERROR(23239, + "Unable to fetch password: {swPassword_getStatus}", + "swPassword_getStatus"_attr = swPassword.getStatus()); return -1; } StringData password = std::move(swPassword.getValue()); @@ -1305,8 +1309,10 @@ int ocspClientCallback(SSL* ssl, void* arg) { UniqueX509 peerCert(SSL_get_peer_certificate(ssl)); if (!peerCert) { - LOG(1) << "Could not get peer certificate from SSL object in OCSP verification callback. " - << "Will continue with the connection."; + LOGV2_DEBUG(23224, + 1, + "Could not get peer certificate from SSL object in OCSP verification callback. " + "Will continue with the connection."); return OCSP_CLIENT_RESPONSE_ACCEPTABLE; } @@ -1328,14 +1334,19 @@ int ocspClientCallback(SSL* ssl, void* arg) { // CRLs or check with the OCSP responder ourselves. If it is true, then we are done. if (!swStapleOK.isOK()) { if (swStapleOK.getStatus() == ErrorCodes::OCSPCertificateStatusRevoked) { - LOG(1) << "Stapled Certificate validation failed: " << swStapleOK.getStatus().reason(); + LOGV2_DEBUG(23225, + 1, + "Stapled Certificate validation failed: {swStapleOK_getStatus_reason}", + "swStapleOK_getStatus_reason"_attr = swStapleOK.getStatus().reason()); return OCSP_CLIENT_RESPONSE_NOT_ACCEPTABLE; } return OCSP_CLIENT_RESPONSE_ERROR; } else if (!swStapleOK.getValue()) { - LOG(1) << "Stapled Certificate validation failed: Stapled response does not " - << "contain status information regarding the peer certificate."; + LOGV2_DEBUG(23226, + 1, + "Stapled Certificate validation failed: Stapled response does not contain " + "status information regarding the peer certificate."); return OCSP_CLIENT_RESPONSE_NOT_ACCEPTABLE; } @@ -1378,7 +1389,8 @@ Status stapleOCSPResponse(SSL_CTX* context) { if (!cert) { // Because OpenSSL 1.0.1 doesn't allow accessing the internal cert object of a // SSL context, so this shouldn't fail the program. - warning() << "Could not staple because could not get certificate from SSL Context."; + LOGV2_WARNING(23231, + "Could not staple because could not get certificate from SSL Context."); return Status::OK(); } @@ -1398,7 +1410,7 @@ Status stapleOCSPResponse(SSL_CTX* context) { auto swOCSPContext = extractOcspUris(context, cert, intermediateCerts.get()); if (!swOCSPContext.isOK()) { - warning() << "Could not staple OCSP response to outgoing certificate."; + LOGV2_WARNING(23232, "Could not staple OCSP response to outgoing certificate."); return swOCSPContext.getStatus(); } @@ -1407,7 +1419,7 @@ Status stapleOCSPResponse(SSL_CTX* context) { dispatchRequests(context, std::move(intermediateCerts), ocspContext) .getAsync([context](StatusWith<std::pair<Status, UniqueOCSPResponse>> swResponse) { if (!swResponse.isOK()) { - warning() << "Could not staple OCSP response to outgoing certificate."; + LOGV2_WARNING(23233, "Could not staple OCSP response to outgoing certificate."); return; } @@ -1569,8 +1581,10 @@ Status SSLManagerOpenSSL::initSSLContext(SSL_CTX* context, UniqueDHParams dhparams = makeDefaultDHParameters(); if (!dhparams || SSL_CTX_set_tmp_dh(context, dhparams.get()) != 1) { - error() << "Failed to set default DH parameters: " - << getSSLErrorMessage(ERR_get_error()); + LOGV2_ERROR( + 23240, + "Failed to set default DH parameters: {getSSLErrorMessage_ERR_get_error}", + "getSSLErrorMessage_ERR_get_error"_attr = getSSLErrorMessage(ERR_get_error())); } } } @@ -1598,14 +1612,14 @@ unsigned long long SSLManagerOpenSSL::_convertASN1ToMillis(ASN1_TIME* asn1time) ON_BLOCK_EXIT([&] { BIO_free(outBIO); }); if (timeError <= 0) { - error() << "ASN1_TIME_print failed or wrote no data."; + LOGV2_ERROR(23241, "ASN1_TIME_print failed or wrote no data."); return 0; } char dateChar[DATE_LEN]; timeError = BIO_gets(outBIO, dateChar, DATE_LEN); if (timeError <= 0) { - error() << "BIO_gets call failed to transfer contents to buf"; + LOGV2_ERROR(23242, "BIO_gets call failed to transfer contents to buf"); return 0; } @@ -1634,22 +1648,30 @@ bool SSLManagerOpenSSL::_parseAndValidateCertificate(const std::string& keyFile, Date_t* serverCertificateExpirationDate) { BIO* inBIO = BIO_new(BIO_s_file()); if (inBIO == nullptr) { - error() << "failed to allocate BIO object: " << getSSLErrorMessage(ERR_get_error()); + LOGV2_ERROR(23243, + "failed to allocate BIO object: {getSSLErrorMessage_ERR_get_error}", + "getSSLErrorMessage_ERR_get_error"_attr = getSSLErrorMessage(ERR_get_error())); return false; } ON_BLOCK_EXIT([&] { BIO_free(inBIO); }); if (BIO_read_filename(inBIO, keyFile.c_str()) <= 0) { - error() << "cannot read key file when setting subject name: " << keyFile << ' ' - << getSSLErrorMessage(ERR_get_error()); + LOGV2_ERROR(23244, + "cannot read key file when setting subject name: {keyFile} " + "{getSSLErrorMessage_ERR_get_error}", + "keyFile"_attr = keyFile, + "getSSLErrorMessage_ERR_get_error"_attr = getSSLErrorMessage(ERR_get_error())); return false; } X509* x509 = PEM_read_bio_X509( inBIO, nullptr, &SSLManagerOpenSSL::password_cb, static_cast<void*>(&keyPassword)); if (x509 == nullptr) { - error() << "cannot retrieve certificate from keyfile: " << keyFile << ' ' - << getSSLErrorMessage(ERR_get_error()); + LOGV2_ERROR(23245, + "cannot retrieve certificate from keyfile: {keyFile} " + "{getSSLErrorMessage_ERR_get_error}", + "keyFile"_attr = keyFile, + "getSSLErrorMessage_ERR_get_error"_attr = getSSLErrorMessage(ERR_get_error())); return false; } ON_BLOCK_EXIT([&] { X509_free(x509); }); @@ -1658,18 +1680,18 @@ bool SSLManagerOpenSSL::_parseAndValidateCertificate(const std::string& keyFile, if (serverCertificateExpirationDate != nullptr) { unsigned long long notBeforeMillis = _convertASN1ToMillis(X509_get_notBefore(x509)); if (notBeforeMillis == 0) { - error() << "date conversion failed"; + LOGV2_ERROR(23246, "date conversion failed"); return false; } unsigned long long notAfterMillis = _convertASN1ToMillis(X509_get_notAfter(x509)); if (notAfterMillis == 0) { - error() << "date conversion failed"; + LOGV2_ERROR(23247, "date conversion failed"); return false; } if ((notBeforeMillis > curTimeMillis64()) || (curTimeMillis64() > notAfterMillis)) { - severe() << "The provided SSL certificate is expired or not yet valid."; + LOGV2_FATAL(23265, "The provided SSL certificate is expired or not yet valid."); fassertFailedNoTrace(28652); } @@ -1683,21 +1705,27 @@ bool SSLManagerOpenSSL::_setupPEM(SSL_CTX* context, const std::string& keyFile, PasswordFetcher* password) { if (SSL_CTX_use_certificate_chain_file(context, keyFile.c_str()) != 1) { - error() << "cannot read certificate file: " << keyFile << ' ' - << getSSLErrorMessage(ERR_get_error()); + LOGV2_ERROR(23248, + "cannot read certificate file: {keyFile} {getSSLErrorMessage_ERR_get_error}", + "keyFile"_attr = keyFile, + "getSSLErrorMessage_ERR_get_error"_attr = getSSLErrorMessage(ERR_get_error())); return false; } BIO* inBio = BIO_new(BIO_s_file()); if (!inBio) { - error() << "failed to allocate BIO object: " << getSSLErrorMessage(ERR_get_error()); + LOGV2_ERROR(23249, + "failed to allocate BIO object: {getSSLErrorMessage_ERR_get_error}", + "getSSLErrorMessage_ERR_get_error"_attr = getSSLErrorMessage(ERR_get_error())); return false; } const auto bioGuard = makeGuard([&inBio]() { BIO_free(inBio); }); if (BIO_read_filename(inBio, keyFile.c_str()) <= 0) { - error() << "cannot read PEM key file: " << keyFile << ' ' - << getSSLErrorMessage(ERR_get_error()); + LOGV2_ERROR(23250, + "cannot read PEM key file: {keyFile} {getSSLErrorMessage_ERR_get_error}", + "keyFile"_attr = keyFile, + "getSSLErrorMessage_ERR_get_error"_attr = getSSLErrorMessage(ERR_get_error())); return false; } @@ -1706,21 +1734,27 @@ bool SSLManagerOpenSSL::_setupPEM(SSL_CTX* context, void* userdata = static_cast<void*>(password); EVP_PKEY* privateKey = PEM_read_bio_PrivateKey(inBio, nullptr, password_cb, userdata); if (!privateKey) { - error() << "cannot read PEM key file: " << keyFile << ' ' - << getSSLErrorMessage(ERR_get_error()); + LOGV2_ERROR(23251, + "cannot read PEM key file: {keyFile} {getSSLErrorMessage_ERR_get_error}", + "keyFile"_attr = keyFile, + "getSSLErrorMessage_ERR_get_error"_attr = getSSLErrorMessage(ERR_get_error())); return false; } const auto privateKeyGuard = makeGuard([&privateKey]() { EVP_PKEY_free(privateKey); }); if (SSL_CTX_use_PrivateKey(context, privateKey) != 1) { - error() << "cannot use PEM key file: " << keyFile << ' ' - << getSSLErrorMessage(ERR_get_error()); + LOGV2_ERROR(23252, + "cannot use PEM key file: {keyFile} {getSSLErrorMessage_ERR_get_error}", + "keyFile"_attr = keyFile, + "getSSLErrorMessage_ERR_get_error"_attr = getSSLErrorMessage(ERR_get_error())); return false; } // Verify that the certificate and the key go together. if (SSL_CTX_check_private_key(context) != 1) { - error() << "SSL certificate validation: " << getSSLErrorMessage(ERR_get_error()); + LOGV2_ERROR(23253, + "SSL certificate validation: {getSSLErrorMessage_ERR_get_error}", + "getSSLErrorMessage_ERR_get_error"_attr = getSSLErrorMessage(ERR_get_error())); return false; } @@ -1786,12 +1820,16 @@ bool SSLManagerOpenSSL::_setupCRL(SSL_CTX* context, const std::string& crlFile) int status = X509_load_crl_file(lookup, crlFile.c_str(), X509_FILETYPE_PEM); if (status == 0) { - error() << "cannot read CRL file: " << crlFile << ' ' - << getSSLErrorMessage(ERR_get_error()); + LOGV2_ERROR(23254, + "cannot read CRL file: {crlFile} {getSSLErrorMessage_ERR_get_error}", + "crlFile"_attr = crlFile, + "getSSLErrorMessage_ERR_get_error"_attr = getSSLErrorMessage(ERR_get_error())); return false; } - log() << "ssl imported " << status << " revoked certificate" << ((status == 1) ? "" : "s") - << " from the revocation list."; + LOGV2(23227, + "ssl imported {status} revoked certificate{status_1_s} from the revocation list.", + "status"_attr = status, + "status_1_s"_attr = ((status == 1) ? "" : "s")); return true; } @@ -1838,7 +1876,7 @@ void SSLManagerOpenSSL::_flushNetworkBIO(SSLConnectionOpenSSL* conn) { int toBIO = BIO_write(conn->networkBIO, buffer, numRead); if (toBIO != numRead) { - LOG(3) << "Failed to write network data to the SSL BIO layer"; + LOGV2_DEBUG(23228, 3, "Failed to write network data to the SSL BIO layer"); throwSocketError(SocketErrorKind::RECV_ERROR, conn->socket->remoteString()); } } @@ -2008,12 +2046,12 @@ Future<SSLPeerInfo> SSLManagerOpenSSL::parseAndValidatePeerCertificate( if (_weakValidation) { // do not give warning if certificate warnings are suppressed if (!_suppressNoCertificateWarning) { - warning() << "no SSL certificate provided by peer"; + LOGV2_WARNING(23234, "no SSL certificate provided by peer"); } return SSLPeerInfo(sni); } else { auto msg = "no SSL certificate provided by peer; connection rejected"; - error() << msg; + LOGV2_ERROR(23255, "{msg}", "msg"_attr = msg); return Status(ErrorCodes::SSLHandshakeFailed, msg); } } @@ -2023,14 +2061,17 @@ Future<SSLPeerInfo> SSLManagerOpenSSL::parseAndValidatePeerCertificate( if (result != X509_V_OK) { if (_allowInvalidCertificates) { - warning() << "SSL peer certificate validation failed: " - << X509_verify_cert_error_string(result); + LOGV2_WARNING( + 23235, + "SSL peer certificate validation failed: {X509_verify_cert_error_string_result}", + "X509_verify_cert_error_string_result"_attr = + X509_verify_cert_error_string(result)); return SSLPeerInfo(sni); } else { str::stream msg; msg << "SSL peer certificate validation failed: " << X509_verify_cert_error_string(result); - error() << msg.ss.str(); + LOGV2_ERROR(23256, "{msg_ss_str}", "msg_ss_str"_attr = msg.ss.str()); return Status(ErrorCodes::SSLHandshakeFailed, msg); } } @@ -2042,7 +2083,10 @@ Future<SSLPeerInfo> SSLManagerOpenSSL::parseAndValidatePeerCertificate( // TODO: check optional cipher restriction, using cert. auto peerSubject = getCertificateSubjectX509Name(peerCert); - LOG(2) << "Accepted TLS connection from peer: " << peerSubject; + LOGV2_DEBUG(23229, + 2, + "Accepted TLS connection from peer: {peerSubject}", + "peerSubject"_attr = peerSubject); StatusWith<stdx::unordered_set<RoleName>> swPeerCertificateRoles = _parsePeerRoles(peerCert); if (!swPeerCertificateRoles.isOK()) { @@ -2072,7 +2116,7 @@ Future<SSLPeerInfo> SSLManagerOpenSSL::parseAndValidatePeerCertificate( // If client and server certificate are the same, log a warning. if (_sslConfiguration.serverSubjectName() == peerSubject) { - warning() << "Client connecting with server's own TLS certificate"; + LOGV2_WARNING(23236, "Client connecting with server's own TLS certificate"); } // void futures are default constructed as ready futures. @@ -2112,8 +2156,9 @@ Future<SSLPeerInfo> SSLManagerOpenSSL::parseAndValidatePeerCertificate( reinterpret_cast<char*>(ASN1_STRING_data(currentName->d.dNSName))); auto swCIDRDNSName = CIDR::parse(dnsName); if (swCIDRDNSName.isOK()) { - warning() << "You have an IP Address in the DNS Name field on your " - "certificate. This formulation is deprecated."; + LOGV2_WARNING(23237, + "You have an IP Address in the DNS Name field on your " + "certificate. This formulation is deprecated."); if (swCIDRRemoteHost.isOK() && swCIDRRemoteHost.getValue() == swCIDRDNSName.getValue()) { sanMatch = true; @@ -2178,9 +2223,9 @@ Future<SSLPeerInfo> SSLManagerOpenSSL::parseAndValidatePeerCertificate( << remoteHost << " does not match " << certificateNames.str(); std::string msg = msgBuilder.str(); if (_allowInvalidCertificates || _allowInvalidHostnames || isUnixDomainSocket(remoteHost)) { - warning() << msg; + LOGV2_WARNING(23238, "{msg}", "msg"_attr = msg); } else { - error() << msg; + LOGV2_ERROR(23257, "{msg}", "msg"_attr = msg); return Future<SSLPeerInfo>::makeReady(Status(ErrorCodes::SSLHandshakeFailed, msg)); } } @@ -2249,32 +2294,39 @@ void SSLManagerOpenSSL::_handleSSLError(SSLConnectionOpenSSL* conn, int ret) { // manner. errToThrow = (code == SSL_ERROR_WANT_READ) ? SocketErrorKind::RECV_ERROR : SocketErrorKind::SEND_ERROR; - error() << "SSL: " << code << ", possibly timed out during connect"; + LOGV2_ERROR( + 23258, "SSL: {code}, possibly timed out during connect", "code"_attr = code); break; case SSL_ERROR_ZERO_RETURN: // TODO: Check if we can avoid throwing an exception for this condition // If so, change error() back to LOG(3) - error() << "SSL network connection closed"; + LOGV2_ERROR(23259, "SSL network connection closed"); break; case SSL_ERROR_SYSCALL: // If ERR_get_error returned 0, the error queue is empty // check the return value of the actual SSL operation if (err != 0) { - error() << "SSL: " << getSSLErrorMessage(err); + LOGV2_ERROR(23260, + "SSL: {getSSLErrorMessage_err}", + "getSSLErrorMessage_err"_attr = getSSLErrorMessage(err)); } else if (ret == 0) { - error() << "Unexpected EOF encountered during SSL communication"; + LOGV2_ERROR(23261, "Unexpected EOF encountered during SSL communication"); } else { - error() << "The SSL BIO reported an I/O error " << errnoWithDescription(); + LOGV2_ERROR(23262, + "The SSL BIO reported an I/O error {errnoWithDescription}", + "errnoWithDescription"_attr = errnoWithDescription()); } break; case SSL_ERROR_SSL: { - error() << "SSL: " << getSSLErrorMessage(err); + LOGV2_ERROR(23263, + "SSL: {getSSLErrorMessage_err}", + "getSSLErrorMessage_err"_attr = getSSLErrorMessage(err)); break; } default: - error() << "unrecognized SSL error"; + LOGV2_ERROR(23264, "unrecognized SSL error"); break; } _flushNetworkBIO(conn); diff --git a/src/mongo/util/net/ssl_manager_test.cpp b/src/mongo/util/net/ssl_manager_test.cpp index a7335970125..c5c05ff5bf3 100644 --- a/src/mongo/util/net/ssl_manager_test.cpp +++ b/src/mongo/util/net/ssl_manager_test.cpp @@ -34,6 +34,7 @@ #include "mongo/util/net/ssl_manager.h" #include "mongo/config.h" +#include "mongo/logv2/log.h" #include "mongo/unittest/unittest.h" #include "mongo/util/log.h" @@ -78,10 +79,17 @@ TEST(SSLManager, matchHostname) { for (const auto& test : tests) { if (bool(test.expected) != hostNameMatchForX509Certificates(test.hostname, test.certName)) { failure = true; - LOG(1) << "Failure for Hostname: " << test.hostname - << " Certificate: " << test.certName; + LOGV2_DEBUG(23266, + 1, + "Failure for Hostname: {test_hostname} Certificate: {test_certName}", + "test_hostname"_attr = test.hostname, + "test_certName"_attr = test.certName); } else { - LOG(1) << "Passed for Hostname: " << test.hostname << " Certificate: " << test.certName; + LOGV2_DEBUG(23267, + 1, + "Passed for Hostname: {test_hostname} Certificate: {test_certName}", + "test_hostname"_attr = test.hostname, + "test_certName"_attr = test.certName); } } ASSERT_FALSE(failure); @@ -358,7 +366,7 @@ TEST(SSLManager, DNParsingAndNormalization) { {"2.5.4.7", "大田区, 東京都"}}}}; for (const auto& test : tests) { - log() << "Testing DN \"" << test.first << "\""; + LOGV2(23268, "Testing DN \"{test_first}\"", "test_first"_attr = test.first); auto swDN = parseDN(test.first); ASSERT_OK(swDN.getStatus()); ASSERT_OK(swDN.getValue().normalizeStrings()); @@ -370,7 +378,7 @@ TEST(SSLManager, DNParsingAndNormalization) { TEST(SSLManager, BadDNParsing) { std::vector<std::string> tests = {"CN=#12345", R"(CN=\B)", R"(CN=<", "\)"}; for (const auto& test : tests) { - log() << "Testing bad DN: \"" << test << "\""; + LOGV2(23269, "Testing bad DN: \"{test}\"", "test"_attr = test); auto swDN = parseDN(test); ASSERT_NOT_OK(swDN.getStatus()); } diff --git a/src/mongo/util/net/ssl_manager_windows.cpp b/src/mongo/util/net/ssl_manager_windows.cpp index 4c9bcb356c8..62c82e04261 100644 --- a/src/mongo/util/net/ssl_manager_windows.cpp +++ b/src/mongo/util/net/ssl_manager_windows.cpp @@ -47,6 +47,7 @@ #include "mongo/bson/util/builder.h" #include "mongo/config.h" #include "mongo/db/server_options.h" +#include "mongo/logv2/log.h" #include "mongo/platform/atomic_word.h" #include "mongo/util/concurrency/mutex.h" #include "mongo/util/debug_util.h" @@ -396,7 +397,7 @@ SSLManagerWindows::SSLManagerWindows(const SSLParams& params, bool isServer) BOOLEAN enabled = FALSE; BCryptGetFipsAlgorithmMode(&enabled); if (!enabled) { - severe() << "FIPS modes is not enabled on the operating system."; + LOGV2_FATAL(23281, "FIPS modes is not enabled on the operating system."); fassertFailedNoTrace(50744); } } @@ -514,7 +515,9 @@ int SSLManagerWindows::SSL_read(SSLConnectionInterface* connInterface, void* buf return bytes_transferred; } default: - severe() << "Unexpected ASIO state: " << static_cast<int>(want); + LOGV2_FATAL(23282, + "Unexpected ASIO state: {static_cast_int_want}", + "static_cast_int_want"_attr = static_cast<int>(want)); MONGO_UNREACHABLE; } } @@ -558,7 +561,9 @@ int SSLManagerWindows::SSL_write(SSLConnectionInterface* connInterface, const vo return bytes_transferred; } default: - severe() << "Unexpected ASIO state: " << static_cast<int>(want); + LOGV2_FATAL(23283, + "Unexpected ASIO state: {static_cast_int_want}", + "static_cast_int_want"_attr = static_cast<int>(want)); MONGO_UNREACHABLE; } } @@ -1309,8 +1314,9 @@ Status SSLManagerWindows::_loadCertificates(const SSLParams& params) { if (_sslCertificate || _sslClusterCertificate) { if (!params.sslCAFile.empty()) { - warning() << "Mixing certs from the system certificate store and PEM files. This may " - "produced unexpected results."; + LOGV2_WARNING(23271, + "Mixing certs from the system certificate store and PEM files. This may " + "produced unexpected results."); } _sslConfiguration.hasCA = true; @@ -1382,8 +1388,9 @@ Status SSLManagerWindows::initSSLContext(SCHANNEL_CRED* cred, } if (!params.sslCipherConfig.empty()) { - warning() - << "sslCipherConfig parameter is not supported with Windows SChannel and is ignored."; + LOGV2_WARNING( + 23272, + "sslCipherConfig parameter is not supported with Windows SChannel and is ignored."); } if (direction == ConnectionDirection::kOutgoing) { @@ -1584,7 +1591,7 @@ Status SSLManagerWindows::_validateCertificate(PCCERT_CONTEXT cert, if ((FiletimeToULL(cert->pCertInfo->NotBefore) > currentTimeLong) || (currentTimeLong > FiletimeToULL(cert->pCertInfo->NotAfter))) { - severe() << "The provided SSL certificate is expired or not yet valid."; + LOGV2_FATAL(23284, "The provided SSL certificate is expired or not yet valid."); fassertFailedNoTrace(50755); } @@ -1642,8 +1649,9 @@ StatusWith<std::vector<std::string>> getSubjectAlternativeNames(PCCERT_CONTEXT c names.push_back(san); auto swCIDRSan = CIDR::parse(san); if (swCIDRSan.isOK()) { - warning() << "You have an IP Address in the DNS Name field on your " - "certificate. This formulation is depreceated."; + LOGV2_WARNING(23273, + "You have an IP Address in the DNS Name field on your " + "certificate. This formulation is depreceated."); } } else if (altNames->rgAltEntry[i].dwAltNameChoice == CERT_ALT_NAME_IP_ADDRESS) { auto ipAddrStruct = altNames->rgAltEntry[i].IPAddress; @@ -1809,14 +1817,19 @@ Status validatePeerCertificate(const std::string& remoteHost, << " does not match " << certificateNames.str(); if (allowInvalidCertificates) { - warning() << "SSL peer certificate validation failed (" - << integerToHex(certChainPolicyStatus.dwError) - << "): " << errnoWithDescription(certChainPolicyStatus.dwError); - warning() << msg.ss.str(); + LOGV2_WARNING(23274, + "SSL peer certificate validation failed " + "({integerToHex_certChainPolicyStatus_dwError}): " + "{errnoWithDescription_certChainPolicyStatus_dwError}", + "integerToHex_certChainPolicyStatus_dwError"_attr = + integerToHex(certChainPolicyStatus.dwError), + "errnoWithDescription_certChainPolicyStatus_dwError"_attr = + errnoWithDescription(certChainPolicyStatus.dwError)); + LOGV2_WARNING(23275, "{msg_ss_str}", "msg_ss_str"_attr = msg.ss.str()); *peerSubjectName = SSLX509Name(); return Status::OK(); } else if (allowInvalidHostnames) { - warning() << msg.ss.str(); + LOGV2_WARNING(23276, "{msg_ss_str}", "msg_ss_str"_attr = msg.ss.str()); return Status::OK(); } else { return Status(ErrorCodes::SSLHandshakeFailed, msg); @@ -1826,7 +1839,7 @@ Status validatePeerCertificate(const std::string& remoteHost, msg << "SSL peer certificate validation failed: (" << integerToHex(certChainPolicyStatus.dwError) << ")" << errnoWithDescription(certChainPolicyStatus.dwError); - error() << msg.ss.str(); + LOGV2_ERROR(23279, "{msg_ss_str}", "msg_ss_str"_attr = msg.ss.str()); return Status(ErrorCodes::SSLHandshakeFailed, msg); } } @@ -1885,12 +1898,12 @@ Future<SSLPeerInfo> SSLManagerWindows::parseAndValidatePeerCertificate( if (_weakValidation) { // do not give warning if "no certificate" warnings are suppressed if (!_suppressNoCertificateWarning) { - warning() << "no SSL certificate provided by peer"; + LOGV2_WARNING(23277, "no SSL certificate provided by peer"); } return SSLPeerInfo(sni); } else { auto msg = "no SSL certificate provided by peer; connection rejected"; - error() << msg; + LOGV2_ERROR(23280, "{msg}", "msg"_attr = msg); return Status(ErrorCodes::SSLHandshakeFailed, msg); } } @@ -1932,11 +1945,14 @@ Future<SSLPeerInfo> SSLManagerWindows::parseAndValidatePeerCertificate( return Future<SSLPeerInfo>::makeReady(SSLPeerInfo(sni)); } - LOG(2) << "Accepted TLS connection from peer: " << peerSubjectName; + LOGV2_DEBUG(23270, + 2, + "Accepted TLS connection from peer: {peerSubjectName}", + "peerSubjectName"_attr = peerSubjectName); // If this is a server and client and server certificate are the same, log a warning. if (remoteHost.empty() && _sslConfiguration.serverSubjectName() == peerSubjectName) { - warning() << "Client connecting with server's own TLS certificate"; + LOGV2_WARNING(23278, "Client connecting with server's own TLS certificate"); } // On the server side, parse the certificate for roles diff --git a/src/mongo/util/net/ssl_options_server.cpp b/src/mongo/util/net/ssl_options_server.cpp index dba0e0f94f7..56b0be72190 100644 --- a/src/mongo/util/net/ssl_options_server.cpp +++ b/src/mongo/util/net/ssl_options_server.cpp @@ -38,6 +38,7 @@ #include "mongo/base/status.h" #include "mongo/config.h" #include "mongo/db/server_options.h" +#include "mongo/logv2/log.h" #include "mongo/util/log.h" #include "mongo/util/options_parser/startup_option_init.h" #include "mongo/util/options_parser/startup_options.h" @@ -138,8 +139,9 @@ MONGO_STARTUP_OPTIONS_POST(SSLServerOptions)(InitializerContext*) { } if (params.count("net.tls.tlsCipherConfig")) { - warning() - << "net.tls.tlsCipherConfig is deprecated. It will be removed in a future release."; + LOGV2_WARNING( + 23286, + "net.tls.tlsCipherConfig is deprecated. It will be removed in a future release."); if (!sslGlobalParams.sslCipherConfig.empty()) { return {ErrorCodes::BadValue, "net.tls.tlsCipherConfig is incompatible with the openTLSCipherConfig " @@ -337,8 +339,9 @@ MONGO_STARTUP_OPTIONS_VALIDATE(SSLServerOptions)(InitializerContext*) { MONGO_INITIALIZER_WITH_PREREQUISITES(ImplicitDisableTLS10Warning, ("ServerLogRedirection")) (InitializerContext*) { if (gImplicitDisableTLS10) { - log() << "Automatically disabling TLS 1.0, to force-enable TLS 1.0 " - "specify --sslDisabledProtocols 'none'"; + LOGV2(23285, + "Automatically disabling TLS 1.0, to force-enable TLS 1.0 " + "specify --sslDisabledProtocols 'none'"); } return Status::OK(); } |