This repository was archived by the owner on Jun 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathhttpsys.ps1
More file actions
394 lines (328 loc) · 13.1 KB
/
httpsys.ps1
File metadata and controls
394 lines (328 loc) · 13.1 KB
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
# Copyright (c) .NET Foundation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
##############################################################################
# Example
# $result = .\httpsys.ps1 -Command Get-SslBinding -IpAddress "0x00" -Port 46300
# .\httpsys.ps1 -Command Add-SslBinding -IpAddress "0x00" -Port 46300 –Thumbprint $result.CertificateHash
# .\httpsys.ps1 -Command Delete-SslBinding -IpAddress "0x00" -Port 46300
##############################################################################
Param (
[parameter(Mandatory=$true , Position=0)]
[ValidateSet("Add-SslBinding",
"Delete-SslBinding",
"Get-SslBinding")]
[string]
$Command,
[parameter()]
[string]
$IpAddress,
[parameter()]
[string]
$Port,
[parameter()]
[string]
$Thumbprint,
[parameter()]
[string]
$TargetSSLStore,
[parameter()]
[string]
$AppId,
[parameter()]
[System.Net.IPEndPoint]
$IpEndPoint
)
# adjust parameter variables
if (-not $IpEndPoint)
{
if ($IpAddress -and $Port)
{
$IpEndPoint = New-Object "System.Net.IPEndPoint" -ArgumentList $IpAddress,$Port
}
}
if (-not $TargetSSLStore)
{
$TargetSSLStore = "Cert:\LocalMachine\My"
}
$StoreName = ($TargetSSLStore.Split("\") | Select-Object -Last 1).Trim()
$Certificate = Get-Item "$TargetSSLStore\$Thumbprint"
if (-not $AppId)
{
# Assign a random GUID for $AppId
$AppId = [guid]::NewGuid()
}
$cs = '
namespace Microsoft.IIS.Administration.Setup {
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.ComponentModel;
public class Http {
public const int HTTP_INITIALIZE_CONFIG = 2;
public const int HTTP_SERVICE_CONFIG_SSLCERT_INFO = 1;
[DllImport("httpapi.dll", CharSet = CharSet.Auto, PreserveSig = true)]
public static extern uint HttpDeleteServiceConfiguration(IntPtr ServiceHandle, int ConfigId, ref HTTP_SERVICE_CONFIG_SSL_SET pConfigInformation, int ConfigInformationLength, IntPtr pOverlapped);
[DllImport("httpapi.dll", CharSet = CharSet.Auto, PreserveSig = true)]
public static extern uint HttpInitialize(HTTPAPI_VERSION version, uint flags, IntPtr pReserved);
[DllImport("httpapi.dll", EntryPoint = "HttpQueryServiceConfiguration",
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern uint HttpQueryServiceConfiguration(
IntPtr serviceHandle,
HTTP_SERVICE_CONFIG_ID configID,
ref HTTP_SERVICE_CONFIG_SSL_QUERY pInputConfigInfo,
UInt32 InputConfigInfoLength,
IntPtr pOutputConfigInfo,
UInt32 OutputConfigInfoLength,
[In, Out] ref UInt32 pReturnLength,
IntPtr pOverlapped
);
[DllImport("httpapi.dll", CharSet = CharSet.Auto, PreserveSig = true)]
public static extern uint HttpSetServiceConfiguration(IntPtr ServiceHandle, int ConfigId, ref HTTP_SERVICE_CONFIG_SSL_SET pConfigInformation, int ConfigInformationLength, IntPtr pOverlapped);
[DllImport("httpapi.dll", CharSet = CharSet.Auto, PreserveSig = true)]
public static extern uint HttpTerminate(uint flags, IntPtr pReserved);
public static HTTP_SERVICE_CONFIG_SSL_SET MarshalConfigSslSet(IntPtr ptr) {
return (HTTP_SERVICE_CONFIG_SSL_SET)Marshal.PtrToStructure(ptr, typeof(HTTP_SERVICE_CONFIG_SSL_SET));
}
}
public enum HTTP_SERVICE_CONFIG_ID {
HttpServiceConfigIPListenList,
HttpServiceConfigSSLCertInfo,
HttpServiceConfigUrlAclInfo,
HttpServiceConfigMax
}
public enum HTTP_SERVICE_CONFIG_QUERY_TYPE {
HttpServiceConfigQueryExact,
HttpServiceConfigQueryNext,
HttpServiceConfigQueryMax
}
[StructLayout(LayoutKind.Sequential)]
public struct HTTPAPI_VERSION {
public ushort HttpApiMajorVersion;
public ushort HttpApiMinorVersion;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct HTTP_SERVICE_CONFIG_SSL_KEY {
public IntPtr pIpPort;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct HTTP_SERVICE_CONFIG_SSL_QUERY {
public HTTP_SERVICE_CONFIG_QUERY_TYPE QueryDesc;
public IntPtr KeyDesc;
public Int32 dwToken;
}
[StructLayout(LayoutKind.Sequential)]
public struct HTTP_SERVICE_CONFIG_SSL_SET {
public IntPtr KeyDesc;
public uint SslHashLength;
public IntPtr pSslHash;
public Guid AppId;
[MarshalAs(UnmanagedType.LPWStr)]
public string pSslCertStoreName;
public int DefaultCertCheckMode;
public int DefaultRevocationFreshnessTime;
public int DefaultRecovationUrlRetrievalTimeout;
[MarshalAs(UnmanagedType.LPWStr)]
public string pDefaultSslCtlIdentifier;
[MarshalAs(UnmanagedType.LPWStr)]
public string pDefaultSslCtlStoreName;
public int DefaultFlags;
}
}
'
$SUCCESS = 0
function InitializeInterop() {
try {
[Microsoft.IIS.Administration.Setup.Http] | Out-Null
}
catch {
Add-Type $cs
}
}
function GetIpEndpointBytes($_ipEndpoint) {
$socketAddress = $_ipEndpoint.Serialize()
$ipBytes = [System.Array]::CreateInstance([System.Byte], $socketAddress.Size)
for ($i = 0; $i -lt $socketAddress.Size; $i++) {
$ipBytes[$i] = $socketAddress[$i]
}
return $ipBytes
}
function GetBindingInfo($sslConfig) {
$hash = [System.Array]::CreateInstance([System.Byte], [int]($sslConfig.SslHashLength))
[System.Runtime.InteropServices.Marshal]::Copy($sslConfig.pSslHash, $hash, 0, $sslConfig.SslHashLength)
$socketAddressLength = 16
$sa = [System.Array]::CreateInstance([System.Byte], $socketAddressLength)
[System.Runtime.InteropServices.Marshal]::Copy($sslConfig.KeyDesc, $sa, 0, $socketAddressLength)
$socketAddress = New-Object "System.Net.SocketAddress" -ArgumentList ([System.Net.Sockets.AddressFamily]::InterNetwork, $socketAddressLength)
for ($i = 0; $i -lt $sa.Length; $i++) {
$socketAddress[$i] = $sa[$i]
}
$ep = New-Object "System.Net.IPEndPoint" -ArgumentList ([ipaddress]::Any, 0)
$endpoint = [System.Net.IPEndPoint]$ep.Create($socketAddress)
$ret = @{}
$ret.CertificateHash = [System.BitConverter]::ToString($hash).Replace("-", "")
$ret.AppId = $sslConfig.AppId
$ret.IpEndpoint = $endpoint
return $ret
}
function InitializeHttpSys() {
$v = New-Object "Microsoft.IIS.Administration.Setup.HTTPAPI_VERSION"
$V.HttpApiMajorVersion = 1
$v.HttpApiMinorVersion = 0
$result = [Microsoft.IIS.Administration.Setup.Http]::HttpInitialize($v, [Microsoft.IIS.Administration.Setup.Http]::HTTP_INITIALIZE_CONFIG, [System.IntPtr]::Zero)
if ($result -ne $SUCCESS) {
Write-Warning "Error initializing Http API"
throw [System.ComponentModel.Win32Exception] $([System.int32]$result)
}
return $result
}
function TerminateHttpSys() {
return [Microsoft.IIS.Administration.Setup.Http]::HttpTerminate([Microsoft.IIS.Administration.Setup.Http]::HTTP_INITIALIZE_CONFIG, [System.IntPtr]::Zero)
}
function Add-SslBinding($_ipEndpoint, $_certificate, $_appId) {
if ($_ipEndpoint -eq $null) {
throw "Ip Endpoint required."
}
if ($_certificate -eq $null) {
throw "Certificate required."
}
if ($appId -eq $null) {
throw "App id required."
}
<# FYI, [System.Guid]::Parse() is not supported in lower version of powershell
if (-not($_appId -is [System.Guid])) {
$_appId = [System.Guid]::Parse($_appId)
}
#>
setSslConfiguration $_ipEndpoint $_certificate $_appId
}
function Delete-SslBinding($_ipEndpoint) {
if ($_ipEndpoint -eq $null) {
throw "Ip Endpoint required."
}
setSslConfiguration $_ipEndpoint $null $([System.Guid]::Empty)
}
function Get-SslBinding($_ipEndpoint) {
if ($_ipEndpoint -eq $null) {
throw "Ip Endpoint required."
}
$bufferSize = 4096
try {
InitializeHttpSys| Out-Null
$ipBytes = [System.Byte[]]$(GetIpEndpointBytes($_ipEndpoint))
$hIp = [System.Runtime.InteropServices.GCHandle]::Alloc($ipBytes, [System.Runtime.InteropServices.GCHandleType]::Pinned)
$pIp = $hIp.AddrOfPinnedObject()
$queryParam = New-Object "Microsoft.IIS.Administration.Setup.HTTP_SERVICE_CONFIG_SSL_QUERY"
$queryParam.QueryDesc = [Microsoft.IIS.Administration.Setup.HTTP_SERVICE_CONFIG_QUERY_TYPE]::HttpServiceConfigQueryExact
$queryParam.dwToken = 0
$queryParam.KeyDesc = $pIp
$returnLen = 0
$pReturnSet = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($bufferSize)
$result = [Microsoft.IIS.Administration.Setup.Http]::HttpQueryServiceConfiguration(
[System.IntPtr]::Zero,
[Microsoft.IIS.Administration.Setup.HTTP_SERVICE_CONFIG_ID]::HttpServiceConfigSSLCertInfo,
[ref] $queryParam,
[uint32]([System.Runtime.InteropServices.Marshal]::SizeOf($queryParam)),
$pReturnSet,
$bufferSize,
[ref] $returnLen,
[System.IntPtr]::Zero)
if ($result -eq 2) {
# File not found
return $null
}
if ($result -ne $SUCCESS) {
Write-Warning "Error reading Ssl Cert Configuration"
throw [System.ComponentModel.Win32Exception] $([System.int32]$result)
}
$sslConfig = [Microsoft.IIS.Administration.Setup.Http]::MarshalConfigSslSet($pReturnSet)
return GetBindingInfo $sslConfig
}
finally {
if ($hIp -ne $null) {
$hIp.Free()
$hIp = $null
}
if ($pReturnSet -ne [System.IntPtr]::Zero) {
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($pReturnSet)
$pReturnSet = [System.IntPtr]::Zero
}
TerminateHttpSys | Out-Null
}
}
function setSslConfiguration($_ipEndpoint, $_certificate, $_appId) {
try {
InitializeHttpSys| Out-Null
$sslSet = New-Object "Microsoft.IIS.Administration.Setup.HTTP_SERVICE_CONFIG_SSL_SET"
$sslSetSize = [System.Runtime.InteropServices.Marshal]::SizeOf($sslSet)
$ipBytes = [System.Byte[]]$(GetIpEndpointBytes($_ipEndpoint))
$hIp = [System.Runtime.InteropServices.GCHandle]::Alloc($ipBytes, [System.Runtime.InteropServices.GCHandleType]::Pinned)
$pIp = $hIp.AddrOfPinnedObject()
$sslSet.KeyDesc = $pIp # IntPtr
$sslSet.SslHashLength = 0
$sslSet.pSslHash = [System.IntPtr]::Zero
$sslSet.pSslCertStoreName = [System.IntPtr]::Zero
$sslSet.AppId = $_appId
if ($_certificate -ne $null) {
# Create binding
$certBytes = $_certificate.GetCertHash()
$hCertBytes = [System.Runtime.InteropServices.GCHandle]::Alloc($certBytes, [System.Runtime.InteropServices.GCHandleType]::Pinned)
$pCertBytes = $hCertBytes.AddrOfPinnedObject()
$sslSet.SslHashLength = 20
$sslSet.pSslHash = $pCertBytes
$sslSet.pSslCertStoreName = $StoreName
$result = [Microsoft.IIS.Administration.Setup.Http]::HttpSetServiceConfiguration([System.IntPtr]::Zero,
[Microsoft.IIS.Administration.Setup.Http]::HTTP_SERVICE_CONFIG_SSLCERT_INFO,
[ref]$sslSet,
$sslSetSize,
[System.IntPtr]::Zero)
}
else {
#Delete binding
$result = [Microsoft.IIS.Administration.Setup.Http]::HttpDeleteServiceConfiguration([System.IntPtr]::Zero,
[Microsoft.IIS.Administration.Setup.Http]::HTTP_SERVICE_CONFIG_SSLCERT_INFO,
[ref]$sslSet,
$sslSetSize,
[System.IntPtr]::Zero)
}
if ($result -ne $SUCCESS) {
Write-Warning "Error setting Ssl Cert Configuration"
throw [System.ComponentModel.Win32Exception] $([System.int32]$result)
}
}
finally {
if ($hIp -ne $null) {
$hIp.Free()
$hIp = $null
}
if ($hCertBytes -ne $null) {
$hCertBytes.Free()
$hCertBytes = $null
}
TerminateHttpSys| Out-Null
}
}
InitializeInterop
switch ($Command)
{
"Add-SslBinding"
{
return Add-SslBinding $IpEndPoint $Certificate $AppId
}
"Delete-SslBinding"
{
return Delete-SslBinding $IpEndpoint
}
"Get-SslBinding"
{
return Get-SslBinding $IpEndpoint
}
default
{
throw "Unknown command"
}
}