[System] Use 'ObjCRuntimeInternal' as the namespace instead of 'ObjCRuntime'. (#4820)
[mono.git] / mcs / class / System / Mono.AppleTls / AppleTlsContext.cs
1 #if SECURITY_DEP && MONO_FEATURE_APPLETLS
2 //
3 // AppleTlsContext.cs
4 //
5 // Author:
6 //       Martin Baulig <martin.baulig@xamarin.com>
7 //
8 // Copyright (c) 2015 Xamarin, Inc.
9 //
10
11 #if MONO_SECURITY_ALIAS
12 extern alias MonoSecurity;
13 #endif
14
15 using System;
16 using System.IO;
17 using System.Net;
18 using System.Text;
19 using System.Globalization;
20 using System.Collections;
21 using System.Collections.Generic;
22 using System.Threading;
23 using System.Threading.Tasks;
24 using System.Runtime.InteropServices;
25 using SSA = System.Security.Authentication;
26 using System.Security.Cryptography.X509Certificates;
27
28 #if MONO_SECURITY_ALIAS
29 using MonoSecurity::Mono.Security.Interface;
30 #else
31 using Mono.Security.Interface;
32 #endif
33
34 using Mono.Net;
35 using Mono.Net.Security;
36 using Mono.Util;
37
38 using ObjCRuntimeInternal;
39
40 namespace Mono.AppleTls
41 {
42         class AppleTlsContext : MobileTlsContext
43         {
44                 public const string SecurityLibrary = "/System/Library/Frameworks/Security.framework/Security";
45
46                 GCHandle handle;
47                 IntPtr context;
48                 IntPtr connectionId;
49                 SslReadFunc readFunc;
50                 SslWriteFunc writeFunc;
51
52                 SecIdentity serverIdentity;
53                 SecIdentity clientIdentity;
54
55                 X509Certificate remoteCertificate;
56                 X509Certificate localClientCertificate;
57                 MonoTlsConnectionInfo connectionInfo;
58                 bool havePeerTrust;
59                 bool isAuthenticated;
60                 bool handshakeFinished;
61                 int handshakeStarted;
62
63                 bool closed;
64                 bool disposed;
65                 bool closedGraceful;
66                 int pendingIO;
67
68                 Exception lastException;
69
70                 public AppleTlsContext (
71                         MobileAuthenticatedStream parent, bool serverMode, string targetHost,
72                         SSA.SslProtocols enabledProtocols, X509Certificate serverCertificate,
73                         X509CertificateCollection clientCertificates, bool askForClientCert)
74                         : base (parent, serverMode, targetHost, enabledProtocols,
75                                 serverCertificate, clientCertificates, askForClientCert)
76                 {
77                         handle = GCHandle.Alloc (this);
78                         connectionId = GCHandle.ToIntPtr (handle);
79                         readFunc = NativeReadCallback;
80                         writeFunc = NativeWriteCallback;
81
82                         if (IsServer) {
83                                 if (serverCertificate == null)
84                                         throw new ArgumentNullException ("serverCertificate");
85                         }
86                 }
87
88                 public IntPtr Handle {
89                         get {
90                                 if (!HasContext)
91                                         throw new ObjectDisposedException ("AppleTlsContext");
92                                 return context;
93                         }
94                 }
95
96                 public override bool HasContext {
97                         get { return !disposed && context != IntPtr.Zero; }
98                 }
99
100                 [System.Diagnostics.Conditional ("APPLE_TLS_DEBUG")]
101                 protected new void Debug (string message, params object[] args)
102                 {
103                         Console.Error.WriteLine ("MobileTlsStream({0}): {1}", Parent.ID, string.Format (message, args));
104                 }
105
106                 void CheckStatusAndThrow (SslStatus status, params SslStatus[] acceptable)
107                 {
108                         var last = Interlocked.Exchange (ref lastException, null);
109                         if (last != null)
110                                 throw last;
111
112                         if (status == SslStatus.Success || Array.IndexOf (acceptable, status) > -1)
113                                 return;
114
115                         switch (status) {
116                         case SslStatus.ClosedAbort:
117                                 throw new IOException ("Connection closed.");
118
119                         case SslStatus.BadCert:
120                                 throw new TlsException (AlertDescription.BadCertificate);
121
122                         case SslStatus.UnknownRootCert:
123                         case SslStatus.NoRootCert:
124                         case SslStatus.XCertChainInvalid:
125                                 throw new TlsException (AlertDescription.CertificateUnknown, status.ToString ());
126
127                         case SslStatus.CertExpired:
128                         case SslStatus.CertNotYetValid:
129                                 throw new TlsException (AlertDescription.CertificateExpired);
130
131                         case SslStatus.Protocol:
132                                 throw new TlsException (AlertDescription.ProtocolVersion);
133
134                         default:
135                                 throw new TlsException (AlertDescription.InternalError, "Unknown Secure Transport error `{0}'.", status);
136                         }
137                 }
138
139                 #region Handshake
140
141                 public override bool IsAuthenticated {
142                         get { return isAuthenticated; }
143                 }
144
145                 public override void StartHandshake ()
146                 {
147                         Debug ("StartHandshake: {0}", IsServer);
148
149                         if (Interlocked.CompareExchange (ref handshakeStarted, 1, 1) != 0)
150                                 throw new InvalidOperationException ();
151
152                         InitializeConnection ();
153
154                         SetSessionOption (SslSessionOption.BreakOnCertRequested, true);
155                         SetSessionOption (SslSessionOption.BreakOnClientAuth, true);
156                         SetSessionOption (SslSessionOption.BreakOnServerAuth, true);
157
158                         if (IsServer) {
159                                 SecCertificate[] intermediateCerts;
160                                 serverIdentity = AppleCertificateHelper.GetIdentity (LocalServerCertificate, out intermediateCerts);
161                                 if (serverIdentity == null)
162                                         throw new SSA.AuthenticationException ("Unable to get server certificate from keychain.");
163
164                                 SetCertificate (serverIdentity, intermediateCerts);
165                                 for (int i = 0; i < intermediateCerts.Length; i++)
166                                         intermediateCerts [i].Dispose ();
167                         }
168                 }
169
170                 public override void FinishHandshake ()
171                 {
172                         InitializeSession ();
173
174                         isAuthenticated = true;
175                 }
176
177                 public override void Flush ()
178                 {
179                 }
180
181                 public override bool ProcessHandshake ()
182                 {
183                         if (handshakeFinished)
184                                 throw new NotSupportedException ("Handshake already finished.");
185
186                         while (true) {
187                                 lastException = null;
188                                 var status = SSLHandshake (Handle);
189                                 Debug ("Handshake: {0} - {0:x}", status);
190
191                                 CheckStatusAndThrow (status, SslStatus.WouldBlock, SslStatus.PeerAuthCompleted, SslStatus.PeerClientCertRequested);
192
193                                 if (status == SslStatus.PeerAuthCompleted) {
194                                         RequirePeerTrust ();
195                                 } else if (status == SslStatus.PeerClientCertRequested) {
196                                         RequirePeerTrust ();
197                                         if (remoteCertificate == null)
198                                                 throw new TlsException (AlertDescription.InternalError, "Cannot request client certificate before receiving one from the server.");
199                                         localClientCertificate = SelectClientCertificate (remoteCertificate, null);
200                                         if (localClientCertificate == null)
201                                                 continue;
202                                         clientIdentity = AppleCertificateHelper.GetIdentity (localClientCertificate);
203                                         if (clientIdentity == null)
204                                                 throw new TlsException (AlertDescription.CertificateUnknown);
205                                         SetCertificate (clientIdentity, new SecCertificate [0]);
206                                 } else if (status == SslStatus.WouldBlock) {
207                                         return false;
208                                 } else if (status == SslStatus.Success) {
209                                         handshakeFinished = true;
210                                         return true;
211                                 }
212                         }
213                 }
214
215                 void RequirePeerTrust ()
216                 {
217                         if (!havePeerTrust) {
218                                 EvaluateTrust ();
219                                 havePeerTrust = true;
220                         }
221                 }
222
223                 void EvaluateTrust ()
224                 {
225                         InitializeSession ();
226
227                         /*
228                          * We're using .NET's SslStream semantics here.
229                          * 
230                          * A server must always provide a valid certificate.
231                          * 
232                          * However, in server mode, "ask for client certificate" means that
233                          * we ask the client to provide a certificate, then invoke the client
234                          * certificate validator - passing 'null' if the client didn't provide
235                          * any.
236                          * 
237                          */
238
239                         var trust = GetPeerTrust (!IsServer);
240                         X509CertificateCollection certificates;
241
242                         if (trust == null || trust.Count == 0) {
243                                 remoteCertificate = null;
244                                 if (!IsServer)
245                                         throw new TlsException (AlertDescription.CertificateUnknown);
246                                 certificates = null;
247                         } else {
248                                 if (trust.Count > 1)
249                                         Debug ("WARNING: Got multiple certificates in SecTrust!");
250
251                                 certificates = new X509CertificateCollection ();
252                                 for (int i = 0; i < trust.Count; i++)
253                                         certificates.Add (trust [(IntPtr)i].ToX509Certificate ());
254
255                                 remoteCertificate = certificates [0];
256                                 Debug ("Got peer trust: {0}", remoteCertificate);
257                         }
258
259                         bool ok;
260                         try {
261                                 ok = ValidateCertificate (certificates);
262                         } catch (Exception ex) {
263                                 Debug ("Certificate validation failed: {0}", ex);
264                                 throw new TlsException (AlertDescription.CertificateUnknown, "Certificate validation threw exception.");
265                         }
266
267                         if (!ok)
268                                 throw new TlsException (AlertDescription.CertificateUnknown);
269                 }
270
271                 void InitializeConnection ()
272                 {
273                         context = SSLCreateContext (IntPtr.Zero, IsServer ? SslProtocolSide.Server : SslProtocolSide.Client, SslConnectionType.Stream);
274
275                         var result = SSLSetIOFuncs (Handle, readFunc, writeFunc);
276                         CheckStatusAndThrow (result);
277
278                         result = SSLSetConnection (Handle, connectionId);
279                         CheckStatusAndThrow (result);
280
281                         if ((EnabledProtocols & SSA.SslProtocols.Tls) != 0)
282                                 MinProtocol = SslProtocol.Tls_1_0;
283                         else if ((EnabledProtocols & SSA.SslProtocols.Tls11) != 0)
284                                 MinProtocol = SslProtocol.Tls_1_1;
285                         else
286                                 MinProtocol = SslProtocol.Tls_1_2;
287
288                         if ((EnabledProtocols & SSA.SslProtocols.Tls12) != 0)
289                                 MaxProtocol = SslProtocol.Tls_1_2;
290                         else if ((EnabledProtocols & SSA.SslProtocols.Tls11) != 0)
291                                 MaxProtocol = SslProtocol.Tls_1_1;
292                         else
293                                 MaxProtocol = SslProtocol.Tls_1_0;
294
295 #if APPLE_TLS_DEBUG
296                         foreach (var c in GetSupportedCiphers ())
297                                 Debug ("  {0} SslCipherSuite.{1} {2:x} {3}", IsServer ? "Server" : "Client", c, (int)c, (CipherSuiteCode)c);
298 #endif
299
300                         if (Settings != null && Settings.EnabledCiphers != null) {
301                                 SslCipherSuite [] ciphers = new SslCipherSuite [Settings.EnabledCiphers.Length];
302                                 for (int i = 0 ; i < Settings.EnabledCiphers.Length; ++i)
303                                         ciphers [i] = (SslCipherSuite)Settings.EnabledCiphers[i];
304                                 SetEnabledCiphers (ciphers);
305                         }
306
307                         if (AskForClientCertificate)
308                                 SetClientSideAuthenticate (SslAuthenticate.Try);
309
310                         IPAddress address;
311                         if (!IsServer && !string.IsNullOrEmpty (TargetHost) &&
312                             !IPAddress.TryParse (TargetHost, out address)) {
313                                 PeerDomainName = ServerName;
314                         }
315                 }
316
317                 void InitializeSession ()
318                 {
319                         if (connectionInfo != null)
320                                 return;
321
322                         var cipher = NegotiatedCipher;
323                         var protocol = GetNegotiatedProtocolVersion ();
324                         Debug ("GET CONNECTION INFO: {0:x}:{0} {1:x}:{1} {2}", cipher, protocol, (TlsProtocolCode)protocol);
325
326                         connectionInfo = new MonoTlsConnectionInfo {
327                                 CipherSuiteCode = (CipherSuiteCode)cipher,
328                                 ProtocolVersion = GetProtocol (protocol),
329                                 PeerDomainName = PeerDomainName
330                         };
331                 }
332
333                 static TlsProtocols GetProtocol (SslProtocol protocol)
334                 {
335                         switch (protocol) {
336                         case SslProtocol.Tls_1_0:
337                                 return TlsProtocols.Tls10;
338                         case SslProtocol.Tls_1_1:
339                                 return TlsProtocols.Tls11;
340                         case SslProtocol.Tls_1_2:
341                                 return TlsProtocols.Tls12;
342                         default:
343                                 throw new NotSupportedException ();
344                         }
345                 }
346
347                 public override MonoTlsConnectionInfo ConnectionInfo {
348                         get { return connectionInfo; }
349                 }
350
351                 internal override bool IsRemoteCertificateAvailable {
352                         get { return remoteCertificate != null; }
353                 }
354
355                 internal override X509Certificate LocalClientCertificate {
356                         get { return localClientCertificate; }
357                 }
358
359                 public override X509Certificate RemoteCertificate {
360                         get { return remoteCertificate; }
361                 }
362
363                 public override TlsProtocols NegotiatedProtocol {
364                         get { return connectionInfo.ProtocolVersion; }
365                 }
366
367                 #endregion
368
369                 #region General P/Invokes
370
371                 [DllImport (SecurityLibrary )]
372                 extern static /* OSStatus */ SslStatus SSLGetProtocolVersionMax (/* SSLContextRef */ IntPtr context, out SslProtocol maxVersion);
373
374                 [DllImport (SecurityLibrary)]
375                 extern static /* OSStatus */ SslStatus SSLSetProtocolVersionMax (/* SSLContextRef */ IntPtr context, SslProtocol maxVersion);
376
377                 public SslProtocol MaxProtocol {
378                         get {
379                                 SslProtocol value;
380                                 var result = SSLGetProtocolVersionMax (Handle, out value);
381                                 CheckStatusAndThrow (result);
382                                 return value;
383                         }
384                         set {
385                                 var result = SSLSetProtocolVersionMax (Handle, value);
386                                 CheckStatusAndThrow (result);
387                         }
388                 }
389
390                 [DllImport (SecurityLibrary)]
391                 extern static /* OSStatus */ SslStatus SSLGetProtocolVersionMin (/* SSLContextRef */ IntPtr context, out SslProtocol minVersion);
392
393                 [DllImport (SecurityLibrary)]
394                 extern static /* OSStatus */ SslStatus SSLSetProtocolVersionMin (/* SSLContextRef */ IntPtr context, SslProtocol minVersion);
395
396                 public SslProtocol MinProtocol {
397                         get {
398                                 SslProtocol value;
399                                 var result = SSLGetProtocolVersionMin (Handle, out value);
400                                 CheckStatusAndThrow (result);
401                                 return value;
402                         }
403                         set {
404                                 var result = SSLSetProtocolVersionMin (Handle, value);
405                                 CheckStatusAndThrow (result);
406                         }
407                 }
408
409                 [DllImport (SecurityLibrary)]
410                 extern static /* OSStatus */ SslStatus SSLGetNegotiatedProtocolVersion (/* SSLContextRef */ IntPtr context, out SslProtocol protocol);
411
412                 public SslProtocol GetNegotiatedProtocolVersion ()
413                 {
414                         SslProtocol value;
415                         var result = SSLGetNegotiatedProtocolVersion (Handle, out value);
416                         CheckStatusAndThrow (result);
417                         return value;
418                 }
419
420                 [DllImport (SecurityLibrary)]
421                 extern static /* OSStatus */ SslStatus SSLGetSessionOption (/* SSLContextRef */ IntPtr context, SslSessionOption option, out bool value);
422
423                 public bool GetSessionOption (SslSessionOption option)
424                 {
425                         bool value;
426                         var result = SSLGetSessionOption (Handle, option, out value);
427                         CheckStatusAndThrow (result);
428                         return value;
429                 }
430
431                 [DllImport (SecurityLibrary)]
432                 extern static /* OSStatus */ SslStatus SSLSetSessionOption (/* SSLContextRef */ IntPtr context, SslSessionOption option, bool value);
433
434                 public void SetSessionOption (SslSessionOption option, bool value)
435                 {
436                         var result = SSLSetSessionOption (Handle, option, value);
437                         CheckStatusAndThrow (result);
438                 }
439
440                 [DllImport (SecurityLibrary)]
441                 extern static /* OSStatus */ SslStatus SSLSetClientSideAuthenticate (/* SSLContextRef */ IntPtr context, SslAuthenticate auth);
442
443                 public void SetClientSideAuthenticate (SslAuthenticate auth)
444                 {
445                         var result = SSLSetClientSideAuthenticate (Handle, auth);
446                         CheckStatusAndThrow (result);
447                 }
448
449                 [DllImport (SecurityLibrary)]
450                 extern static /* OSStatus */ SslStatus SSLHandshake (/* SSLContextRef */ IntPtr context);
451
452                 [DllImport (SecurityLibrary)]
453                 extern static /* OSStatus */ SslStatus SSLGetSessionState (/* SSLContextRef */ IntPtr context, ref SslSessionState state);
454
455                 public SslSessionState SessionState {
456                         get {
457                                 var value = SslSessionState.Invalid;
458                                 var result = SSLGetSessionState (Handle, ref value);
459                                 CheckStatusAndThrow (result);
460                                 return value;
461                         }
462                 }
463
464                 [DllImport (SecurityLibrary)]
465                 extern unsafe static /* OSStatus */ SslStatus SSLGetPeerID (/* SSLContextRef */ IntPtr context, /* const void** */ out IntPtr peerID, /* size_t* */ out IntPtr peerIDLen);
466
467                 [DllImport (SecurityLibrary)]
468                 extern unsafe static /* OSStatus */ SslStatus SSLSetPeerID (/* SSLContextRef */ IntPtr context, /* const void* */ byte* peerID, /* size_t */ IntPtr peerIDLen);
469
470                 public unsafe byte[] PeerId {
471                         get {
472                                 IntPtr length;
473                                 IntPtr id;
474                                 var result = SSLGetPeerID (Handle, out id, out length);
475                                 CheckStatusAndThrow (result);
476                                 if ((result != SslStatus.Success) || ((int)length == 0))
477                                         return null;
478                                 var data = new byte [(int)length];
479                                 Marshal.Copy (id, data, 0, (int) length);
480                                 return data;
481                         }
482                         set {
483                                 SslStatus result;
484                                 IntPtr length = (value == null) ? IntPtr.Zero : (IntPtr)value.Length;
485                                 fixed (byte *p = value) {
486                                         result = SSLSetPeerID (Handle, p, length);
487                                 }
488                                 CheckStatusAndThrow (result);
489                         }
490                 }
491
492                 [DllImport (SecurityLibrary)]
493                 extern unsafe static /* OSStatus */ SslStatus SSLGetBufferedReadSize (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr bufSize);
494
495                 public IntPtr BufferedReadSize {
496                         get {
497                                 IntPtr value;
498                                 var result = SSLGetBufferedReadSize (Handle, out value);
499                                 CheckStatusAndThrow (result);
500                                 return value;
501                         }
502                 }
503
504                 [DllImport (SecurityLibrary)]
505                 extern unsafe static /* OSStatus */ SslStatus SSLGetNumberSupportedCiphers (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr numCiphers);
506
507                 [DllImport (SecurityLibrary)]
508                 extern unsafe static /* OSStatus */ SslStatus SSLGetSupportedCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t* */ ref IntPtr numCiphers);
509
510                 public unsafe IList<SslCipherSuite> GetSupportedCiphers ()
511                 {
512                         IntPtr n;
513                         var result = SSLGetNumberSupportedCiphers (Handle, out n);
514                         CheckStatusAndThrow (result);
515                         if ((result != SslStatus.Success) || ((int)n <= 0))
516                                 return null;
517
518                         var ciphers = new SslCipherSuite [(int)n];
519                         fixed (SslCipherSuite *p = ciphers) {
520                                 result = SSLGetSupportedCiphers (Handle, p, ref n);
521                         }
522                         CheckStatusAndThrow (result);
523                         return ciphers;
524                 }
525
526                 [DllImport (SecurityLibrary)]
527                 extern unsafe static /* OSStatus */ SslStatus SSLGetNumberEnabledCiphers (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr numCiphers);
528
529                 [DllImport (SecurityLibrary)]
530                 extern unsafe static /* OSStatus */ SslStatus SSLGetEnabledCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t* */ ref IntPtr numCiphers);
531
532                 public unsafe IList<SslCipherSuite> GetEnabledCiphers ()
533                 {
534                         IntPtr n;
535                         var result = SSLGetNumberEnabledCiphers (Handle, out n);
536                         CheckStatusAndThrow (result);
537                         if ((result != SslStatus.Success) || ((int)n <= 0))
538                                 return null;
539
540                         var ciphers = new SslCipherSuite [(int)n];
541                         fixed (SslCipherSuite *p = ciphers) {
542                                 result = SSLGetEnabledCiphers (Handle, p, ref n);
543                         }
544                         CheckStatusAndThrow (result);
545                         return ciphers;
546                 }
547
548                 [DllImport (SecurityLibrary)]
549                 extern unsafe static /* OSStatus */ SslStatus SSLSetEnabledCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t */ IntPtr numCiphers);
550
551                 public unsafe void SetEnabledCiphers (SslCipherSuite [] ciphers)
552                 {
553                         if (ciphers == null)
554                                 throw new ArgumentNullException ("ciphers");
555
556                         SslStatus result;
557
558                         fixed (SslCipherSuite *p = ciphers)
559                                 result = SSLSetEnabledCiphers (Handle, p, (IntPtr)ciphers.Length);
560                         CheckStatusAndThrow (result);
561                 }
562
563                 [DllImport (SecurityLibrary)]
564                 extern unsafe static /* OSStatus */ SslStatus SSLGetNegotiatedCipher (/* SSLContextRef */ IntPtr context, /* SslCipherSuite* */ out SslCipherSuite cipherSuite);
565
566                 public SslCipherSuite NegotiatedCipher {
567                         get {
568                                 SslCipherSuite value;
569                                 var result = SSLGetNegotiatedCipher (Handle, out value);
570                                 CheckStatusAndThrow (result);
571                                 return value;
572                         }
573                 }
574
575                 [DllImport (SecurityLibrary)]
576                 extern unsafe static /* OSStatus */ SslStatus SSLGetPeerDomainNameLength (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr peerNameLen);
577
578                 [DllImport (SecurityLibrary)]
579                 extern unsafe static /* OSStatus */ SslStatus SSLGetPeerDomainName (/* SSLContextRef */ IntPtr context, /* char* */ byte[] peerName, /* size_t */ ref IntPtr peerNameLen);
580
581                 [DllImport (SecurityLibrary)]
582                 extern unsafe static /* OSStatus */ SslStatus SSLSetPeerDomainName (/* SSLContextRef */ IntPtr context, /* char* */ byte[] peerName, /* size_t */ IntPtr peerNameLen);
583
584                 public string PeerDomainName {
585                         get {
586                                 IntPtr length;
587                                 var result = SSLGetPeerDomainNameLength (Handle, out length);
588                                 CheckStatusAndThrow (result);
589                                 if (result != SslStatus.Success || (int)length == 0)
590                                         return String.Empty;
591                                 var bytes = new byte [(int)length];
592                                 result = SSLGetPeerDomainName (Handle, bytes, ref length);
593                                 CheckStatusAndThrow (result);
594
595                                 int peerDomainLength = (int)length;
596
597                                 if (result != SslStatus.Success)
598                                         return string.Empty;
599                                 if (peerDomainLength > 0 && bytes [peerDomainLength-1] == 0)
600                                         peerDomainLength = peerDomainLength - 1;
601                                 return Encoding.UTF8.GetString (bytes, 0, peerDomainLength);
602                         }
603                         set {
604                                 SslStatus result;
605                                 if (value == null) {
606                                         result = SSLSetPeerDomainName (Handle, null, (IntPtr)0);
607                                 } else {
608                                         var bytes = Encoding.UTF8.GetBytes (value);
609                                         result = SSLSetPeerDomainName (Handle, bytes, (IntPtr)bytes.Length);
610                                 }
611                                 CheckStatusAndThrow (result);
612                         }
613                 }
614
615                 [DllImport (SecurityLibrary)]
616                 extern unsafe static /* OSStatus */ SslStatus SSLSetCertificate (/* SSLContextRef */ IntPtr context, /* CFArrayRef */ IntPtr certRefs);
617
618                 CFArray Bundle (SecIdentity identity, IEnumerable<SecCertificate> certificates)
619                 {
620                         if (identity == null)
621                                 throw new ArgumentNullException ("identity");
622                         int i = 0;
623
624                         int n = 0;
625                         if (certificates != null) {
626                                 foreach (var obj in certificates)
627                                         n++;
628                         }
629
630                         var ptrs = new IntPtr [n + 1];
631                         ptrs [0] = identity.Handle;
632                         foreach (var certificate in certificates)
633                                 ptrs [++i] = certificate.Handle;
634                         return CFArray.CreateArray (ptrs);
635                 }
636
637                 public void SetCertificate (SecIdentity identify, IEnumerable<SecCertificate> certificates)
638                 {
639                         using (var array = Bundle (identify, certificates)) {
640                                 var result = SSLSetCertificate (Handle, array.Handle);
641                                 CheckStatusAndThrow (result);
642                         }
643                 }
644
645                 [DllImport (SecurityLibrary)]
646                 extern unsafe static /* OSStatus */ SslStatus SSLGetClientCertificateState (/* SSLContextRef */ IntPtr context, out SslClientCertificateState clientState);
647
648                 public SslClientCertificateState ClientCertificateState {
649                         get {
650                                 SslClientCertificateState value;
651                                 var result = SSLGetClientCertificateState (Handle, out value);
652                                 CheckStatusAndThrow (result);
653                                 return value;
654                         }
655                 }
656
657                 [DllImport (SecurityLibrary)]
658                 extern unsafe static /* OSStatus */ SslStatus SSLCopyPeerTrust (/* SSLContextRef */ IntPtr context, /* SecTrustRef */ out IntPtr trust);
659
660                 public SecTrust GetPeerTrust (bool requireTrust)
661                 {
662                         IntPtr value;
663                         var result = SSLCopyPeerTrust (Handle, out value);
664                         if (requireTrust) {
665                                 CheckStatusAndThrow (result);
666                                 if (value == IntPtr.Zero)
667                                         throw new TlsException (AlertDescription.CertificateUnknown);
668                         }
669                         return (value == IntPtr.Zero) ? null : new SecTrust (value);
670                 }
671
672                 #endregion
673
674                 #region IO Functions
675
676                 [DllImport (SecurityLibrary)]
677                 extern static /* SSLContextRef */ IntPtr SSLCreateContext (/* CFAllocatorRef */ IntPtr alloc, SslProtocolSide protocolSide, SslConnectionType connectionType);
678
679                 [DllImport (SecurityLibrary)]
680                 extern static /* OSStatus */ SslStatus SSLSetConnection (/* SSLContextRef */ IntPtr context, /* SSLConnectionRef */ IntPtr connection);
681
682                 [DllImport (SecurityLibrary)]
683                 extern static /* OSStatus */ SslStatus SSLSetIOFuncs (/* SSLContextRef */ IntPtr context, /* SSLReadFunc */ SslReadFunc readFunc, /* SSLWriteFunc */ SslWriteFunc writeFunc);
684
685                 [MonoPInvokeCallback (typeof (SslReadFunc))]
686                 static SslStatus NativeReadCallback (IntPtr ptr, IntPtr data, ref IntPtr dataLength)
687                 {
688                         var handle = GCHandle.FromIntPtr (ptr);
689                         if (!handle.IsAllocated)
690                                 return SslStatus.Internal;
691
692                         var context = (AppleTlsContext) handle.Target;
693                         if (context.disposed)
694                                 return SslStatus.ClosedAbort;
695
696                         try {
697                                 return context.NativeReadCallback (data, ref dataLength);
698                         } catch (Exception ex) {
699                                 if (context.lastException == null)
700                                         context.lastException = ex;
701                                 return SslStatus.Internal;
702                         }
703                 }
704
705                 [MonoPInvokeCallback (typeof (SslWriteFunc))]
706                 static SslStatus NativeWriteCallback (IntPtr ptr, IntPtr data, ref IntPtr dataLength)
707                 {
708                         var handle = GCHandle.FromIntPtr (ptr);
709                         if (!handle.IsAllocated)
710                                 return SslStatus.Internal;
711
712                         var context = (AppleTlsContext) handle.Target;
713                         if (context.disposed)
714                                 return SslStatus.ClosedAbort;
715
716                         try {
717                                 return context.NativeWriteCallback (data, ref dataLength);
718                         } catch (Exception ex) {
719                                 if (context.lastException == null)
720                                         context.lastException = ex;
721                                 return SslStatus.Internal;
722                         }
723                 }
724
725                 SslStatus NativeReadCallback (IntPtr data, ref IntPtr dataLength)
726                 {
727                         if (closed || disposed || Parent == null)
728                                 return SslStatus.ClosedAbort;
729
730                         var len = (int)dataLength;
731                         var readBuffer = new byte [len];
732
733                         Debug ("NativeReadCallback: {0} {1}", dataLength, len);
734
735                         bool wantMore;
736                         var ret = Parent.InternalRead (readBuffer, 0, len, out wantMore);
737                         dataLength = (IntPtr)ret;
738
739                         Debug ("NativeReadCallback #1: {0} - {1} {2}", len, ret, wantMore);
740
741                         if (ret < 0)
742                                 return SslStatus.ClosedAbort;
743
744                         Marshal.Copy (readBuffer, 0, data, ret);
745
746                         if (ret > 0)
747                                 return SslStatus.Success;
748                         else if (wantMore)
749                                 return SslStatus.WouldBlock;
750                         else if (ret == 0) {
751                                 closedGraceful = true;
752                                 return SslStatus.ClosedGraceful;
753                         } else {
754                                 return SslStatus.Success;
755                         }
756                 }
757
758                 SslStatus NativeWriteCallback (IntPtr data, ref IntPtr dataLength)
759                 {
760                         if (closed || disposed || Parent == null)
761                                 return SslStatus.ClosedAbort;
762
763                         var len = (int)dataLength;
764                         var writeBuffer = new byte [len];
765
766                         Marshal.Copy (data, writeBuffer, 0, len);
767
768                         Debug ("NativeWriteCallback: {0}", len);
769
770                         var ok = Parent.InternalWrite (writeBuffer, 0, len);
771
772                         Debug ("NativeWriteCallback done: {0} {1}", len, ok);
773
774                         return ok ? SslStatus.Success : SslStatus.ClosedAbort;
775                 }
776
777                 [DllImport (SecurityLibrary)]
778                 extern unsafe static /* OSStatus */ SslStatus SSLRead (/* SSLContextRef */ IntPtr context, /* const void* */ byte* data, /* size_t */ IntPtr dataLength, /* size_t* */ out IntPtr processed);
779
780                 public override unsafe int Read (byte[] buffer, int offset, int count, out bool wantMore)
781                 {
782                         if (Interlocked.Exchange (ref pendingIO, 1) == 1)
783                                 throw new InvalidOperationException ();
784
785                         Debug ("Read: {0},{1}", offset, count);
786
787                         lastException = null;
788
789                         try {
790                                 IntPtr processed;
791                                 SslStatus status;
792
793                                 fixed (byte *d = &buffer [offset])
794                                         status = SSLRead (Handle, d, (IntPtr)count, out processed);
795
796                                 Debug ("Read done: {0} {1} {2}", status, count, processed);
797
798                                 if (closedGraceful && (status == SslStatus.ClosedAbort || status == SslStatus.ClosedGraceful)) {
799                                         /*
800                                          * This is really ugly, but unfortunately SSLRead() also returns 'SslStatus.ClosedAbort'
801                                          * when the first inner Read() returns 0.  MobileAuthenticatedStream.InnerRead() attempts
802                                          * to distinguish between a graceful close and abnormal termination of connection.
803                                          */
804                                         wantMore = false;
805                                         return 0;
806                                 }
807
808                                 CheckStatusAndThrow (status, SslStatus.WouldBlock, SslStatus.ClosedGraceful);
809                                 wantMore = status == SslStatus.WouldBlock;
810                                 return (int)processed;
811                         } catch (Exception ex) {
812                                 Debug ("Read error: {0}", ex);
813                                 throw;
814                         } finally {
815                                 pendingIO = 0;
816                         }
817                 }
818
819                 [DllImport (SecurityLibrary)]
820                 extern unsafe static /* OSStatus */ SslStatus SSLWrite (/* SSLContextRef */ IntPtr context, /* const void* */ byte* data, /* size_t */ IntPtr dataLength, /* size_t* */ out IntPtr processed);
821
822                 public override unsafe int Write (byte[] buffer, int offset, int count, out bool wantMore)
823                 {
824                         if (Interlocked.Exchange (ref pendingIO, 1) == 1)
825                                 throw new InvalidOperationException ();
826
827                         Debug ("Write: {0},{1}", offset, count);
828
829                         lastException = null;
830
831                         try {
832                                 SslStatus status = SslStatus.ClosedAbort;
833                                 IntPtr processed = (IntPtr)(-1);
834
835                                 fixed (byte *d = &buffer [offset])
836                                         status = SSLWrite (Handle, d, (IntPtr)count, out processed);
837
838                                 Debug ("Write done: {0} {1}", status, processed);
839
840                                 CheckStatusAndThrow (status, SslStatus.WouldBlock);
841
842                                 wantMore = status == SslStatus.WouldBlock;
843                                 return (int)processed;
844                         } finally {
845                                 pendingIO = 0;
846                         }
847                 }
848
849                 [DllImport (SecurityLibrary)]
850                 extern static /* OSStatus */ SslStatus SSLClose (/* SSLContextRef */ IntPtr context);
851
852                 public override void Close ()
853                 {
854                         if (Interlocked.Exchange (ref pendingIO, 1) == 1)
855                                 throw new InvalidOperationException ();
856
857                         Debug ("Close");
858
859                         lastException = null;
860
861                         try {
862                                 if (closed || disposed)
863                                         return;
864
865                                 var status = SSLClose (Handle);
866                                 Debug ("Close done: {0}", status);
867                                 CheckStatusAndThrow (status);
868                         } finally {
869                                 closed = true;
870                                 pendingIO = 0;
871                         }
872                 }
873
874                 #endregion
875
876                 protected override void Dispose (bool disposing)
877                 {
878                         try {
879                                 if (disposed)
880                                         return;
881                                 if (disposing) {
882                                         disposed = true;
883                                         if (serverIdentity != null) {
884                                                 serverIdentity.Dispose ();
885                                                 serverIdentity = null;
886                                         }
887                                         if (clientIdentity != null) {
888                                                 clientIdentity.Dispose ();
889                                                 clientIdentity = null;
890                                         }
891                                         if (remoteCertificate != null) {
892                                                 remoteCertificate.Dispose ();
893                                                 remoteCertificate = null;
894                                         }
895                                 }
896                         } finally {
897                                 disposed = true;
898                                 if (context != IntPtr.Zero) {
899                                         CFObject.CFRelease (context);
900                                         context = IntPtr.Zero;
901                                 }
902                                 base.Dispose (disposing);
903                         }
904                 }
905         }
906 }
907 #endif