summaryrefslogtreecommitdiff
path: root/src/mongo/util/net/ssl_manager.h
blob: 002a0dd6be7bf6700bd657036ba87f599dd3abb2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/*    Copyright 2009 10gen Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    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
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    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 GNU Affero General 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.
 */

#pragma once

#include <boost/optional.hpp>
#include <memory>
#include <string>

#include "mongo/config.h"

#ifdef MONGO_CONFIG_SSL

#include "mongo/base/disallow_copying.h"
#include "mongo/base/string_data.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/util/decorable.h"
#include "mongo/util/net/sock.h"
#include "mongo/util/net/ssl_types.h"
#include "mongo/util/time_support.h"

#include <openssl/err.h>
#include <openssl/ssl.h>

#endif  // #ifdef MONGO_CONFIG_SSL

namespace mongo {
/*
 * @return the SSL version std::string prefixed with prefix and suffixed with suffix
 */
const std::string getSSLVersion(const std::string& prefix, const std::string& suffix);
}

#ifdef MONGO_CONFIG_SSL
namespace mongo {
struct SSLParams;

class SSLConnection {
public:
    SSL* ssl;
    BIO* networkBIO;
    BIO* internalBIO;
    Socket* socket;

    SSLConnection(SSL_CTX* ctx, Socket* sock, const char* initialBytes, int len);

    ~SSLConnection();
};

struct SSLConfiguration {
    SSLConfiguration() : serverSubjectName(""), clientSubjectName("") {}
    SSLConfiguration(const std::string& serverSubjectName,
                     const std::string& clientSubjectName,
                     const Date_t& serverCertificateExpirationDate)
        : serverSubjectName(serverSubjectName),
          clientSubjectName(clientSubjectName),
          serverCertificateExpirationDate(serverCertificateExpirationDate) {}

    bool isClusterMember(StringData subjectName) const;
    BSONObj getServerStatusBSON() const;
    std::string serverSubjectName;
    std::string clientSubjectName;
    Date_t serverCertificateExpirationDate;
    bool hasCA = false;
};

/**
 * Stores information about a globally unique OID.
 */
class ASN1OID {
public:
    ASN1OID(std::string identifier, std::string shortDescription, std::string longDescription)
        : identifier(std::move(identifier)),
          shortDescription(std::move(shortDescription)),
          longDescription(std::move(longDescription)) {}

    std::string identifier;        // An OID
    std::string shortDescription;  // A brief description of the entity associated with the OID
    std::string longDescription;   // A long form description of the entity associated with the OID
};
const ASN1OID mongodbRolesOID("1.3.6.1.4.1.34601.2.1.1",
                              "MongoRoles",
                              "Sequence of MongoDB Database Roles");

class SSLManagerInterface : public Decorable<SSLManagerInterface> {
public:
    static std::unique_ptr<SSLManagerInterface> create(const SSLParams& params, bool isServer);

    virtual ~SSLManagerInterface();

    /**
     * Initiates a TLS connection.
     * Throws SocketException on failure.
     * @return a pointer to an SSLConnection. Resources are freed in SSLConnection's destructor
     */
    virtual SSLConnection* connect(Socket* socket) = 0;

    /**
     * Waits for the other side to initiate a TLS connection.
     * Throws SocketException on failure.
     * @return a pointer to an SSLConnection. Resources are freed in SSLConnection's destructor
     */
    virtual SSLConnection* accept(Socket* socket, const char* initialBytes, int len) = 0;

    /**
     * Fetches a peer certificate and validates it if it exists
     * Throws SocketException on failure
     * @return a std::string containing the certificate's subject name.
     *
     * This version of parseAndValidatePeerCertificate is deprecated because it throws a
     * SocketException upon failure. New code should prefer the version that returns
     * a StatusWith instead.
     */
    virtual SSLPeerInfo parseAndValidatePeerCertificateDeprecated(
        const SSLConnection* conn, const std::string& remoteHost) = 0;

    /**
     * Gets the SSLConfiguration containing all information about the current SSL setup
     * @return the SSLConfiguration
     */
    virtual const SSLConfiguration& getSSLConfiguration() const = 0;

    /**
    * Fetches the error text for an error code, in a thread-safe manner.
    */
    static std::string getSSLErrorMessage(int code);

    /**
     * ssl.h wrappers
     */
    virtual int SSL_read(SSLConnection* conn, void* buf, int num) = 0;

    virtual int SSL_write(SSLConnection* conn, const void* buf, int num) = 0;

    virtual unsigned long ERR_get_error() = 0;

    virtual char* ERR_error_string(unsigned long e, char* buf) = 0;

    virtual int SSL_get_error(const SSLConnection* conn, int ret) = 0;

    virtual int SSL_shutdown(SSLConnection* conn) = 0;

    virtual void SSL_free(SSLConnection* conn) = 0;

    enum class ConnectionDirection { kIncoming, kOutgoing };

    /**
     * Initializes an OpenSSL context according to the provided settings. Only settings which are
     * acceptable on non-blocking connections are set. "direction" specifies whether the SSL_CTX
     * will be used to make outgoing connections or accept incoming connections.
     */
    virtual Status initSSLContext(SSL_CTX* context,
                                  const SSLParams& params,
                                  ConnectionDirection direction) = 0;

    /**
     * Fetches a peer certificate and validates it if it exists. If validation fails, but weak
     * validation is enabled, boost::none will be returned. If validation fails, and invalid
     * certificates are not allowed, a non-OK status will be returned. If validation is successful,
     * an engaged optional containing the certificate's subject name, and any roles acquired by
     * X509 authorization will be returned.
     */
    virtual StatusWith<boost::optional<SSLPeerInfo>> parseAndValidatePeerCertificate(
        SSL* ssl, const std::string& remoteHost) = 0;
};

// Access SSL functions through this instance.
SSLManagerInterface* getSSLManager();

extern bool isSSLServer;

/**
 * The global SSL configuration. This should be accessed only after global initialization has
 * completed. If it must be accessed in an initializer, the initializer should have
 * "EndStartupOptionStorage" as a prerequisite.
 */
const SSLParams& getSSLGlobalParams();


/**
 * Returns true if the `nameToMatch` is a valid match against the `certHostName` requirement from an
 * x.509 certificate.  Matches a remote host name to an x.509 host name, including wildcards.
 */
bool hostNameMatchForX509Certificates(std::string nameToMatch, std::string certHostName);
}  // namespace mongo
#endif  // #ifdef MONGO_CONFIG_SSL