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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
|
// **********************************************************************
//
// Copyright (c) 2003-2015 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/SecureTransportTransceiverI.h>
#include <IceSSL/Instance.h>
#include <IceSSL/SSLEngine.h>
#include <Ice/LoggerUtil.h>
#include <Ice/LocalException.h>
#ifdef ICE_USE_SECURE_TRANSPORT
using namespace std;
using namespace Ice;
using namespace IceSSL;
namespace
{
string
trustResultDescription(SecTrustResultType result)
{
switch(result)
{
case kSecTrustResultInvalid:
{
return "Invalid setting or result";
}
case kSecTrustResultDeny:
{
return "The user specified that the certificate should not be trusted";
}
case kSecTrustResultRecoverableTrustFailure:
case kSecTrustResultFatalTrustFailure:
{
return "Trust denied";
}
case kSecTrustResultOtherError:
{
return "Other error internal error";
}
default:
{
assert(false);
return "";
}
}
}
string
protocolName(SSLProtocol protocol)
{
switch(protocol)
{
case kSSLProtocol2:
return "SSL 2.0";
case kSSLProtocol3:
return "SSL 3.0";
case kTLSProtocol1:
return "TLS 1.0";
case kTLSProtocol11:
return "TLS 1.1";
case kTLSProtocol12:
return "TLS 1.2";
default:
return "Unknown";
}
}
//
// Socket write callback
//
OSStatus
socketWrite(SSLConnectionRef connection, const void* data, size_t* length)
{
const TransceiverI* transceiver = static_cast<const TransceiverI*>(connection);
assert(transceiver);
return transceiver->writeRaw(reinterpret_cast<const char*>(data), length);
}
//
// Socket read callback
//
OSStatus
socketRead(SSLConnectionRef connection, void* data, size_t* length)
{
const TransceiverI* transceiver = static_cast<const TransceiverI*>(connection);
assert(transceiver);
return transceiver->readRaw(reinterpret_cast<char*>(data), length);
}
void
checkTrustResult(SecTrustRef trust, const SecureTransportEnginePtr& engine, const InstancePtr& instance)
{
OSStatus err = noErr;
SecTrustResultType trustResult = kSecTrustResultOtherError;
if(trust)
{
if((err = SecTrustSetAnchorCertificates(trust, engine->getCertificateAuthorities())))
{
throw SecurityException(__FILE__, __LINE__, "IceSSL: handshake failure:\n" + errorToString(err));
}
//
// Disable network fetch, we don't want this to block.
//
if((err = SecTrustSetNetworkFetchAllowed(trust, false)))
{
throw ProtocolException(__FILE__, __LINE__, "IceSSL: handshake failure:\n" + errorToString(err));
}
//
// Evaluate the trust
//
if((err = SecTrustEvaluate(trust, &trustResult)))
{
throw ProtocolException(__FILE__, __LINE__, "IceSSL: handshake failure:\n" + errorToString(err));
}
}
switch(trustResult)
{
case kSecTrustResultUnspecified:
case kSecTrustResultProceed:
{
//
// Trust verify success.
//
break;
}
case kSecTrustResultInvalid:
//case kSecTrustResultConfirm: // Used in old OS X versions
case kSecTrustResultDeny:
case kSecTrustResultRecoverableTrustFailure:
case kSecTrustResultFatalTrustFailure:
case kSecTrustResultOtherError:
{
if(engine->getVerifyPeer() == 0)
{
if(instance->traceLevel() >= 1)
{
ostringstream os;
os << "IceSSL: ignoring certificate verification failure\n" << trustResultDescription(trustResult);
instance->logger()->trace(instance->traceCategory(), os.str());
}
break;
}
else
{
ostringstream os;
os << "IceSSL: certificate verification failure\n" << trustResultDescription(trustResult);
string msg = os.str();
if(instance->traceLevel() >= 1)
{
instance->logger()->trace(instance->traceCategory(), msg);
}
throw ProtocolException(__FILE__, __LINE__, msg);
}
}
}
}
}
IceInternal::NativeInfoPtr
IceSSL::TransceiverI::getNativeInfo()
{
return _stream;
}
IceInternal::SocketOperation
IceSSL::TransceiverI::initialize(IceInternal::Buffer& readBuffer, IceInternal::Buffer& writeBuffer, bool&)
{
IceInternal::SocketOperation status = _stream->connect(readBuffer, writeBuffer);
if(status != IceInternal::SocketOperationNone)
{
return status;
}
OSStatus err = 0;
if(!_ssl)
{
//
// Initialize SSL context
//
_ssl = _engine->newContext(_incoming);
if((err = SSLSetIOFuncs(_ssl, socketRead, socketWrite)))
{
throw SecurityException(__FILE__, __LINE__, "IceSSL: setting IO functions failed\n" +
errorToString(err));
}
if((err = SSLSetConnection(_ssl, reinterpret_cast<SSLConnectionRef>(this))))
{
throw SecurityException(__FILE__, __LINE__, "IceSSL: setting SSL connection failed\n" +
errorToString(err));
}
}
SSLSessionState state;
SSLGetSessionState(_ssl, &state);
//
// SSL Handshake
//
while(state == kSSLHandshake || state == kSSLIdle)
{
err = SSLHandshake(_ssl);
if(err == noErr)
{
break; // We're done!
}
else if(err == errSSLWouldBlock)
{
assert(_flags & SSLWantRead || _flags & SSLWantWrite);
return _flags & SSLWantRead ? IceInternal::SocketOperationRead : IceInternal::SocketOperationWrite;
}
else if(err == errSSLPeerAuthCompleted)
{
assert(!_trust);
err = SSLCopyPeerTrust(_ssl, &_trust);
if(_incoming && err == errSSLBadCert && _engine->getVerifyPeer() == 1)
{
// This happens in 10.10 when the client doesn't provide
// a certificate and the server is configured to try
// authenticate
continue;
}
if(err == noErr)
{
checkTrustResult(_trust, _engine, _instance);
continue; // Call SSLHandshake to resume the handsake.
}
// Let it fall through, this will raise a SecurityException with the SSLCopyPeerTrust error.
}
else if(err == errSSLClosedGraceful || err == errSSLClosedAbort)
{
throw ConnectionLostException(__FILE__, __LINE__, 0);
}
IceInternal::Address remoteAddr;
string desc = "<not available>";
if(IceInternal::fdToRemoteAddress(_stream->fd(), remoteAddr))
{
desc = IceInternal::addrToString(remoteAddr);
}
ostringstream os;
os << "IceSSL: ssl error occurred for new " << (_incoming ? "incoming" : "outgoing") << " connection:\n"
<< "remote address = " << desc << "\n" << errorToString(err);
throw ProtocolException(__FILE__, __LINE__, os.str());
}
_engine->verifyPeer(_stream->fd(), _host, getNativeConnectionInfo());
if(_instance->engine()->securityTraceLevel() >= 1)
{
assert(_ssl);
Trace out(_instance->logger(), _instance->traceCategory());
out << "SSL summary for " << (_incoming ? "incoming" : "outgoing") << " connection\n";
SSLProtocol protocol;
SSLGetNegotiatedProtocolVersion(_ssl, &protocol);
const string sslProtocolName = protocolName(protocol);
SSLCipherSuite cipher;
SSLGetNegotiatedCipher(_ssl, &cipher);
const string sslCipherName = _engine->getCipherName(cipher);
if(sslCipherName.empty())
{
out << "unknown cipher\n";
}
else
{
out << "cipher = " << sslCipherName << "\n";
out << "protocol = " << sslProtocolName << "\n";
}
out << toString();
}
return IceInternal::SocketOperationNone;
}
IceInternal::SocketOperation
IceSSL::TransceiverI::closing(bool initiator, const Ice::LocalException&)
{
// If we are initiating the connection closure, wait for the peer
// to close the TCP/IP connection. Otherwise, close immediately.
return initiator ? IceInternal::SocketOperationRead : IceInternal::SocketOperationNone;
}
void
IceSSL::TransceiverI::close()
{
if(_trust)
{
CFRelease(_trust);
_trust = 0;
}
if(_ssl)
{
SSLClose(_ssl);
CFRelease(_ssl);
_ssl = 0;
}
_stream->close();
}
IceInternal::SocketOperation
IceSSL::TransceiverI::write(IceInternal::Buffer& buf)
{
if(!_stream->isConnected())
{
return _stream->write(buf);
}
if(buf.i == buf.b.end())
{
return IceInternal::SocketOperationNone;
}
//
// It's impossible for packetSize to be more than an Int.
//
size_t packetSize = std::min(static_cast<size_t>(buf.b.end() - buf.i), _maxSendPacketSize);
while(buf.i != buf.b.end())
{
size_t processed = 0;
OSStatus err = _buffered ? SSLWrite(_ssl, 0, 0, &processed) :
SSLWrite(_ssl, reinterpret_cast<const void*>(buf.i), packetSize, &processed);
if(err)
{
if(err == errSSLWouldBlock)
{
if(_buffered == 0)
{
_buffered = processed;
}
assert(_flags & SSLWantWrite);
return IceInternal::SocketOperationWrite;
}
if(err == errSSLClosedGraceful)
{
throw ConnectionLostException(__FILE__, __LINE__, 0);
}
//
// SSL protocol errors are defined in SecureTransport.h are in the range
// -9800 to -9849
//
if(err <= -9800 && err >= -9849)
{
throw ProtocolException(__FILE__, __LINE__, "IceSSL: error during write:\n" + errorToString(err));
}
errno = err;
if(IceInternal::connectionLost())
{
throw ConnectionLostException(__FILE__, __LINE__, IceInternal::getSocketErrno());
}
else
{
throw SocketException(__FILE__, __LINE__, IceInternal::getSocketErrno());
}
}
if(_buffered)
{
buf.i += _buffered;
_buffered = 0;
}
else
{
buf.i += processed;
}
if(packetSize > buf.b.end() - buf.i)
{
packetSize = buf.b.end() - buf.i;
}
}
return IceInternal::SocketOperationNone;
}
IceInternal::SocketOperation
IceSSL::TransceiverI::read(IceInternal::Buffer& buf, bool&)
{
if(!_stream->isConnected())
{
return _stream->read(buf);
}
//
// Note: we don't set the hasMoreData flag in this implementation.
// We assume that SecureTransport doesn't read more SSL records
// than necessary to fill the requested data and that the sender
// sends Ice messages in individual SSL records.
//
if(buf.i == buf.b.end())
{
return IceInternal::SocketOperationNone;
}
size_t packetSize = std::min(static_cast<size_t>(buf.b.end() - buf.i), _maxRecvPacketSize);
while(buf.i != buf.b.end())
{
size_t processed = 0;
OSStatus err = SSLRead(_ssl, reinterpret_cast<void*>(buf.i), packetSize, &processed);
if(err)
{
if(err == errSSLWouldBlock)
{
buf.i += processed;
assert(_flags & SSLWantRead);
return IceInternal::SocketOperationRead;
}
if(err == errSSLClosedGraceful || err == errSSLClosedAbort)
{
throw ConnectionLostException(__FILE__, __LINE__, 0);
}
//
// SSL protocol errors are defined in SecureTransport.h are in the range
// -9800 to -9849
//
if(err <= -9800 && err >= -9849)
{
throw ProtocolException(__FILE__, __LINE__, "IceSSL: error during read:\n" + errorToString(err));
}
errno = err;
if(IceInternal::connectionLost())
{
throw ConnectionLostException(__FILE__, __LINE__, IceInternal::getSocketErrno());
}
else
{
throw SocketException(__FILE__, __LINE__, IceInternal::getSocketErrno());
}
}
buf.i += processed;
if(packetSize > buf.b.end() - buf.i)
{
packetSize = buf.b.end() - buf.i;
}
}
return IceInternal::SocketOperationNone;
}
string
IceSSL::TransceiverI::protocol() const
{
return _instance->protocol();
}
string
IceSSL::TransceiverI::toString() const
{
return _stream->toString();
}
string
IceSSL::TransceiverI::toDetailedString() const
{
return toString();
}
Ice::ConnectionInfoPtr
IceSSL::TransceiverI::getInfo() const
{
return getNativeConnectionInfo();
}
void
IceSSL::TransceiverI::checkSendSize(const IceInternal::Buffer&)
{
}
void
IceSSL::TransceiverI::setBufferSize(int rcvSize, int sndSize)
{
_stream->setBufferSize(rcvSize, sndSize);
}
IceSSL::TransceiverI::TransceiverI(const InstancePtr& instance,
const IceInternal::StreamSocketPtr& stream,
const string& hostOrAdapterName,
bool incoming) :
_instance(instance),
_engine(SecureTransportEnginePtr::dynamicCast(instance->engine())),
_host(incoming ? "" : hostOrAdapterName),
_adapterName(incoming ? hostOrAdapterName : ""),
_incoming(incoming),
_stream(stream),
_ssl(0),
_trust(0),
_buffered(0)
{
//
// Limit the size of packets passed to SSLWrite/SSLRead to avoid
// blocking and holding too much memory.
//
_maxSendPacketSize = std::max(512, IceInternal::getSendBufferSize(_stream->fd()));
_maxRecvPacketSize = std::max(512, IceInternal::getRecvBufferSize(_stream->fd()));
}
IceSSL::TransceiverI::~TransceiverI()
{
}
NativeConnectionInfoPtr
IceSSL::TransceiverI::getNativeConnectionInfo() const
{
NativeConnectionInfoPtr info = new NativeConnectionInfo();
IceInternal::fdToAddressAndPort(_stream->fd(), info->localAddress, info->localPort, info->remoteAddress,
info->remotePort);
if(_stream->fd() != INVALID_SOCKET)
{
info->rcvSize = IceInternal::getRecvBufferSize(_stream->fd());
info->sndSize = IceInternal::getSendBufferSize(_stream->fd());
}
if(_ssl)
{
for(int i = 0, count = SecTrustGetCertificateCount(_trust); i < count; ++i)
{
SecCertificateRef cert = SecTrustGetCertificateAtIndex(_trust, i);
CFRetain(cert);
CertificatePtr certificate = new Certificate(cert);
info->nativeCerts.push_back(certificate);
info->certs.push_back(certificate->encode());
}
SSLCipherSuite cipher;
SSLGetNegotiatedCipher(_ssl, &cipher);
info->cipher = _engine->getCipherName(cipher);
}
info->adapterName = _adapterName;
info->incoming = _incoming;
return info;
}
OSStatus
IceSSL::TransceiverI::writeRaw(const char* data, size_t* length) const
{
_flags &= ~SSLWantWrite;
try
{
ssize_t ret = _stream->write(data, *length);
if(ret < *length)
{
*length = static_cast<size_t>(ret);
_flags |= SSLWantWrite;
return errSSLWouldBlock;
}
}
catch(const Ice::ConnectionLostException&)
{
return errSSLClosedGraceful;
}
catch(const Ice::SocketException& ex)
{
return ex.error;
}
catch(...)
{
assert(false);
return IceInternal::getSocketErrno();
}
return noErr;
}
OSStatus
IceSSL::TransceiverI::readRaw(char* data, size_t* length) const
{
_flags &= ~SSLWantRead;
try
{
ssize_t ret = _stream->read(data, *length);
if(ret < *length)
{
*length = static_cast<size_t>(ret);
_flags |= SSLWantRead;
return errSSLWouldBlock;
}
}
catch(const Ice::ConnectionLostException&)
{
return errSSLClosedGraceful;
}
catch(const Ice::SocketException& ex)
{
return ex.error;
}
catch(...)
{
assert(false);
return IceInternal::getSocketErrno();
}
return noErr;
}
#endif
|