Merge pull request #4680 from lambdageek/bug-49721-take2
[mono.git] / mcs / class / System / Mono.AppleTls / AppleCertificateHelper.cs
1 #if SECURITY_DEP && MONO_FEATURE_APPLETLS
2 //
3 // AppleCertificateHelper.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.Collections;
17 using System.Reflection;
18 using System.Runtime.InteropServices;
19 using System.Security.Cryptography.X509Certificates;
20
21 #if MONO_SECURITY_ALIAS
22 using MonoSecurity::Mono.Security.Interface;
23 #else
24 using Mono.Security.Interface;
25 #endif
26
27 namespace Mono.AppleTls
28 {
29         static class AppleCertificateHelper
30         {
31                 public static SecIdentity GetIdentity (X509Certificate certificate)
32                 {
33                         /*
34                          * If we got an 'X509Certificate2', then we require it to have a private key
35                          * and import it.
36                          */
37                         var certificate2 = certificate as X509Certificate2;
38                         if (certificate2 != null)
39                                 return SecImportExport.ItemImport (certificate2);
40
41                         /*
42                          * Reading Certificates from the Mac Keychain
43                          * ==========================================
44                          *
45                          * Reading the private key from the keychain is a new feature introduced with
46                          * AppleTls on XamMac and iOS. On Desktop Mono, this new feature has several
47                          * known issues and it also did not received any testing yet. We go back to the old
48                          * way of doing things, which is to explicitly provide an X509Certificate2 with a
49                          * private key.
50                          * 
51                          * Keychain Dialog Popups
52                          * ======================
53                          * 
54                          * When using Xamarin.Mac or Xamarin.iOS, we try to search the keychain
55                          * for the certificate and private key.
56                          * 
57                          * On Xamarin.iOS, this is easy because each app has its own keychain.
58                          * 
59                          * On Xamarin.Mac, the .app package needs to be trusted via code-sign
60                          * to get permission to access the user's keychain. [FIXME: I still have to
61                          * research how to actually do that.] Without this, you will get a popup
62                          * message each time, asking you whether you want to allow the app to access
63                          * the keychain, but you can make these go away by selecting "Trust always".
64                          * 
65                          * On Desktop Mono, this is problematic because selecting "Trust always"
66                          * give the 'mono' binary (and thus everything you'll ever run with Mono)
67                          * permission to retrieve the private key from the keychain.
68                          * 
69                          * This code would also trigger constant keychain popup messages,
70                          * which could only be suppressed by granting full trust. It also makes it
71                          * impossible to run Mono in headless mode.
72                          * 
73                          * SecIdentityCreate
74                          * =================
75                          * 
76                          * To avoid these problems, we are currently using an undocumented API
77                          * called SecIdentityRef() to avoid using the Mac keychain whenever a
78                          * X509Certificate2 with a private key is used.
79                          * 
80                          * On iOS and XamMac, you can still provide the X509Certificate without
81                          * a private key - in this case, a keychain search will be performed (and you
82                          * may get a popup message on XamMac).
83                          */
84
85 #if MOBILE
86                         using (var secCert = new SecCertificate (certificate)) {
87                                 return SecKeyChain.FindIdentity (secCert, true);
88                         }
89 #else
90                         return null;
91 #endif
92                 }
93
94                 public static SecIdentity GetIdentity (X509Certificate certificate, out SecCertificate[] intermediateCerts)
95                 {
96                         var identity = GetIdentity (certificate);
97
98                         var impl2 = certificate.Impl as X509Certificate2Impl;
99                         if (impl2 == null || impl2.IntermediateCertificates == null) {
100                                 intermediateCerts = new SecCertificate [0];
101                                 return identity;
102                         }
103
104                         try {
105                                 intermediateCerts = new SecCertificate [impl2.IntermediateCertificates.Count];
106                                 for (int i = 0; i < intermediateCerts.Length; i++)
107                                         intermediateCerts [i] = new SecCertificate (impl2.IntermediateCertificates [i]);
108
109                                 return identity;
110                         } catch {
111                                 identity.Dispose ();
112                                 throw;
113                         }
114                 }
115
116                 public static bool InvokeSystemCertificateValidator (
117                         ICertificateValidator2 validator, string targetHost, bool serverMode,
118                         X509CertificateCollection certificates,
119                         ref MonoSslPolicyErrors errors, ref int status11)
120                 {
121                         if (certificates == null) {
122                                 errors |= MonoSslPolicyErrors.RemoteCertificateNotAvailable;
123                                 return false;
124                         }
125
126                         if (!string.IsNullOrEmpty (targetHost)) {
127                                 var pos = targetHost.IndexOf (':');
128                                 if (pos > 0)
129                                         targetHost = targetHost.Substring (0, pos);
130                         }
131
132                         var policy = SecPolicy.CreateSslPolicy (!serverMode, targetHost);
133                         var trust = new SecTrust (certificates, policy);
134
135                         if (validator.Settings.TrustAnchors != null) {
136                                 var status = trust.SetAnchorCertificates (validator.Settings.TrustAnchors);
137                                 if (status != SecStatusCode.Success)
138                                         throw new InvalidOperationException (status.ToString ());
139                                 trust.SetAnchorCertificatesOnly (false);
140                         }
141
142                         if (validator.Settings.CertificateValidationTime != null) {
143                                 var status = trust.SetVerifyDate (validator.Settings.CertificateValidationTime.Value);
144                                 if (status != SecStatusCode.Success)
145                                         throw new InvalidOperationException (status.ToString ());
146                         }
147
148                         var result = trust.Evaluate ();
149                         if (result == SecTrustResult.Unspecified)
150                                 return true;
151
152                         errors |= MonoSslPolicyErrors.RemoteCertificateChainErrors;
153                         return false;
154                 }
155         }
156 }
157 #endif