[runtime] Fix memory leak in mono_save_seq_point_info().
[mono.git] / mcs / class / System / Mono.Btls / MonoBtlsProvider.cs
1 //
2 // MonoBtlsProvider.cs
3 //
4 // Author:
5 //       Martin Baulig <martin.baulig@xamarin.com>
6 //
7 // Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
15 //
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
18 //
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 // THE SOFTWARE.
26 #if SECURITY_DEP && MONO_FEATURE_BTLS
27 #if MONO_SECURITY_ALIAS
28 extern alias MonoSecurity;
29 #endif
30
31 using System;
32 using System.IO;
33 using System.Threading;
34 using System.Threading.Tasks;
35 using System.Security.Cryptography.X509Certificates;
36 using System.Security.Authentication;
37
38 #if MONO_SECURITY_ALIAS
39 using MonoSecurity::Mono.Security.Interface;
40 using MX = MonoSecurity::Mono.Security.X509;
41 #else
42 using Mono.Security.Interface;
43 using MX = Mono.Security.X509;
44 #endif
45
46 using MNS = Mono.Net.Security;
47
48 namespace Mono.Btls
49 {
50         class MonoBtlsProvider : MonoTlsProvider
51         {
52                 static readonly Guid id = new Guid ("432d18c9-9348-4b90-bfbf-9f2a10e1f15b");
53
54                 public override Guid ID {
55                         get { return id; }
56                 }
57                 public override string Name {
58                         get { return "btls"; }
59                 }
60
61                 internal MonoBtlsProvider ()
62                 {
63                         if (!MNS.MonoTlsProviderFactory.IsBtlsSupported ())
64                                 throw new NotSupportedException ("BTLS is not supported in this runtime.");
65                 }
66
67                 public override bool SupportsSslStream {
68                         get { return true; }
69                 }
70
71                 public override bool SupportsMonoExtensions {
72                         get { return true; }
73                 }
74
75                 public override bool SupportsConnectionInfo {
76                         get { return true; }
77                 }
78
79                 public override SslProtocols SupportedProtocols {
80                         get { return SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls; }
81                 }
82
83                 public override IMonoSslStream CreateSslStream (
84                         Stream innerStream, bool leaveInnerStreamOpen,
85                         MonoTlsSettings settings = null)
86                 {
87                         return new MonoBtlsStream (
88                                 innerStream, leaveInnerStreamOpen, settings, this);
89                 }
90
91                 internal override bool HasNativeCertificates {
92                         get { return true; }
93                 }
94
95                 internal override X509Certificate2Impl GetNativeCertificate (
96                         byte[] data, string password, X509KeyStorageFlags flags)
97                 {
98                         var impl = new X509CertificateImplBtls (false);
99                         impl.Import (data, password, flags);
100                         return impl;
101                 }
102
103                 internal override X509Certificate2Impl GetNativeCertificate (
104                         X509Certificate certificate)
105                 {
106                         var impl = certificate.Impl as X509CertificateImplBtls;
107                         if (impl != null)
108                                 return (X509Certificate2Impl)impl.Clone ();
109
110                         var data = certificate.GetRawCertData ();
111                         return new X509CertificateImplBtls (data, MonoBtlsX509Format.DER, false);
112                 }
113
114                 internal static MonoBtlsX509VerifyParam GetVerifyParam (string targetHost, bool serverMode)
115                 {
116                         MonoBtlsX509VerifyParam param;
117                         if (serverMode)
118                                 param = MonoBtlsX509VerifyParam.GetSslClient ();
119                         else
120                                 param = MonoBtlsX509VerifyParam.GetSslServer ();
121
122                         if (targetHost == null)
123                                 return param;
124
125                         try {
126                                 var copy = param.Copy ();
127                                 copy.SetHost (targetHost);
128                                 return copy;
129                         } finally {
130                                 param.Dispose ();
131                         }
132                 }
133
134                 internal override bool ValidateCertificate (
135                         ICertificateValidator2 validator, string targetHost, bool serverMode,
136                         X509CertificateCollection certificates, bool wantsChain, ref X509Chain chain,
137                         ref MonoSslPolicyErrors errors, ref int status11)
138                 {
139                         if (chain != null) {
140                                 var chainImpl = (X509ChainImplBtls)chain.Impl;
141                                 var success = chainImpl.StoreCtx.VerifyResult == 1;
142                                 CheckValidationResult (
143                                         validator, targetHost, serverMode, certificates,
144                                         wantsChain, chain, chainImpl.StoreCtx,
145                                         success, ref errors, ref status11);
146                                 return success;
147                         }
148
149                         using (var store = new MonoBtlsX509Store ())
150                         using (var nativeChain = MonoBtlsProvider.GetNativeChain (certificates))
151                         using (var param = GetVerifyParam (targetHost, serverMode))
152                         using (var storeCtx = new MonoBtlsX509StoreCtx ()) {
153                                 SetupCertificateStore (store, validator.Settings, serverMode);
154
155                                 storeCtx.Initialize (store, nativeChain);
156
157                                 storeCtx.SetVerifyParam (param);
158
159                                 var ret = storeCtx.Verify ();
160
161                                 var success = ret == 1;
162
163                                 if (wantsChain && chain == null) {
164                                         chain = GetManagedChain (nativeChain);
165                                 }
166
167                                 CheckValidationResult (
168                                         validator, targetHost, serverMode, certificates,
169                                         wantsChain, null, storeCtx,
170                                         success, ref errors, ref status11);
171                                 return success;
172                         }
173                 }
174
175                 internal static bool ValidateCertificate (MonoBtlsX509Chain chain, MonoBtlsX509VerifyParam param)
176                 {
177                         using (var store = new MonoBtlsX509Store ())
178                         using (var storeCtx = new MonoBtlsX509StoreCtx ()) {
179                                 SetupCertificateStore (store);
180
181                                 storeCtx.Initialize (store, chain);
182
183                                 if (param != null)
184                                         storeCtx.SetVerifyParam (param);
185
186                                 var ret = storeCtx.Verify ();
187
188                                 return ret == 1;
189                         }
190                 }
191
192                 void CheckValidationResult (
193                         ICertificateValidator validator, string targetHost, bool serverMode,
194                         X509CertificateCollection certificates, bool wantsChain,
195                         X509Chain chain, MonoBtlsX509StoreCtx storeCtx,
196                         bool success, ref MonoSslPolicyErrors errors, ref int status11)
197                 {
198                         if (!success) {
199                                 errors = MonoSslPolicyErrors.RemoteCertificateChainErrors;
200                                 status11 = unchecked((int)0x800B010B);
201                         }
202                 }
203
204                 internal static void SetupCertificateStore (MonoBtlsX509Store store, MonoTlsSettings settings, bool server)
205                 {
206 #if MONODROID
207                         SetupCertificateStore (store);
208                         return;
209 #else
210
211                         if (settings?.CertificateSearchPaths == null) {
212                                 SetupCertificateStore (store);
213                                 return;
214                         }
215
216                         foreach (var path in settings.CertificateSearchPaths) {
217                                 if (string.Equals (path, "@default", StringComparison.Ordinal)) {
218                                         AddTrustedRoots (store, settings, server);
219                                         AddUserStore (store);
220                                         AddMachineStore (store);
221                                 } else if (string.Equals (path, "@user", StringComparison.Ordinal))
222                                         AddUserStore (store);
223                                 else if (string.Equals (path, "@machine", StringComparison.Ordinal))
224                                         AddMachineStore (store);
225                                 else if (string.Equals (path, "@trusted", StringComparison.Ordinal))
226                                         AddTrustedRoots (store, settings, server);
227                                 else if (path.StartsWith ("@pem:", StringComparison.Ordinal)) {
228                                         var realPath = path.Substring (5);
229                                         if (Directory.Exists (realPath))
230                                                 store.AddDirectoryLookup (realPath, MonoBtlsX509FileType.PEM);
231                                 } else if (path.StartsWith ("@der:", StringComparison.Ordinal)) {
232                                         var realPath = path.Substring (5);
233                                         if (Directory.Exists (realPath))
234                                                 store.AddDirectoryLookup (realPath, MonoBtlsX509FileType.ASN1);
235                                 } else {
236                                         if (Directory.Exists (path))
237                                                 store.AddDirectoryLookup (path, MonoBtlsX509FileType.PEM);
238                                 }
239                         }
240 #endif
241                 }
242
243                 internal static void SetupCertificateStore (MonoBtlsX509Store store)
244                 {
245 #if MONODROID
246                         store.SetDefaultPaths ();
247                         store.AddAndroidLookup ();
248 #else
249                         AddUserStore (store);
250                         AddMachineStore (store);
251 #endif
252                 }
253
254 #if !MONODROID
255                 static void AddUserStore (MonoBtlsX509Store store)
256                 {
257                         var userPath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.UserTrustedRoots);
258                         if (Directory.Exists (userPath))
259                                 store.AddDirectoryLookup (userPath, MonoBtlsX509FileType.PEM);
260                 }
261
262                 static void AddMachineStore (MonoBtlsX509Store store)
263                 {
264                         var machinePath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.MachineTrustedRoots);
265                         if (Directory.Exists (machinePath))
266                                 store.AddDirectoryLookup (machinePath, MonoBtlsX509FileType.PEM);
267                 }
268
269                 static void AddTrustedRoots (MonoBtlsX509Store store, MonoTlsSettings settings, bool server)
270                 {
271                         if (settings?.TrustAnchors == null)
272                                 return;
273                         var trust = server ? MonoBtlsX509TrustKind.TRUST_CLIENT : MonoBtlsX509TrustKind.TRUST_SERVER;
274                         store.AddCollection (settings.TrustAnchors, trust);
275                 }
276 #endif
277
278                 public static string GetSystemStoreLocation ()
279                 {
280 #if MONODROID
281                         return "/system/etc/security/cacerts";
282 #else
283                         return MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.MachineTrustedRoots);
284 #endif
285                 }
286
287                 public static X509Certificate CreateCertificate (byte[] data, MonoBtlsX509Format format, bool disallowFallback = false)
288                 {
289                         using (var impl = new X509CertificateImplBtls (data, format, disallowFallback)) {
290                                 return new X509Certificate (impl);
291                         }
292                 }
293
294                 public static X509Certificate2 CreateCertificate2 (byte[] data, MonoBtlsX509Format format, bool disallowFallback = false)
295                 {
296                         using (var impl = new X509CertificateImplBtls (data, format, disallowFallback)) {
297                                 return new X509Certificate2 (impl);
298                         }
299                 }
300
301                 public static X509Certificate2 CreateCertificate2 (byte[] data, string password, bool disallowFallback = false)
302                 {
303                         using (var impl = new X509CertificateImplBtls (disallowFallback)) {
304                                 impl.Import (data, password, X509KeyStorageFlags.DefaultKeySet);
305                                 return new X509Certificate2 (impl);
306                         }
307                 }
308
309                 public static X509Certificate CreateCertificate (MonoBtlsX509 x509)
310                 {
311                         using (var impl = new X509CertificateImplBtls (x509, true))
312                                 return new X509Certificate (impl);
313                 }
314
315                 public static X509Chain CreateChain ()
316                 {
317                         using (var impl = new X509ChainImplBtls ())
318                                 return new X509Chain (impl);
319                 }
320
321                 public static X509Chain GetManagedChain (MonoBtlsX509Chain chain)
322                 {
323                         var impl = new X509ChainImplBtls (chain);
324                         return new X509Chain (impl);
325                 }
326
327                 public static MonoBtlsX509 GetBtlsCertificate (X509Certificate certificate)
328                 {
329                         var impl = certificate.Impl as X509CertificateImplBtls;
330                         if (impl != null)
331                                 return impl.X509.Copy ();
332
333                         return MonoBtlsX509.LoadFromData (certificate.GetRawCertData (), MonoBtlsX509Format.DER);
334                 }
335
336                 public static MonoBtlsX509Chain GetNativeChain (X509CertificateCollection certificates)
337                 {
338                         var chain = new MonoBtlsX509Chain ();
339                         try {
340                                 foreach (var cert in certificates) {
341                                         using (var x509 = GetBtlsCertificate (cert))
342                                                 chain.AddCertificate (x509);
343                                 }
344                                 return chain;
345                         } catch {
346                                 chain.Dispose ();
347                                 throw;
348                         }
349                 }
350         }
351 }
352 #endif