PSModules/Carbon.Windows.HttpServer/1.0.0/src/Http.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
 
namespace Carbon.Windows.HttpServer
{
    internal static class Win32ErrorCodes
    {
        internal const int Ok = 0x000;
        internal const int InsufficientBuffer = 0x07A;
        internal const int NoMoreItems = 0x103;
    }
 
    public sealed class HttpsCertificateBinding
    {
 
        #region httpapi.dll
        private const uint HttpInitializeConfig = 0x00000002;
 
        [Flags]
        private enum SslParamDefaultFlags : uint
        {
            UseDsMapper = 0x00000001,
            NegotiateClientCert = 0x00000002,
            NoRawFilter = 0x00000004
        }
 
        // ReSharper disable InconsistentNaming
        // ReSharper disable FieldCanBeMadeReadOnly.Local
        // ReSharper disable OptionalParameterRefOut
        // ReSharper disable MemberCanBePrivate.Local
        // ReSharper disable UnusedMember.Local
        private enum HTTP_SERVICE_CONFIG_ID
        {
            HttpServiceConfigIPListenList = 0,
            HttpServiceConfigSSLCertInfo,
            HttpServiceConfigUrlAclInfo,
            HttpServiceConfigMax
        }
 
        private enum HTTP_SERVICE_CONFIG_QUERY_TYPE
        {
            HttpServiceConfigQueryExact = 0,
            HttpServiceConfigQueryNext,
            HttpServiceConfigQueryMax
        }
 
        [StructLayout(LayoutKind.Sequential)]
        private struct HTTP_SERVICE_CONFIG_SSL_KEY
        {
            public IntPtr pIpPort;
        }
 
        [StructLayout(LayoutKind.Sequential)]
        private struct HTTP_SERVICE_CONFIG_SSL_QUERY
        {
            public HTTP_SERVICE_CONFIG_QUERY_TYPE QueryDesc;
            public HTTP_SERVICE_CONFIG_SSL_KEY KeyDesc;
            public uint dwToken;
        }
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        private struct HTTP_SERVICE_CONFIG_URLACL_KEY
        {
            [MarshalAs(UnmanagedType.LPWStr)]
            public string pUrlPrefix;
 
            public HTTP_SERVICE_CONFIG_URLACL_KEY(string urlPrefix)
            {
                pUrlPrefix = urlPrefix;
            }
        }
 
        [StructLayout(LayoutKind.Sequential)]
        private struct HTTP_SERVICE_CONFIG_URLACL_QUERY
        {
            public HTTP_SERVICE_CONFIG_QUERY_TYPE QueryDesc;
            public HTTP_SERVICE_CONFIG_URLACL_KEY KeyDesc;
            public uint dwToken;
        }
 
        [StructLayout(LayoutKind.Sequential, Pack = 2)]
        private struct HTTPAPI_VERSION
        {
            public ushort HttpApiMajorVersion;
            public ushort HttpApiMinorVersion;
 
            public HTTPAPI_VERSION(ushort majorVersion, ushort minorVersion)
            {
                HttpApiMajorVersion = majorVersion;
                HttpApiMinorVersion = minorVersion;
            }
        }
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        private struct HTTP_SERVICE_CONFIG_SSL_PARAM
        {
            public int SslHashLength;
            public IntPtr pSslHash;
            public Guid AppId;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string pSslCertStoreName;
            public uint DefaultCertCheckMode;
            public int DefaultRevocationFreshnessTime;
            public int DefaultRevocationUrlRetrievalTimeout;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string pDefaultSslCtlIdentifier;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string pDefaultSslCtlStoreName;
            public SslParamDefaultFlags DefaultFlags;
        }
 
        [StructLayout(LayoutKind.Sequential)]
        private struct HTTP_SERVICE_CONFIG_SSL_SET
        {
            public HTTP_SERVICE_CONFIG_SSL_KEY KeyDesc;
            public HTTP_SERVICE_CONFIG_SSL_PARAM ParamDesc;
        }
 
        [DllImport("httpapi.dll", SetLastError = true)]
        private static extern ulong HttpInitialize(HTTPAPI_VERSION Version, uint Flags, IntPtr pReserved);
 
        [DllImport("httpapi.dll", SetLastError = true)]
        private static extern ulong HttpQueryServiceConfiguration(
            IntPtr ServiceIntPtr,
            HTTP_SERVICE_CONFIG_ID ConfigId,
            IntPtr pInputConfigInfo,
            int InputConfigInfoLength,
            IntPtr pOutputConfigInfo,
            int OutputConfigInfoLength,
            [Optional] out int pReturnLength,
            IntPtr pOverlapped);
 
