Add support on Windows to install atexit handler(s) early in application’s startup.
[mono.git] / mcs / class / System / System.Security.Cryptography.X509Certificates / OSX509Certificates.cs
1 // Copyright (C) 2010 Novell, Inc (http://www.novell.com)
2 // Copyright 2012-2014 Xamarin Inc.
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining
5 // a copy of this software and associated documentation files (the
6 // "Software"), to deal in the Software without restriction, including
7 // without limitation the rights to use, copy, modify, merge, publish,
8 // distribute, sublicense, and/or sell copies of the Software, and to
9 // permit persons to whom the Software is furnished to do so, subject to
10 // the following conditions:
11 // 
12 // The above copyright notice and this permission notice shall be
13 // included in all copies or substantial portions of the Software.
14 // 
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 //
23 #if SECURITY_DEP
24
25 using System;
26 using System.Runtime.InteropServices;
27 using System.Security.Cryptography.X509Certificates;
28
29 namespace System.Security.Cryptography.X509Certificates {
30
31         static class OSX509Certificates {
32                 public const string SecurityLibrary = "/System/Library/Frameworks/Security.framework/Security";
33                 public const string CoreFoundationLibrary = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";
34         
35                 [DllImport (SecurityLibrary)]
36                 extern static IntPtr SecCertificateCreateWithData (IntPtr allocator, IntPtr nsdataRef);
37                 
38                 [DllImport (SecurityLibrary)]
39                 extern static /* OSStatus */ int SecTrustCreateWithCertificates (IntPtr certOrCertArray, IntPtr policies, out IntPtr sectrustref);
40                 
41                 [DllImport (SecurityLibrary)]
42                 extern static /* OSStatus */ int SecTrustSetAnchorCertificates (IntPtr /* SecTrustRef */ trust, IntPtr /* CFArrayRef */ anchorCertificates);
43
44                 [DllImport (SecurityLibrary)]
45                 extern static IntPtr SecPolicyCreateSSL ([MarshalAs (UnmanagedType.I1)] bool server, IntPtr cfStringHostname);
46                 
47                 [DllImport (SecurityLibrary)]
48                 extern static /* OSStatus */ int SecTrustEvaluate (IntPtr secTrustRef, out SecTrustResult secTrustResultTime);
49
50                 [DllImport (CoreFoundationLibrary, CharSet=CharSet.Unicode)]
51                 extern static IntPtr CFStringCreateWithCharacters (IntPtr allocator, string str, /* CFIndex */ IntPtr count);
52
53                 [DllImport (CoreFoundationLibrary)]
54                 unsafe extern static IntPtr CFDataCreate (IntPtr allocator, byte *bytes, /* CFIndex */ IntPtr length);
55
56                 [DllImport (CoreFoundationLibrary)]
57                 extern static void CFRetain (IntPtr handle);
58
59                 [DllImport (CoreFoundationLibrary)]
60                 extern static void CFRelease (IntPtr handle);
61
62                 [DllImport (CoreFoundationLibrary)]
63                 extern static IntPtr CFArrayCreate (IntPtr allocator, IntPtr values, /* CFIndex */ IntPtr numValues, IntPtr callbacks);
64
65                 // uint32_t
66                 public enum SecTrustResult {
67                         Invalid,
68                         Proceed,
69                         Confirm,
70                         Deny,
71                         Unspecified,
72                         RecoverableTrustFailure,
73                         FatalTrustFailure,
74                         ResultOtherError,
75                 }
76
77                 static IntPtr MakeCFData (byte [] data)
78                 {
79                         unsafe {
80                                 fixed (byte *ptr = &data [0])
81                                         return CFDataCreate (IntPtr.Zero, ptr, (IntPtr) data.Length);
82                         }
83                 }
84
85                 static unsafe IntPtr FromIntPtrs (IntPtr [] values)
86                 {
87                         fixed (IntPtr* pv = values) {
88                                 return CFArrayCreate (
89                                         IntPtr.Zero, 
90                                         (IntPtr) pv,
91                                         (IntPtr) values.Length,
92                                         IntPtr.Zero);
93                         }
94                 }
95
96                 static IntPtr GetCertificate (X509Certificate certificate)
97                 {
98                         var handle = certificate.Impl.GetNativeAppleCertificate ();
99                         if (handle != IntPtr.Zero) {
100                                 CFRetain (handle);
101                                 return handle;
102                         }
103                         var dataPtr = MakeCFData (certificate.GetRawCertData ());
104                         handle = SecCertificateCreateWithData (IntPtr.Zero, dataPtr);
105                         CFRelease (dataPtr);
106                         return handle;
107                 }
108                 
109                 public static SecTrustResult TrustEvaluateSsl (X509CertificateCollection certificates, X509CertificateCollection anchors, string host)
110                 {
111                         if (certificates == null)
112                                 return SecTrustResult.Deny;
113
114                         try {
115                                 return _TrustEvaluateSsl (certificates, anchors, host);
116                         } catch {
117                                 return SecTrustResult.Deny;
118                         }
119                 }
120
121                 static SecTrustResult _TrustEvaluateSsl (X509CertificateCollection certificates, X509CertificateCollection anchors, string hostName)
122                 {
123                         int certCount = certificates.Count;
124                         int anchorCount = anchors != null ? anchors.Count : 0;
125                         IntPtr [] secCerts = new IntPtr [certCount];
126                         IntPtr [] secCertAnchors = new IntPtr [anchorCount];
127                         IntPtr certArray = IntPtr.Zero;
128                         IntPtr anchorArray = IntPtr.Zero;
129                         IntPtr sslsecpolicy = IntPtr.Zero;
130                         IntPtr host = IntPtr.Zero;
131                         IntPtr sectrust = IntPtr.Zero;
132                         SecTrustResult result = SecTrustResult.Deny;
133
134                         try {
135                                 for (int i = 0; i < certCount; i++) {
136                                         secCerts [i] = GetCertificate (certificates [i]);
137                                         if (secCerts [i] == IntPtr.Zero)
138                                                 return SecTrustResult.Deny;
139                                 }
140
141                                 for (int i = 0; i < anchorCount; i++) {
142                                         secCertAnchors [i] = GetCertificate (anchors [i]);
143                                         if (secCertAnchors [i] == IntPtr.Zero)
144                                                 return SecTrustResult.Deny;
145                                 }
146
147                                 certArray = FromIntPtrs (secCerts);
148
149                                 if (!string.IsNullOrEmpty (hostName))
150                                         host = CFStringCreateWithCharacters (IntPtr.Zero, hostName, (IntPtr) hostName.Length);
151                                 sslsecpolicy = SecPolicyCreateSSL (true, host);
152
153                                 int code = SecTrustCreateWithCertificates (certArray, sslsecpolicy, out sectrust);
154                                 if (code != 0)
155                                         return SecTrustResult.Deny;
156
157                                 if (anchorCount > 0) {
158                                         anchorArray = FromIntPtrs (secCertAnchors);
159                                         SecTrustSetAnchorCertificates (sectrust, anchorArray);
160                                 }
161
162                                 code = SecTrustEvaluate (sectrust, out result);
163                                 return result;
164                         } finally {
165                                 if (certArray != IntPtr.Zero)
166                                         CFRelease (certArray);
167
168                                 if (anchorArray != IntPtr.Zero)
169                                         CFRelease (anchorArray);
170                                 
171                                 for (int i = 0; i < certCount; i++)
172                                         if (secCerts [i] != IntPtr.Zero)
173                                                 CFRelease (secCerts [i]);
174
175                                 for (int i = 0; i < anchorCount; i++)
176                                         if (secCertAnchors [i] != IntPtr.Zero)
177                                                 CFRelease (secCertAnchors [i]);
178
179                                 if (sslsecpolicy != IntPtr.Zero)
180                                         CFRelease (sslsecpolicy);
181                                 if (host != IntPtr.Zero)
182                                         CFRelease (host);
183                                 if (sectrust != IntPtr.Zero)
184                                         CFRelease (sectrust);
185                         }
186                 }
187         }
188 }
189 #endif