| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | using System.Diagnostics; |
| | 4 | | using System.Net.Security; |
| | 5 | | using System.Net.Sockets; |
| | 6 | | using System.Security.Authentication; |
| | 7 | | using System.Security.Cryptography.X509Certificates; |
| | 8 | |
|
| | 9 | | namespace Ice.SSL; |
| | 10 | |
|
| | 11 | | #pragma warning disable CA1001 // _sslStream is disposed by destroy. |
| | 12 | | internal sealed class TransceiverI : Ice.Internal.Transceiver |
| | 13 | | #pragma warning restore CA1001 |
| | 14 | | { |
| 1 | 15 | | public Socket fd() => _delegate.fd(); |
| | 16 | |
|
| | 17 | | public int initialize(Ice.Internal.Buffer readBuffer, Ice.Internal.Buffer writeBuffer, ref bool hasMoreData) |
| | 18 | | { |
| 1 | 19 | | if (!_isConnected) |
| | 20 | | { |
| 1 | 21 | | int status = _delegate.initialize(readBuffer, writeBuffer, ref hasMoreData); |
| 1 | 22 | | if (status != Ice.Internal.SocketOperation.None) |
| | 23 | | { |
| 1 | 24 | | return status; |
| | 25 | | } |
| 1 | 26 | | _isConnected = true; |
| | 27 | | } |
| | 28 | |
|
| 1 | 29 | | Ice.Internal.Network.setBlock(fd(), true); // SSL requires a blocking socket |
| | 30 | |
|
| 1 | 31 | | if (_sslStream == null) |
| | 32 | | { |
| | 33 | | try |
| | 34 | | { |
| 1 | 35 | | _sslStream = new SslStream( |
| 1 | 36 | | new NetworkStream(_delegate.fd(), ownsSocket: false), |
| 1 | 37 | | leaveInnerStreamOpen: false); |
| 1 | 38 | | } |
| 0 | 39 | | catch (IOException ex) |
| | 40 | | { |
| 0 | 41 | | if (Ice.Internal.Network.connectionLost(ex)) |
| | 42 | | { |
| 0 | 43 | | throw new Ice.ConnectionLostException(ex); |
| | 44 | | } |
| | 45 | | else |
| | 46 | | { |
| 0 | 47 | | throw new Ice.SocketException(ex); |
| | 48 | | } |
| | 49 | | } |
| 1 | 50 | | return Ice.Internal.SocketOperation.Connect; |
| | 51 | | } |
| | 52 | |
|
| | 53 | | Debug.Assert(_sslStream.IsAuthenticated); |
| 1 | 54 | | _authenticated = true; |
| | 55 | |
|
| 1 | 56 | | _cipher = _sslStream.CipherAlgorithm.ToString(); |
| 1 | 57 | | _instance.verifyPeer((ConnectionInfo)getInfo(_incoming, _adapterName, connectionId: ""), ToString()); |
| | 58 | |
|
| 1 | 59 | | if (_instance.securityTraceLevel() >= 1) |
| | 60 | | { |
| 0 | 61 | | _instance.traceStream(_sslStream, ToString()); |
| | 62 | | } |
| 1 | 63 | | return Ice.Internal.SocketOperation.None; |
| | 64 | | } |
| | 65 | |
|
| 1 | 66 | | public int closing(bool initiator, Ice.LocalException ex) => _delegate.closing(initiator, ex); |
| | 67 | |
|
| | 68 | | public void close() |
| | 69 | | { |
| 1 | 70 | | if (_sslStream != null) |
| | 71 | | { |
| 1 | 72 | | cancelSslHandshake(); |
| 1 | 73 | | _sslStream.Dispose(); // Disposing the stream also closes the socket. |
| 1 | 74 | | _sslStream = null; |
| | 75 | | } |
| | 76 | |
|
| 1 | 77 | | _delegate.close(); |
| 1 | 78 | | } |
| | 79 | |
|
| | 80 | | public Ice.Internal.EndpointI bind() |
| | 81 | | { |
| | 82 | | Debug.Assert(false); |
| 0 | 83 | | return null; |
| | 84 | | } |
| | 85 | |
|
| | 86 | | public void destroy() |
| | 87 | | { |
| 1 | 88 | | _delegate.destroy(); |
| 1 | 89 | | cancelSslHandshake(); |
| 1 | 90 | | _sslStream?.Dispose(); |
| 1 | 91 | | _sslHandshakeCts.Dispose(); |
| 1 | 92 | | } |
| | 93 | |
|
| | 94 | | public int write(Ice.Internal.Buffer buf) => |
| | 95 | | // Force caller to use async write. |
| 1 | 96 | | buf.b.hasRemaining() ? Ice.Internal.SocketOperation.Write : Ice.Internal.SocketOperation.None; |
| | 97 | |
|
| | 98 | | public int read(Ice.Internal.Buffer buf, ref bool hasMoreData) => |
| | 99 | | // Force caller to use async read. |
| 1 | 100 | | buf.b.hasRemaining() ? Ice.Internal.SocketOperation.Read : Ice.Internal.SocketOperation.None; |
| | 101 | |
|
| | 102 | | public bool startRead(Ice.Internal.Buffer buf, Ice.Internal.AsyncCallback callback, object state) |
| | 103 | | { |
| 1 | 104 | | if (!_isConnected) |
| | 105 | | { |
| 1 | 106 | | return _delegate.startRead(buf, callback, state); |
| | 107 | | } |
| | 108 | |
|
| | 109 | | Debug.Assert(_sslStream != null && _sslStream.IsAuthenticated); |
| | 110 | |
|
| | 111 | | try |
| | 112 | | { |
| 1 | 113 | | _readResult = _sslStream.ReadAsync(buf.b.rawBytes(), buf.b.position(), buf.b.remaining()); |
| 1 | 114 | | _readResult.ContinueWith( |
| 1 | 115 | | task => callback(state), |
| 1 | 116 | | TaskScheduler.Default); |
| 1 | 117 | | return false; |
| | 118 | | } |
| 0 | 119 | | catch (IOException ex) |
| | 120 | | { |
| 0 | 121 | | if (Ice.Internal.Network.connectionLost(ex)) |
| | 122 | | { |
| 0 | 123 | | throw new Ice.ConnectionLostException(ex); |
| | 124 | | } |
| 0 | 125 | | if (Ice.Internal.Network.timeout(ex)) |
| | 126 | | { |
| 0 | 127 | | throw new Ice.TimeoutException(); |
| | 128 | | } |
| 0 | 129 | | throw new Ice.SocketException(ex); |
| | 130 | | } |
| 0 | 131 | | catch (ObjectDisposedException ex) |
| | 132 | | { |
| 0 | 133 | | throw new Ice.ConnectionLostException(ex); |
| | 134 | | } |
| 0 | 135 | | catch (Exception ex) |
| | 136 | | { |
| 0 | 137 | | throw new Ice.SyscallException(ex); |
| | 138 | | } |
| 1 | 139 | | } |
| | 140 | |
|
| | 141 | | public void finishRead(Ice.Internal.Buffer buf) |
| | 142 | | { |
| 1 | 143 | | if (!_isConnected) |
| | 144 | | { |
| 1 | 145 | | _delegate.finishRead(buf); |
| 1 | 146 | | return; |
| | 147 | | } |
| 1 | 148 | | else if (_sslStream == null) // Transceiver was closed |
| | 149 | | { |
| 0 | 150 | | _readResult = null; |
| 0 | 151 | | return; |
| | 152 | | } |
| | 153 | |
|
| | 154 | | Debug.Assert(_readResult != null); |
| | 155 | | try |
| | 156 | | { |
| | 157 | | int ret; |
| | 158 | | try |
| | 159 | | { |
| 1 | 160 | | ret = _readResult.Result; |
| 1 | 161 | | } |
| 1 | 162 | | catch (AggregateException ex) |
| | 163 | | { |
| 1 | 164 | | throw ex.InnerException; |
| | 165 | | } |
| | 166 | |
|
| 1 | 167 | | if (ret == 0) |
| | 168 | | { |
| 1 | 169 | | throw new Ice.ConnectionLostException(); |
| | 170 | | } |
| | 171 | | Debug.Assert(ret > 0); |
| 1 | 172 | | buf.b.position(buf.b.position() + ret); |
| 1 | 173 | | } |
| 1 | 174 | | catch (Ice.LocalException) |
| | 175 | | { |
| 1 | 176 | | throw; |
| | 177 | | } |
| 1 | 178 | | catch (IOException ex) |
| | 179 | | { |
| 1 | 180 | | if (Ice.Internal.Network.connectionLost(ex)) |
| | 181 | | { |
| 1 | 182 | | throw new Ice.ConnectionLostException(ex); |
| | 183 | | } |
| 0 | 184 | | if (Ice.Internal.Network.timeout(ex)) |
| | 185 | | { |
| 0 | 186 | | throw new Ice.TimeoutException(); |
| | 187 | | } |
| 0 | 188 | | throw new Ice.SocketException(ex); |
| | 189 | | } |
| 0 | 190 | | catch (ObjectDisposedException ex) |
| | 191 | | { |
| 0 | 192 | | throw new Ice.ConnectionLostException(ex); |
| | 193 | | } |
| 0 | 194 | | catch (Exception ex) |
| | 195 | | { |
| 0 | 196 | | throw new Ice.SyscallException(ex); |
| | 197 | | } |
| 1 | 198 | | } |
| | 199 | |
|
| | 200 | | public bool startWrite(Internal.Buffer buf, Internal.AsyncCallback cb, object state, out bool messageWritten) |
| | 201 | | { |
| 1 | 202 | | if (!_isConnected) |
| | 203 | | { |
| 1 | 204 | | return _delegate.startWrite(buf, cb, state, out messageWritten); |
| | 205 | | } |
| | 206 | |
|
| | 207 | | Debug.Assert(_sslStream != null); |
| 1 | 208 | | if (!_authenticated) |
| | 209 | | { |
| 1 | 210 | | messageWritten = false; |
| 1 | 211 | | return startAuthenticate(cb, state); |
| | 212 | | } |
| | 213 | |
|
| | 214 | | try |
| | 215 | | { |
| 1 | 216 | | _writeResult = _sslStream.WriteAsync(buf.b.rawBytes(), buf.b.position(), buf.b.remaining()); |
| 1 | 217 | | _writeResult.ContinueWith(task => cb(state), TaskScheduler.Default); |
| 1 | 218 | | messageWritten = true; |
| 1 | 219 | | return false; |
| | 220 | | } |
| 0 | 221 | | catch (IOException ex) |
| | 222 | | { |
| 0 | 223 | | if (Ice.Internal.Network.connectionLost(ex)) |
| | 224 | | { |
| 0 | 225 | | throw new Ice.ConnectionLostException(ex); |
| | 226 | | } |
| 0 | 227 | | if (Ice.Internal.Network.timeout(ex)) |
| | 228 | | { |
| 0 | 229 | | throw new Ice.TimeoutException(); |
| | 230 | | } |
| 0 | 231 | | throw new Ice.SocketException(ex); |
| | 232 | | } |
| 0 | 233 | | catch (ObjectDisposedException ex) |
| | 234 | | { |
| 0 | 235 | | throw new Ice.ConnectionLostException(ex); |
| | 236 | | } |
| 0 | 237 | | catch (Exception ex) |
| | 238 | | { |
| 0 | 239 | | throw new Ice.SyscallException(ex); |
| | 240 | | } |
| 1 | 241 | | } |
| | 242 | |
|
| | 243 | | public void finishWrite(Ice.Internal.Buffer buf) |
| | 244 | | { |
| 1 | 245 | | if (!_isConnected) |
| | 246 | | { |
| 1 | 247 | | _delegate.finishWrite(buf); |
| 1 | 248 | | return; |
| | 249 | | } |
| 1 | 250 | | else if (_sslStream == null) // Transceiver was closed |
| | 251 | | { |
| 0 | 252 | | buf.b.position(buf.b.limit()); // Assume all the data was sent for at-most-once semantics. |
| 0 | 253 | | _writeResult = null; |
| 0 | 254 | | return; |
| | 255 | | } |
| 1 | 256 | | else if (!_authenticated) |
| | 257 | | { |
| 1 | 258 | | finishAuthenticate(); |
| 1 | 259 | | return; |
| | 260 | | } |
| | 261 | |
|
| | 262 | | Debug.Assert(_writeResult != null); |
| | 263 | | try |
| | 264 | | { |
| | 265 | | try |
| | 266 | | { |
| 1 | 267 | | _writeResult.Wait(); |
| 1 | 268 | | } |
| 1 | 269 | | catch (AggregateException ex) |
| | 270 | | { |
| 1 | 271 | | throw ex.InnerException; |
| | 272 | | } |
| 1 | 273 | | buf.b.position(buf.b.position() + buf.b.remaining()); |
| 1 | 274 | | } |
| 1 | 275 | | catch (IOException ex) |
| | 276 | | { |
| 1 | 277 | | if (Ice.Internal.Network.connectionLost(ex)) |
| | 278 | | { |
| 1 | 279 | | throw new Ice.ConnectionLostException(ex); |
| | 280 | | } |
| 0 | 281 | | if (Ice.Internal.Network.timeout(ex)) |
| | 282 | | { |
| 0 | 283 | | throw new Ice.TimeoutException(); |
| | 284 | | } |
| 0 | 285 | | throw new Ice.SocketException(ex); |
| | 286 | | } |
| 0 | 287 | | catch (ObjectDisposedException ex) |
| | 288 | | { |
| 0 | 289 | | throw new Ice.ConnectionLostException(ex); |
| | 290 | | } |
| 0 | 291 | | catch (Exception ex) |
| | 292 | | { |
| 0 | 293 | | throw new Ice.SyscallException(ex); |
| | 294 | | } |
| 1 | 295 | | } |
| | 296 | |
|
| 1 | 297 | | public string protocol() => _delegate.protocol(); |
| | 298 | |
|
| | 299 | | public Ice.ConnectionInfo getInfo(bool incoming, string adapterName, string connectionId) |
| | 300 | | { |
| | 301 | | Debug.Assert(incoming == _incoming); |
| | 302 | | // adapterName is the name of the object adapter currently associated with this connection, while _adapterName |
| | 303 | | // represents the name of the object adapter that created this connection (incoming only). |
| | 304 | |
|
| 1 | 305 | | return new Ice.SSL.ConnectionInfo( |
| 1 | 306 | | _delegate.getInfo(incoming, adapterName, connectionId), |
| 1 | 307 | | _cipher, |
| 1 | 308 | | _sslStream is SslStream sslStream && sslStream.RemoteCertificate is X509Certificate2 remoteCertificate ? |
| 1 | 309 | | [remoteCertificate] : [], |
| 1 | 310 | | _verified); |
| | 311 | | } |
| | 312 | |
|
| 1 | 313 | | public void checkSendSize(Ice.Internal.Buffer buf) => _delegate.checkSendSize(buf); |
| | 314 | |
|
| 1 | 315 | | public void setBufferSize(int rcvSize, int sndSize) => _delegate.setBufferSize(rcvSize, sndSize); |
| | 316 | |
|
| 1 | 317 | | public override string ToString() => _delegate.ToString(); |
| | 318 | |
|
| 0 | 319 | | public string toDetailedString() => _delegate.toDetailedString(); |
| | 320 | |
|
| | 321 | | // Only for use by ConnectorI, AcceptorI. |
| 1 | 322 | | internal TransceiverI( |
| 1 | 323 | | Instance instance, |
| 1 | 324 | | Ice.Internal.Transceiver del, |
| 1 | 325 | | string hostOrAdapterName, |
| 1 | 326 | | bool incoming, |
| 1 | 327 | | SslServerAuthenticationOptions serverAuthenticationOptions) |
| | 328 | | { |
| 1 | 329 | | _instance = instance; |
| 1 | 330 | | _delegate = del; |
| 1 | 331 | | _incoming = incoming; |
| 1 | 332 | | if (_incoming) |
| | 333 | | { |
| 1 | 334 | | _adapterName = hostOrAdapterName; |
| 1 | 335 | | _serverAuthenticationOptions = serverAuthenticationOptions; |
| | 336 | | } |
| | 337 | | else |
| | 338 | | { |
| 1 | 339 | | _host = hostOrAdapterName; |
| | 340 | | Debug.Assert(_serverAuthenticationOptions is null); |
| | 341 | | } |
| | 342 | |
|
| 1 | 343 | | _sslStream = null; |
| | 344 | |
|
| 1 | 345 | | _verifyPeer = _instance.properties().getIcePropertyAsInt("IceSSL.VerifyPeer"); |
| 1 | 346 | | } |
| | 347 | |
|
| | 348 | | /// <summary> |
| | 349 | | /// If the SSL handshake is in progress, cancel it and wait for it to finish. This is used to ensure that the |
| | 350 | | /// SSLStream is not disposed while the handshake is in progress. |
| | 351 | | /// </summary> |
| | 352 | | private void cancelSslHandshake() |
| | 353 | | { |
| 1 | 354 | | if (!_verified && _writeResult is not null) |
| | 355 | | { |
| 1 | 356 | | _sslHandshakeCts.Cancel(); |
| | 357 | | try |
| | 358 | | { |
| 1 | 359 | | _writeResult.Wait(); |
| 1 | 360 | | _writeResult = null; |
| 1 | 361 | | } |
| 1 | 362 | | catch |
| | 363 | | { |
| 1 | 364 | | } |
| | 365 | | } |
| | 366 | | Debug.Assert(_writeResult is null || _writeResult.IsCompleted); |
| 1 | 367 | | } |
| | 368 | |
|
| | 369 | | private bool startAuthenticate(Ice.Internal.AsyncCallback callback, object state) |
| | 370 | | { |
| | 371 | | try |
| | 372 | | { |
| 1 | 373 | | if (_incoming) |
| | 374 | | { |
| 1 | 375 | | _writeResult = _sslStream.AuthenticateAsServerAsync( |
| 1 | 376 | | _serverAuthenticationOptions ?? |
| 1 | 377 | | _instance.engine().createServerAuthenticationOptions(validationCallback), |
| 1 | 378 | | _sslHandshakeCts.Token); |
| | 379 | | } |
| | 380 | | else |
| | 381 | | { |
| 1 | 382 | | _writeResult = _sslStream.AuthenticateAsClientAsync( |
| 1 | 383 | | _instance.initializationData().clientAuthenticationOptions ?? |
| 1 | 384 | | _instance.engine().createClientAuthenticationOptions(validationCallback, _host), |
| 1 | 385 | | _sslHandshakeCts.Token); |
| | 386 | | } |
| 1 | 387 | | _writeResult.ContinueWith( |
| 1 | 388 | | task => callback(state), |
| 1 | 389 | | TaskScheduler.Default); |
| 1 | 390 | | } |
| 0 | 391 | | catch (IOException ex) |
| | 392 | | { |
| 0 | 393 | | if (Ice.Internal.Network.connectionLost(ex)) |
| | 394 | | { |
| | 395 | | // This situation occurs when connectToSelf is called; the "remote" end closes the socket immediately. |
| 0 | 396 | | throw new ConnectionLostException(ex); |
| | 397 | | } |
| 0 | 398 | | throw new SocketException(ex); |
| | 399 | | } |
| 0 | 400 | | catch (AuthenticationException ex) |
| | 401 | | { |
| 0 | 402 | | throw new SecurityException( |
| 0 | 403 | | _errorDescription.Length == 0 ? "SSL authentication failure." : _errorDescription, |
| 0 | 404 | | ex); |
| | 405 | | } |
| 0 | 406 | | catch (System.Exception ex) |
| | 407 | | { |
| 0 | 408 | | throw new Ice.SyscallException(ex); |
| | 409 | | } |
| | 410 | |
|
| | 411 | | Debug.Assert(_writeResult != null); |
| 1 | 412 | | return false; |
| | 413 | | } |
| | 414 | |
|
| | 415 | | private void finishAuthenticate() |
| | 416 | | { |
| | 417 | | Debug.Assert(_writeResult != null); |
| | 418 | | try |
| | 419 | | { |
| | 420 | | try |
| | 421 | | { |
| | 422 | | // If authentication fails the task throws AuthenticationException. |
| 1 | 423 | | _writeResult.Wait(); |
| 1 | 424 | | _verified = true; |
| 1 | 425 | | _cipher = _sslStream.CipherAlgorithm.ToString(); |
| 1 | 426 | | } |
| 1 | 427 | | catch (AggregateException ex) |
| | 428 | | { |
| 1 | 429 | | throw ex.InnerException; |
| | 430 | | } |
| 1 | 431 | | } |
| 1 | 432 | | catch (IOException ex) |
| | 433 | | { |
| 1 | 434 | | if (Ice.Internal.Network.connectionLost(ex)) |
| | 435 | | { |
| | 436 | | // This situation occurs when connectToSelf is called; the "remote" end closes the socket immediately. |
| 1 | 437 | | throw new Ice.ConnectionLostException(); |
| | 438 | | } |
| 0 | 439 | | throw new Ice.SocketException(ex); |
| | 440 | | } |
| 1 | 441 | | catch (AuthenticationException ex) |
| | 442 | | { |
| 1 | 443 | | throw new SecurityException( |
| 1 | 444 | | _errorDescription.Length == 0 ? "SSL authentication failure." : _errorDescription, |
| 1 | 445 | | ex); |
| | 446 | | } |
| 0 | 447 | | catch (System.Exception ex) |
| | 448 | | { |
| 0 | 449 | | throw new Ice.SyscallException(ex); |
| | 450 | | } |
| 1 | 451 | | } |
| | 452 | |
|
| | 453 | | private bool validationCallback( |
| | 454 | | object sender, |
| | 455 | | X509Certificate certificate, |
| | 456 | | X509Chain chain, |
| | 457 | | SslPolicyErrors policyErrors) |
| | 458 | | { |
| 1 | 459 | | int errors = (int)policyErrors; |
| 1 | 460 | | int traceLevel = _instance.securityTraceLevel(); |
| 1 | 461 | | string traceCategory = _instance.securityTraceCategory(); |
| 1 | 462 | | Ice.Logger logger = _instance.logger(); |
| 1 | 463 | | string message = ""; |
| | 464 | |
|
| 1 | 465 | | if (_incoming && (errors & (int)SslPolicyErrors.RemoteCertificateNotAvailable) != 0 && _verifyPeer <= 1) |
| | 466 | | { |
| | 467 | | // The client certificate is optional when IceSSL.VerifyPeer = 1, and not required when IceSSL.VerifyPeer = |
| 1 | 468 | | errors ^= (int)SslPolicyErrors.RemoteCertificateNotAvailable; |
| | 469 | | } |
| | 470 | |
|
| 1 | 471 | | if ((errors & (int)SslPolicyErrors.RemoteCertificateNameMismatch) != 0) |
| | 472 | | { |
| 1 | 473 | | message += ": Remote certificate name mismatch"; |
| | 474 | | } |
| | 475 | |
|
| 1 | 476 | | if ((errors & (int)SslPolicyErrors.RemoteCertificateNotAvailable) != 0) |
| | 477 | | { |
| 1 | 478 | | message += ": Remote certificate not available"; |
| | 479 | | } |
| | 480 | |
|
| 1 | 481 | | foreach (X509ChainStatus status in chain?.ChainStatus ?? []) |
| | 482 | | { |
| 1 | 483 | | message += $": {status.StatusInformation}"; |
| | 484 | | } |
| | 485 | |
|
| 1 | 486 | | if (errors != 0) |
| | 487 | | { |
| 1 | 488 | | _errorDescription = |
| 1 | 489 | | message.Length > 0 ? $"SSL authentication failure{message}." : "SSL authentication failure."; |
| 1 | 490 | | if (traceLevel >= 1) |
| | 491 | | { |
| 0 | 492 | | logger.trace(traceCategory, _errorDescription); |
| | 493 | | } |
| | 494 | | } |
| 1 | 495 | | return errors == 0; |
| | 496 | | } |
| | 497 | |
|
| 1 | 498 | | private string _errorDescription = ""; |
| | 499 | | private readonly Instance _instance; |
| | 500 | | private readonly Ice.Internal.Transceiver _delegate; |
| 1 | 501 | | private readonly string _host = ""; |
| 1 | 502 | | private readonly string _adapterName = ""; |
| | 503 | | private readonly bool _incoming; |
| | 504 | | private SslStream _sslStream; |
| | 505 | | private readonly int _verifyPeer; |
| | 506 | | private bool _isConnected; |
| | 507 | | private bool _authenticated; |
| | 508 | | private Task _writeResult; |
| | 509 | | private Task<int> _readResult; |
| | 510 | | private string _cipher; |
| | 511 | | private bool _verified; |
| | 512 | | private readonly SslServerAuthenticationOptions _serverAuthenticationOptions; |
| 1 | 513 | | private readonly CancellationTokenSource _sslHandshakeCts = new(); |
| | 514 | | } |