        [DllImport("httpapi.dll", SetLastError = true)]
        static extern ulong HttpDeleteServiceConfiguration(
            IntPtr ServiceIntPtr,
            HTTP_SERVICE_CONFIG_ID ConfigId,
            IntPtr pConfigInformation,
            int ConfigInformationLength,
            IntPtr pOverlapped);
 
        [DllImport("httpapi.dll", SetLastError = true)]
        static extern ulong HttpSetServiceConfiguration(
            IntPtr ServiceIntPtr,
            HTTP_SERVICE_CONFIG_ID ConfigId,
            IntPtr pConfigInformation,
            int ConfigInformationLength,
            IntPtr pOverlapped);
 
        [DllImport("httpapi.dll", SetLastError = true)]
        private static extern ulong HttpTerminate(uint Flags, IntPtr pReserved);
 
        private enum SockAddrFamily
        {
            Inet = 2,
            Inet6 = 23
        }
 
        [StructLayout(LayoutKind.Sequential)]
        private struct SockAddr
        {
            public ushort Family;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 14)]
            public byte[] Data;
        };
 
        [StructLayout(LayoutKind.Sequential)]
        private struct SockAddrIn
        {
            public ushort Family;
            public ushort Port;
            public uint Addr;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
            public byte[] Zero;
        }
 
        [StructLayout(LayoutKind.Sequential)]
        private struct SockAddrIn6
        {
            public ushort Family;
            public ushort Port;
            public uint FlowInfo;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            public byte[] Addr;
            public uint ScopeId;
        };
 
        private static IPAddress ConvertSockAddrPtrToIPAddress(IntPtr sockAddrPtr, out ushort port)
        {
            var sockAddr = (SockAddr) Marshal.PtrToStructure(sockAddrPtr, typeof (SockAddr));
            switch ((SockAddrFamily) sockAddr.Family)
            {
                case SockAddrFamily.Inet:
                {
                    var sockAddrIn = (SockAddrIn) Marshal.PtrToStructure(sockAddrPtr, typeof (SockAddrIn));
                    port = sockAddrIn.Port;
                    return new IPAddress(sockAddrIn.Addr);
                }
                case SockAddrFamily.Inet6:
                {
                    var sockAddrIn6 = (SockAddrIn6) Marshal.PtrToStructure(sockAddrPtr, typeof (SockAddrIn6));
                    port = sockAddrIn6.Port;
                    return new IPAddress(sockAddrIn6.Addr);
                }
                default:
                    throw new Exception(string.Format("Non-IP address family: {0}", sockAddr.Family));
            }
        }
 
        // ReSharper restore UnusedMember.Local
        // ReSharper restore MemberCanBePrivate.Local
        // ReSharper restore OptionalParameterRefOut
        // ReSharper restore FieldCanBeMadeReadOnly.Local
        // ReSharper restore InconsistentNaming
        #endregion
 
        public HttpsCertificateBinding(
            IPAddress ipAddress, ushort port, string certificateHash, Guid applicationID, StoreName? storeName, bool verifyClientCertRevocation,
            bool verifyRevocationUsingCachedClientCertsOnly, bool usageCheckEnabled, uint revocationFreshnessTime, uint urlRetrievalTimeout, string ctlIdentifier,
            string ctlStoreName, bool dsMapperUsageEnabled, bool negotiateClientCertificate)
        {
            if (ipAddress == null)
            {
                throw new ArgumentNullException("ipAddress");
            }
 
            if ( ! Regex.IsMatch(certificateHash, "^[0-9a-f]{40}$") )
            {
                throw new ArgumentException(
                    string.Format("'{0}' not a valid certificate hash/thumbprint.", certificateHash), "certificateHash");
            }
 
            IPAddress = ipAddress;
            Port = port;
            ApplicationID = applicationID;
            CertificateHash = certificateHash;
            CertificateStoreName = storeName;
            VerifyClientCertificateRevocation = verifyClientCertRevocation;
            VerifyRevocationUsingCachedClientCertificatesOnly = verifyRevocationUsingCachedClientCertsOnly;
            UsageCheckEnabled = usageCheckEnabled;
            RevocationFreshnessTime = revocationFreshnessTime;
            UrlRetrievalTimeout = urlRetrievalTimeout;
            CtlIdentifier = ctlIdentifier;
            CtlStoreName = ctlStoreName;
            DSMapperUsageEnabled = dsMapperUsageEnabled;
            NegotiateClientCertificate = negotiateClientCertificate;
        }
 
        public Guid ApplicationID { get; private set; }
 
        public string CertificateHash { get; private set; }
 
        public StoreName? CertificateStoreName { get; private set; }
 
        public string CtlIdentifier { get; private set; }
 
        public string CtlStoreName { get; private set; }
 
        public bool DSMapperUsageEnabled { get; private set; }
 
        public IPAddress IPAddress { get; private set; }
 
        public string IPPort
        {
            get { return string.Format("{0}:{1}", IPAddress, Port); }
        }
 
        public bool NegotiateClientCertificate { get; private set; }
 
        public ushort Port { get; private set; }
 
        public uint RevocationFreshnessTime { get; private set; }
 
        public uint UrlRetrievalTimeout { get; private set; }
 
        public bool UsageCheckEnabled { get; private set; }
 
        public bool VerifyClientCertificateRevocation { get; private set; }
 
        public bool VerifyRevocationUsingCachedClientCertificatesOnly { get; private set; }
 
        public override bool Equals(object obj)
        {
            var binding = obj as HttpsCertificateBinding;
 
            if (binding == null)
            {
                return false;
            }
 
            return IPAddress.Equals(binding.IPAddress) &&
                Port.Equals(binding.Port) &&
                CertificateHash.Equals(binding.CertificateHash) &&
                ApplicationID.Equals(binding.ApplicationID);
        }
 
        public override int GetHashCode()
        {
            unchecked // Overflow is fine, just wrap
            {
                int hash = 17;
                // Suitable nullity checks etc, of course :)
                hash = hash * 23 + IPAddress.GetHashCode();
                hash = hash * 23 + Port.GetHashCode();
                hash = hash * 23 + CertificateHash.GetHashCode();
                hash = hash * 23 + ApplicationID.GetHashCode();
                return hash;
            }
        }
 
        [StructLayout(LayoutKind.Sequential)]
        internal struct sockaddr_in
        {
            internal short sin_family;
            internal ushort sin_port;
            internal in_addr sin_addr;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
            internal byte[] sin_zero;
 
        }
 
        [StructLayout(LayoutKind.Explicit, Size = 4)]
        internal struct in_addr
        {
            [FieldOffset(0)]
            internal byte s_b1;
            [FieldOffset(1)]
            internal byte s_b2;
            [FieldOffset(2)]
            internal byte s_b3;
            [FieldOffset(3)]
            internal byte s_b4;
 
            [FieldOffset(0)]
            internal ushort s_w1;
            [FieldOffset(2)]
            internal ushort s_w2;
 
            [FieldOffset(0)]
            internal uint S_addr;
 
            /// <summary>
            /// can be used for most tcp & ip code
            /// </summary>
            internal uint s_addr
            {
                get { return S_addr; }
            }
 
            /// <summary>
            /// host on imp
            /// </summary>
            internal byte s_host
            {
                get { return s_b2; }
            }
 
            /// <summary>
            /// network
            /// </summary>
            internal byte s_net
            {
                get { return s_b1; }
            }
 
            /// <summary>
            /// imp
            /// </summary>
            internal ushort s_imp
            {
                get { return s_w2; }
            }
 
            /// <summary>
            /// imp #
            /// </summary>
            internal byte s_impno
            {
                get { return s_b4; }
            }
 
            /// <summary>
            /// logical host
            /// </summary>
            internal byte s_lh
            {
                get { return s_b3; }
            }
        }
 
        public static HttpsCertificateBinding[] GetHttpsCertificateBindings()
        {
 
            InitializeHttp();
 
            try
            {
                var bindings = new List<HttpsCertificateBinding>();
 
                uint recordNum = 0;
                while (true)
                {
                    var inputConfigInfoQuery = new HTTP_SERVICE_CONFIG_SSL_QUERY
                    {
                        QueryDesc = HTTP_SERVICE_CONFIG_QUERY_TYPE.HttpServiceConfigQueryNext,
                        dwToken = recordNum++
                    };
 
                    var size = Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_QUERY));
                    var pInputConfigInfo = Marshal.AllocCoTaskMem(size);
                    Marshal.StructureToPtr(inputConfigInfoQuery, pInputConfigInfo, false);
 
                    var pOutputConfigInfo = Marshal.AllocCoTaskMem(0);
                    var returnLength = 0;
 
                    var retVal = HttpQueryServiceConfiguration(IntPtr.Zero,
                        HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo,
                        pInputConfigInfo,
                        Marshal.SizeOf(inputConfigInfoQuery),
                        pOutputConfigInfo,
                        returnLength,
                        out returnLength,
                        IntPtr.Zero);
 
                    if (Win32ErrorCodes.InsufficientBuffer == retVal)
                    {
                        Marshal.FreeCoTaskMem(pOutputConfigInfo);
                        pOutputConfigInfo = Marshal.AllocCoTaskMem(Convert.ToInt32(returnLength));
 
                        retVal = HttpQueryServiceConfiguration(IntPtr.Zero,
                            HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo,
                            pInputConfigInfo,
                            Marshal.SizeOf(inputConfigInfoQuery),
                            pOutputConfigInfo,
                            returnLength,
                            out returnLength,
                            IntPtr.Zero);
                    }
                    else if (Win32ErrorCodes.NoMoreItems == retVal)
                    {
                        break;
                    }
 
                    if (Win32ErrorCodes.Ok == retVal)
                    {
                        var outputConfigInfo = (HTTP_SERVICE_CONFIG_SSL_SET)
                            Marshal.PtrToStructure(pOutputConfigInfo, typeof(HTTP_SERVICE_CONFIG_SSL_SET));
 
                        var paramInfo = outputConfigInfo.ParamDesc;
                        ushort port;
                        var ipAddress = ConvertSockAddrPtrToIPAddress(outputConfigInfo.KeyDesc.pIpPort, out port);
                        var portBytes = BitConverter.GetBytes(port);
                        var reversedPortBytes = new [] {portBytes[1], portBytes[0]};
                        port = BitConverter.ToUInt16(reversedPortBytes, 0);
 
                        var hash = new byte[outputConfigInfo.ParamDesc.SslHashLength];
                        Marshal.Copy(outputConfigInfo.ParamDesc.pSslHash, hash, 0, hash.Length);
 
                        var hex = new StringBuilder(hash.Length * 2);
                        foreach (var b in hash)
                        {
                            hex.AppendFormat("{0:x2}", b);
                        }
                        var certificateHash = hex.ToString();
 
                        var appID = paramInfo.AppId;
 
                        var storeName = ConvertToStoreName(paramInfo.pSslCertStoreName);
 
                        var verifyClientCertRevocation = ((paramInfo.DefaultCertCheckMode & 1) == 0);
                        var verifyRevocationUsingCachedClientCertsOnly = (paramInfo.DefaultCertCheckMode & 2) == 2;
                        var usageCheckEnabled = (paramInfo.DefaultCertCheckMode & 16) == 0;
                        var revocationFreshnessTime = (uint)paramInfo.DefaultRevocationFreshnessTime;
                        var urlRetrievalTimeout = (uint)paramInfo.DefaultRevocationUrlRetrievalTimeout;
                        string ctlIdentifier = paramInfo.pDefaultSslCtlIdentifier ?? String.Empty;
                        string ctlStoreName = paramInfo.pDefaultSslCtlStoreName ?? String.Empty;
                        var dsMapperUsageEnabled = paramInfo.DefaultFlags.HasFlag(SslParamDefaultFlags.UseDsMapper);
                        var negotiateClientCertificate = paramInfo.DefaultFlags.HasFlag(SslParamDefaultFlags.NegotiateClientCert);
 
                        var binding = new HttpsCertificateBinding(ipAddress, port, certificateHash, appID, storeName,
                            verifyClientCertRevocation,
                            verifyRevocationUsingCachedClientCertsOnly, usageCheckEnabled, revocationFreshnessTime, urlRetrievalTimeout,
                            ctlIdentifier, ctlStoreName, dsMapperUsageEnabled, negotiateClientCertificate);
 
                        bindings.Add(binding);
                    }
                    else
                    {
                        throw new Win32Exception();
                    }
 
                }
 
                return bindings.ToArray();
            }
            finally
            {
                TerminateHttp();
            }
        }
 
        private static StoreName? ConvertToStoreName(string name)
        {
            StoreName storeNameEnum;
            if (Enum.TryParse(name, true, out storeNameEnum))
            {
                return storeNameEnum;
            }
            return null;
        }
 
        private static void InitializeHttp()
        {
            var httpApiVersion = new HTTPAPI_VERSION(1, 0);
 
            var retVal = HttpInitialize(httpApiVersion, HttpInitializeConfig, IntPtr.Zero);
            if (Win32ErrorCodes.Ok != retVal)
            {
                throw new Win32Exception();
            }
        }
 
        private static void TerminateHttp()
        {
            HttpTerminate(HttpInitializeConfig, IntPtr.Zero);
        }
    }
}