summaryrefslogtreecommitdiff
path: root/cpp/src/IceSSL/SSLEngine.cpp
blob: 41c598140c929e61914cb1e701e88051140dbca6 (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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// **********************************************************************
//
// Copyright (c) 2003-2018 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

#include <IceSSL/SSLEngine.h>
#include <IceSSL/TrustManager.h>
#include <IceSSL/ConnectionInfo.h>

#include <IceUtil/StringUtil.h>

#include <Ice/Communicator.h>
#include <Ice/Properties.h>
#include <Ice/Logger.h>
#include <Ice/LoggerUtil.h>
#include <Ice/LocalException.h>

#include <string>

using namespace std;
using namespace Ice;
using namespace IceUtil;
using namespace IceSSL;

IceUtil::Shared* IceSSL::upCast(IceSSL::SSLEngine* p) { return p; }

IceSSL::SSLEngine::SSLEngine(const Ice::CommunicatorPtr& communicator) :
    _initialized(false),
    _communicator(communicator),
    _logger(communicator->getLogger()),
    _trustManager(new TrustManager(communicator))
{
}

IceSSL::CertificateVerifierPtr
IceSSL::SSLEngine::getCertificateVerifier() const
{
    return _verifier;
}

void
IceSSL::SSLEngine::setCertificateVerifier(const IceSSL::CertificateVerifierPtr& verifier)
{
    _verifier = verifier;
}

IceSSL::PasswordPromptPtr
IceSSL::SSLEngine::getPasswordPrompt() const
{
    return _prompt;
}

void
IceSSL::SSLEngine::setPasswordPrompt(const IceSSL::PasswordPromptPtr& prompt)
{
    _prompt = prompt;
}

string
IceSSL::SSLEngine::password(bool /*encrypting*/)
{
    if(_prompt)
    {
        try
        {
            return _prompt->getPassword();
        }
        catch(...)
        {
            //
            // Don't allow exceptions to cross an OpenSSL boundary.
            //
            return string();
        }
    }
    else
    {
        return _password;
    }
}

bool
IceSSL::SSLEngine::initialized() const
{
    Mutex::Lock lock(_mutex);
    return _initialized;
}

string
IceSSL::SSLEngine::getPassword() const
{
    return _password;
}

void
IceSSL::SSLEngine::setPassword(const std::string& password)
{
    _password = password;
}

void
IceSSL::SSLEngine::initialize()
{
    const string propPrefix = "IceSSL.";
    const PropertiesPtr properties = communicator()->getProperties();

    //
    // CheckCertName determines whether we compare the name in a peer's
    // certificate against its hostname.
    //
    _checkCertName = properties->getPropertyAsIntWithDefault(propPrefix + "CheckCertName", 0) > 0;

    //
    // VerifyDepthMax establishes the maximum length of a peer's certificate
    // chain, including the peer's certificate. A value of 0 means there is
    // no maximum.
    //
    _verifyDepthMax = properties->getPropertyAsIntWithDefault(propPrefix + "VerifyDepthMax", 3);

    //
    // VerifyPeer determines whether certificate validation failures abort a connection.
    //
    _verifyPeer = properties->getPropertyAsIntWithDefault(propPrefix + "VerifyPeer", 2);

    if(_verifyPeer < 0 || _verifyPeer > 2)
    {
        throw PluginInitializationException(__FILE__, __LINE__, "IceSSL: invalid value for " + propPrefix +
                                            "VerifyPeer");
    }

    _securityTraceLevel = properties->getPropertyAsInt("IceSSL.Trace.Security");
    _securityTraceCategory = "Security";
}

void
IceSSL::SSLEngine::verifyPeerCertName(const string& address, const ConnectionInfoPtr& info)
{
    //
    // For an outgoing connection, we compare the proxy address (if any) against
    // fields in the server's certificate (if any).
    //
    if(_checkCertName && !info->certs.empty() && !address.empty())
    {
        const CertificatePtr cert = info->certs[0];

        //
        // Extract the IP addresses and the DNS names from the subject
        // alternative names.
        //
        vector<pair<int, string> > subjectAltNames = cert->getSubjectAlternativeNames();
        vector<string> ipAddresses;
        vector<string> dnsNames;
        for(vector<pair<int, string> >::const_iterator p = subjectAltNames.begin(); p != subjectAltNames.end(); ++p)
        {
            if(p->first == AltNAmeIP)
            {
                ipAddresses.push_back(IceUtilInternal::toLower(p->second));
            }
            else if(p->first == AltNameDNS)
            {
                dnsNames.push_back(IceUtilInternal::toLower(p->second));
            }
        }

        bool certNameOK = false;
        string addrLower = IceUtilInternal::toLower(address);
        bool isIpAddress = IceInternal::isIpAddress(address);

        //
        // If address is an IP address, compare it to the subject alternative names IP adddress
        //
        if(isIpAddress)
        {
            certNameOK = find(ipAddresses.begin(), ipAddresses.end(), addrLower) != ipAddresses.end();
        }
        else
        {
            //
            // If subjectAlt is empty compare it ot the subject CN, othewise
            // compare it to the to the subject alt name dnsNames
            //
            if(dnsNames.empty())
            {
                DistinguishedName d = cert->getSubjectDN();
                string dn = IceUtilInternal::toLower(string(d));
                string cn = "cn=" + addrLower;
                string::size_type pos = dn.find(cn);
                if(pos != string::npos)
                {
                    //
                    // Ensure we match the entire common name.
                    //
                    certNameOK = (pos + cn.size() == dn.size()) || (dn[pos + cn.size()] == ',');
                }
            }
            else
            {
                certNameOK = find(dnsNames.begin(), dnsNames.end(), addrLower) != dnsNames.end();
            }
        }

        if(!certNameOK)
        {
            ostringstream ostr;
            ostr << "IceSSL: certificate validation failure: "
                 << (isIpAddress ? "IP address mismatch" : "Hostname mismatch");
            string msg = ostr.str();
            if(_securityTraceLevel >= 1)
            {
                Trace out(_logger, _securityTraceCategory);
                out << msg;
            }

            if(_verifyPeer > 0)
            {
                throw SecurityException(__FILE__, __LINE__, msg);
            }
        }
    }
}

void
IceSSL::SSLEngine::verifyPeer(const string& address, const ConnectionInfoPtr& info, const string& desc)
{
    const CertificateVerifierPtr verifier = getCertificateVerifier();
    if(_verifyDepthMax > 0 && static_cast<int>(info->certs.size()) > _verifyDepthMax)
    {
        ostringstream ostr;
        ostr << (info->incoming ? "incoming" : "outgoing") << " connection rejected:\n"
                << "length of peer's certificate chain (" << info->certs.size() << ") exceeds maximum of "
                << _verifyDepthMax;
        string msg = ostr.str();
        if(_securityTraceLevel >= 1)
        {
            _logger->trace(_securityTraceCategory, msg + "\n" + desc);
        }
        throw SecurityException(__FILE__, __LINE__, msg);
    }

    if(!_trustManager->verify(info, desc))
    {
        string msg = string(info->incoming ? "incoming" : "outgoing") + " connection rejected by trust manager";
        if(_securityTraceLevel >= 1)
        {
            _logger->trace(_securityTraceCategory, msg + "\n" + desc);
        }
        throw SecurityException(__FILE__, __LINE__, msg);
    }

    if(verifier && !verifier->verify(info))
    {
        string msg = string(info->incoming ? "incoming" : "outgoing") + " connection rejected by certificate verifier";
        if(_securityTraceLevel >= 1)
        {
            _logger->trace(_securityTraceCategory, msg + "\n" + desc);
        }
        throw SecurityException(__FILE__, __LINE__, msg);
    }
}

bool
IceSSL::SSLEngine::getCheckCertName() const
{
    return _checkCertName;
}

int
IceSSL::SSLEngine::getVerifyPeer() const
{
    return _verifyPeer;
}

int
IceSSL::SSLEngine::securityTraceLevel() const
{
    return _securityTraceLevel;
}

std::string
IceSSL::SSLEngine::securityTraceCategory() const
{
    return _securityTraceCategory;
}