summaryrefslogtreecommitdiff
path: root/cpp/src/Ice/SslConnectionOpenSSLServer.cpp
blob: d58e797e1c9f764bae530f4db15a3f5da804a574 (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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
// **********************************************************************
//
// Copyright (c) 2001
// MutableRealms, Inc.
// Huntsville, AL, USA
//
// All Rights Reserved
//
// **********************************************************************

#include <string>
#include <sstream>
#include <Ice/Network.h>
#include <Ice/Security.h>
#include <Ice/SecurityException.h>
#include <Ice/SslConnectionOpenSSLServer.h>

#include <Ice/TraceLevels.h>
#include <Ice/Logger.h>

using IceSecurity::Ssl::CertificateException;
using IceSecurity::Ssl::ProtocolException;
using IceSecurity::Ssl::SystemPtr;

using namespace IceInternal;
using namespace std;

using std::string;
using std::ostringstream;
using std::hex;
using std::dec;

//////////////////////////////////////
////////// ServerConnection //////////
//////////////////////////////////////

//
// Public Methods
//

IceSecurity::Ssl::OpenSSL::ServerConnection::ServerConnection(SSL* connection, const SystemPtr& system) :
                                            Connection(connection, system)
{
}

IceSecurity::Ssl::OpenSSL::ServerConnection::~ServerConnection()
{
    ICE_METHOD_INV("OpenSSL::ServerConnection::~ServerConnection()");

    ICE_METHOD_RET("OpenSSL::ServerConnection::~ServerConnection()");
}

void
IceSecurity::Ssl::OpenSSL::ServerConnection::shutdown()
{
    ICE_METHOD_INV("OpenSSL::ServerConnection::shutdown()");

    Connection::shutdown();

    ICE_METHOD_RET("OpenSSL::ServerConnection::shutdown()");
}

int
IceSecurity::Ssl::OpenSSL::ServerConnection::init(int timeout)
{
    ICE_METHOD_INV("OpenSSL::ServerConnection::init()");

    int retCode = SSL_is_init_finished(_sslConnection);
    
    while (!retCode)
    {
        int i = 0;

        _readTimeout = timeout > _handshakeReadTimeout ? timeout : _handshakeReadTimeout;

        if (_initWantRead)
        {
            i = readSelect(_readTimeout);
        }
        else if (_initWantWrite)
        {
            i = writeSelect(timeout);
        }

        if (_initWantRead && i == 0)
        {
            return 0;
        }

        if (_initWantWrite && i == 0)
        {
            return 0;
        }

        _initWantRead = 0;
        _initWantWrite = 0;

        int result = accept();

        // Find out what the error was (if any).
        int code = getLastError();

        // We're doing an Accept and we don't get a retry on the socket.
        if ((result <= 0) && (BIO_sock_should_retry(result) == 0))
        {
            // Socket can't retry - bad scene, find out why.
            long verify_error = SSL_get_verify_result(_sslConnection);

            if (verify_error != X509_V_OK)
            {
                CertificateException certEx(__FILE__, __LINE__);

                certEx._message = "SSL certificate verification error.";

                ICE_EXCEPTION(certEx._message);

                throw certEx;
            }
            else
            {
                ProtocolException protocolEx(__FILE__, __LINE__);

                protocolEx._message = "Encountered an SSL Protocol violation during handshake.";

                ICE_SSLERRORS(protocolEx._message);
                ICE_EXCEPTION(protocolEx._message);

                throw protocolEx;
            }
        }

        switch (code)
        {
            case SSL_ERROR_WANT_READ:
            {
                _initWantRead = 1;
                break;
            }

            case SSL_ERROR_WANT_WRITE:
            {
                _initWantWrite = 1;
                break;
            }

            
            case SSL_ERROR_NONE:
            case SSL_ERROR_WANT_X509_LOOKUP:
            {
                // Do nothing, life is good!
                break;
            }

            case SSL_ERROR_SYSCALL:
            {
                // This is a SOCKET_ERROR, but we don't use
                // this define here as OpenSSL doesn't refer
                // to it as a SOCKET_ERROR (but that's what it is
                // if you look at their code).
                if(result == -1)
                {
                    if (interrupted())
                    {
                        break;
                    }

                    if (wouldBlock())
                    {
                        readSelect(_readTimeout);
                        break;
                    }

                    if (connectionLost())
                    {
                        ICE_DEV_DEBUG("ServerConnection::init(): Throwing ConnectionLostException... SslConnectionOpenSSLServer.cpp, 207");
                        ConnectionLostException ex(__FILE__, __LINE__);
                        ex.error = getSocketErrno();
                        throw ex;
                    }
                    else
                    {
                        ICE_DEV_DEBUG("ServerConnection::init(): Throwing SocketException... SslConnectionOpenSSLServer.cpp, 214");
                        SocketException ex(__FILE__, __LINE__);
                        ex.error = getSocketErrno();
                        throw ex;
                    }
                }
                else
                {
                    ProtocolException protocolEx(__FILE__, __LINE__);

                    // Protocol Error: Unexpected EOF
                    protocolEx._message = "Encountered an EOF during handshake that violates the SSL Protocol.";

                    ICE_SSLERRORS(protocolEx._message);
                    ICE_EXCEPTION(protocolEx._message);

                    throw protocolEx;
                }
            }

            case SSL_ERROR_SSL:
            {
                ProtocolException protocolEx(__FILE__, __LINE__);

                protocolEx._message = "Encountered a violation of the SSL Protocol during handshake.";

                ICE_SSLERRORS(protocolEx._message);
                ICE_EXCEPTION(protocolEx._message);

                throw protocolEx;
            }
        }

        retCode = SSL_is_init_finished(_sslConnection);

        if (retCode > 0)
        {
            // Init finished, look at the connection information.
            showConnectionInfo();
        }
    }

    ICE_METHOD_RET("OpenSSL::ServerConnection::init()");

    return retCode;
}

int
IceSecurity::Ssl::OpenSSL::ServerConnection::read(Buffer& buf, int timeout)
{
    ICE_METHOD_INV("OpenSSL::ServerConnection::read(Buffer&, int)");

    int bytesRead = 1;
    int totalBytesRead = 0;

    // We keep reading until we're done.
    while ((buf.i != buf.b.end()) && bytesRead)
    {
        // Copy over bytes from _inBuffer to buf.
        bytesRead = readInBuffer(buf);

        // Nothing in the _inBuffer?
        if (!bytesRead)
        {
            // Read from SSL.
            bytesRead = readSSL(buf, timeout);
        }

        // Keep track of the total bytes read.
        totalBytesRead += bytesRead;
    }

    ICE_METHOD_RET("OpenSSL::ServerConnection::read(Buffer&, int)");

    return totalBytesRead;
}

int
IceSecurity::Ssl::OpenSSL::ServerConnection::write(Buffer& buf, int timeout)
{
    ICE_METHOD_INV("OpenSSL::ServerConnection::write(Buffer&, int)");

    int totalBytesWritten = 0;
    int bytesWritten = 0;

    int packetSize = buf.b.end() - buf.i;

#ifdef WIN32
    //
    // Limit packet size to avoid performance problems on WIN32.
    //
    if (packetSize > 64 * 1024)
    {
        packetSize = 64 * 1024;
    }
#endif

    int initReturn = 0;

    // We keep writing until we're done.
    while (buf.i != buf.b.end())
    {
        // Ensure we're initialized.
        initReturn = initialize(timeout);

        if (initReturn <= 0)
        {
            // Retry the initialize call
            continue;
        }

        // initReturn must be > 0, so we're okay to try a write

        // Perform a select on the socket.
        if (!writeSelect(timeout))
        {
            // We're done here.
            break;
        }

        bytesWritten = sslWrite((char *)buf.i, packetSize);

        switch (getLastError())
        {
            case SSL_ERROR_NONE:
            {
	        if (_traceLevels->network >= 3)
	        {
                    ostringstream s;
                    s << "sent " << bytesWritten << " of " << packetSize;
                    s << " bytes via ssl\n" << fdToString(SSL_get_fd(_sslConnection));
	            _logger->trace(_traceLevels->networkCat, s.str());
                }

                totalBytesWritten += bytesWritten;

                buf.i += bytesWritten;

                if (packetSize > buf.b.end() - buf.i)
                {
                    packetSize = buf.b.end() - buf.i;
                }
                continue;
            }

            case SSL_ERROR_WANT_WRITE:  // Retry...
            {
                ICE_PROTOCOL("Error SSL_ERROR_WANT_WRITE: Repeating as per protocol.");

                continue;
            }

            case SSL_ERROR_WANT_READ:   // The demo server ignores this error.
            {
                ICE_PROTOCOL("Error SSL_ERROR_WANT_READ: Ignoring as per protocol.");

                continue;
            }

            case SSL_ERROR_WANT_X509_LOOKUP:    // The demo server ignores this error.
            {
                ICE_PROTOCOL("Error SSL_ERROR_WANT_X509_LOOKUP: Repeating as per protocol.");

                continue;
            }

            case SSL_ERROR_SYSCALL:
            {
                if (bytesWritten == -1)
                {
                    // IO Error in underlying BIO

	            if (interrupted())
	            {
		        break;
	            }

                    if (wouldBlock())
	            {
                        break;
                    }

                    if (connectionLost())
	            {
                        ICE_DEV_DEBUG("ServerConnection::write(): Throwing ConnectionLostException... SslConnectionOpenSSLServer.cpp, 388");
	                ConnectionLostException ex(__FILE__, __LINE__);
                        ex.error = getSocketErrno();
                        throw ex;
	            }
	            else
	            {
                        ICE_DEV_DEBUG("ServerConnection::write(): Throwing SocketException... SslConnectionOpenSSLServer.cpp, 395");
		        SocketException ex(__FILE__, __LINE__);
		        ex.error = getSocketErrno();
		        throw ex;
	            }
                }
                else
                {
                    ProtocolException protocolEx(__FILE__, __LINE__);

                    // Protocol Error: Unexpected EOF
                    protocolEx._message = "Encountered an EOF that violates the SSL Protocol.";

                    ICE_SSLERRORS(protocolEx._message);
                    ICE_EXCEPTION(protocolEx._message);

                    throw protocolEx;
                }
            }

            case SSL_ERROR_SSL:
            {
                ProtocolException protocolEx(__FILE__, __LINE__);

                protocolEx._message = "Encountered a violation of the SSL Protocol.";

                ICE_SSLERRORS(protocolEx._message);
                ICE_EXCEPTION(protocolEx._message);

                throw protocolEx;
            }

            case SSL_ERROR_ZERO_RETURN:
            {
                ICE_EXCEPTION("SSL_ERROR_ZERO_RETURN");
                ICE_DEV_DEBUG("ServerConnection::write(): Throwing ConnectionLostException... SslConnectionOpenSSLServer.cpp, 430");

                ConnectionLostException ex(__FILE__, __LINE__);
                ex.error = getSocketErrno();
                throw ex;
            }
        }
    }

    ICE_METHOD_RET("OpenSSL::ServerConnection::write(Buffer&, int)");

    return totalBytesWritten;
}

//
// Protected Methods
//

void
IceSecurity::Ssl::OpenSSL::ServerConnection::showConnectionInfo()
{
    ICE_METHOD_INV("OpenSSL::ServerConnection::showConnectionInfo()");

    // Only in extreme cases do we enable this, partially because it doesn't use the Logger.
    if (ICE_SECURITY_LEVEL_PROTOCOL_DEBUG)
    {
        ICE_PROTOCOL_DEBUG("Begin Connection Information");

        BIO* bio = BIO_new_fp(stdout, BIO_NOCLOSE);

        showCertificateChain(bio);

        showPeerCertificate(bio,"Server");

        showSharedCiphers(bio);

        showSelectedCipherInfo(bio);

        showHandshakeStats(bio);

        showSessionInfo(bio);

        ICE_PROTOCOL_DEBUG("End of Connection Information");

        if (bio != 0)
        {
            BIO_free(bio);
            bio = 0;
        }
    }

    ICE_METHOD_RET("OpenSSL::ServerConnection::showConnectionInfo()");
}