win_iis_webbinding: Fix bug with ipaddress * returning multiple bindings (#34721)

* win_iis_webbinding: Fix bug with ipaddress * returning multiple bindings
instead of only the ones defined as *. Address possible future issues around
hostheader * by just disallowing it. Resolves 25473. Added new test for
this case.

Removed all validation for https binding collisions due to difficulty in
validating all cases in which they could or could not collide. As a
result, also removed return values relating to certificate data.

Updated testing and docs appropriately

* win_iis_webbinding: added break to remove binding loops
pull/33297/merge
nwsparks 7 years ago committed by Jordan Borean
parent 389f4ef1fb
commit beb0fd9b8b

@ -52,84 +52,39 @@ function Create-BindingInfo {
} }
# Used instead of get-webbinding to ensure we always return a single binding # Used instead of get-webbinding to ensure we always return a single binding
# We can't filter properly with get-webbinding...ex get-webbinding ip * returns all bindings
# pass it $binding_parameters hashtable # pass it $binding_parameters hashtable
function Get-SingleWebBinding { function Get-SingleWebBinding {
$bind_search_splat = @{
'name' = $args[0].name
'protocol' = $args[0].protocol
'port' = $args[0].port
'ip' = $args[0].ip
'hostheader' = $args[0].hostheader
}
# if no bindings exist, get-webbinding fails with an error that can't be ignored via error actions on older systems
# let's ignore that specific error
If (-not $bind_search_splat['hostheader'])
{
Try { Try {
Get-WebBinding @bind_search_splat | Where-Object {$_.BindingInformation.Split(':')[-1] -eq [string]::Empty} $site_bindings = get-webbinding -name $args[0].name
} }
Catch { Catch {
# 2k8r2 throws this error when you run get-webbinding with no bindings in iis
If (-not $_.Exception.Message.CompareTo('Cannot process argument because the value of argument "obj" is null. Change the value of argument "obj" to a non-null value')) If (-not $_.Exception.Message.CompareTo('Cannot process argument because the value of argument "obj" is null. Change the value of argument "obj" to a non-null value'))
{ {
Throw $_.Exception.Message Throw $_.Exception.Message
} }
} Else { return }
}
Else
{
Try {
Get-WebBinding @bind_search_splat
}
Catch {
If (-not $_.Exception.Message.CompareTo('Cannot process argument because the value of argument "obj" is null. Change the value of argument "obj" to a non-null value'))
{
Throw $_.Exception.Message
}
}
}
} }
Function Get-CertificateSubjects { Foreach ($binding in $site_bindings)
Param (
[string]$CertPath
)
If (-Not (Test-Path $CertPath) )
{ {
Fail-Json -obj $result -message "Unable to locate certificate at $CertPath" $splits = $binding.bindingInformation -split ':'
}
$cert = get-item $CertPath
If ([version][System.Environment]::OSVersion.Version -ge [version]6.2) if (
{ $args[0].protocol -eq $binding.protocol -and
$cert.DnsNameList.unicode $args[0].ipaddress -eq $splits[0] -and
} $args[0].port -eq $splits[1] -and
Else $args[0].hostheader -eq $splits[2]
{ )
$san = $cert.extensions | Where-Object {$_.Oid.FriendlyName -eq 'Subject Alternative Name'}
If ($san)
{
$san.Format(1) -split '\r\n' | Where-Object {$_} | ForEach-Object {
($_ -split '=')[-1]
}
}
Else
{
If ($cert.subject -like "*,*")
{
($cert.Subject | Select-String "CN=(.*?),?").matches.groups[-1].value
}
Else
{ {
$cert.subject -replace "CN=",'' Return $binding
}
} }
} }
} }
############################# #############################
### Pre-Action Validation ### ### Pre-Action Validation ###
############################# #############################
@ -203,29 +158,6 @@ If ($certificateHash -and $state -eq 'present')
{ {
Fail-Json -obj $result -message "Unable to locate certificate at $cert_path" Fail-Json -obj $result -message "Unable to locate certificate at $cert_path"
} }
#check if cert is wildcard and update results with useful info.
$cert_subjects = Get-CertificateSubjects $cert_path
$result.certificate_subjects = $cert_subjects
If ($cert_subjects | Where-Object {$_ -match '^\*'})
{
$cert_is_wildcard = $true
$result.cert_is_wildcard = $cert_is_wildcard
}
Else
{
$cert_is_wildcard = $false
$result.cert_is_wildcard = $cert_is_wildcard
}
If ($os_version -lt [version]6.2 -and $host_header -and -not $cert_is_wildcard)
{
Fail-Json -obj $result -message "You cannot specify host headers with SSL unless it is a wildcard certificate."
}
Elseif ($os_version -ge [version]6.2 -and $host_header -and (-not $cert_is_wildcard -and $sslFlags -eq 0))
{
Fail-Json -obj $result -message "You cannot specify host headers with SSL unless it is a wildcard certificate or SNI is enabled."
}
} }
# make sure binding info is valid for central cert store if sslflags -gt 1 # make sure binding info is valid for central cert store if sslflags -gt 1
@ -236,10 +168,10 @@ If ($sslFlags -gt 1 -and ($certificateHash -ne [string]::Empty -or $certificateS
the certificate is automatically retrieved from the store rather than manually assigned to the binding." the certificate is automatically retrieved from the store rather than manually assigned to the binding."
} }
# make sure host_header: '*' only present when state: absent # disallow host_header: '*'
If ($host_header -match '^\*$' -and $state -ne 'absent') If ($host_header -eq '*')
{ {
Fail-Json -obj $result -message "host_header: '*' can only be used in combinaiton with state: absent" Fail-Json -obj $result -message "To make or remove a catch-all binding, please omit the host_header parameter entirely rather than specify host_header *"
} }
########################## ##########################
@ -259,6 +191,10 @@ If ($host_header)
{ {
$binding_parameters.HostHeader = $host_header $binding_parameters.HostHeader = $host_header
} }
Else
{
$binding_parameters.HostHeader = [string]::Empty
}
# Get bindings matching parameters # Get bindings matching parameters
Try { Try {
@ -274,10 +210,27 @@ Catch {
If ($current_bindings -and $state -eq 'absent') If ($current_bindings -and $state -eq 'absent')
{ {
Try { Try {
# will remove multiple objects in the case of * host header #there is a bug in this method that will result in all bindings being removed if the IP in $current_bindings is a *
$current_bindings | Remove-WebBinding -WhatIf:$check_mode #$current_bindings | Remove-WebBinding -verbose -WhatIf:$check_mode
#another method that did not work. It kept failing to match on element and removed everything.
#$element = @{protocol="$protocol";bindingInformation="$ip`:$port`:$host_header"}
#Remove-WebconfigurationProperty -filter $current_bindings.ItemXPath -Name Bindings.collection -AtElement $element -WhatIf #:$check_mode
#this method works
[array]$bindings = Get-WebconfigurationProperty -filter $current_bindings.ItemXPath -Name Bindings.collection
$index = Foreach ($item in $bindings) {
If ( $protocol -eq $item.protocol -and $current_bindings.bindingInformation -eq $item.bindingInformation ) {
$bindings.indexof($item)
break
}
}
Remove-WebconfigurationProperty -filter $current_bindings.ItemXPath -Name Bindings.collection -AtIndex $index -WhatIf:$check_mode
$result.changed = $true $result.changed = $true
} }
Catch { Catch {
Fail-Json -obj $result -message "Failed to remove the binding from IIS - $($_.Exception.Message)" Fail-Json -obj $result -message "Failed to remove the binding from IIS - $($_.Exception.Message)"
} }
@ -299,7 +252,7 @@ ElseIf (-Not $current_bindings -and $state -eq 'absent')
### Modify existing bindings ### ### Modify existing bindings ###
################################ ################################
<# <#
since we have already.binding_info the parameters available to get-webbinding, since we have already have the parameters available to get-webbinding,
we just need to check here for the ones that are not available which are the we just need to check here for the ones that are not available which are the
ssl settings (hash, store, sslflags). If they aren't set we update here, or ssl settings (hash, store, sslflags). If they aren't set we update here, or
exit with changed: false exit with changed: false
@ -373,44 +326,6 @@ ElseIf ($current_bindings)
######################## ########################
ElseIf (-not $current_bindings -and $state -eq 'present') ElseIf (-not $current_bindings -and $state -eq 'present')
{ {
If ($certificateHash)
{
<#
Make sure a valid binding is specified. It's possible for another site to have a binding on the same IP:PORT. If
we bind to that same ip port without hostheader/sni it will cause a collision. Note, this check only matters for
https. Http will generate an error when new-webbinding is called if there is a conflict, unlike https.
I couldn't think of a good way to handle scenarios involving wildcards. There's just too many to think about and I
wouldn't want to potentially hard fail valid scenarios here that I did not consider...so those can still collide. We just skip
validation anytime an existing binding is a wildcard.
If a collision does occur, the website will be stopped. To help with this we'll return the website state into results.
#>
#use this instead of get-webbinding. on 2k8r2 get-webbinding fails with an error if a site with no bindings exists
$binding_matches = (Get-Website).bindings.collection | Where-Object {$_.BindingInformation -eq "$ip`:$port`:"}
#get dns names for all certs in matching bindings
$subjects = Foreach ($binding in $binding_matches)
{
$cert_path = "cert:\localmachine\$($binding.certificatestorename)\$($binding.certificatehash)"
Get-CertificateSubjects $cert_path
}
#skip validating scenarios where existing certs are wildcard
If (-not ($subjects | Where-Object {$_ -match "^\*"}))
{
If ($sslFlags -eq 0 -and $binding_matches -and $os_version -gt [version]6.2)
{
Fail-Json -obj $result -message "A conflicting binding has been found on the same ip $ip and port $port. To continue, you will either have to remove the offending binding or enable sni"
}
ElseIf ($binding_matches -and $os_version -lt [version]6.2)
{
Fail-Json -obj $result -message "A conflicting binding has been found on the same ip $ip and port $port. To continue you will need to remove the existing binding or assign a new IP or Port to this one"
}
}
}
# add binding. this creates the binding, but does not apply a certificate to it. # add binding. this creates the binding, but does not apply a certificate to it.
Try Try
{ {
@ -437,7 +352,8 @@ ElseIf (-not $current_bindings -and $state -eq 'present')
If ($certificateHash -and -not $check_mode) If ($certificateHash -and -not $check_mode)
{ {
Try { Try {
$new_binding = get-webbinding -Name $name -IPAddress $ip -port $port -Protocol $protocol -hostheader $host_header #$new_binding = get-webbinding -Name $name -IPAddress $ip -port $port -Protocol $protocol -hostheader $host_header
$new_binding = Get-SingleWebBinding $binding_parameters
$new_binding.addsslcertificate($certificateHash,$certificateStoreName) $new_binding.addsslcertificate($certificateHash,$certificateStoreName)
} }
Catch { Catch {

@ -42,8 +42,7 @@ options:
host_header: host_header:
description: description:
- The host header to bind to / use for the new site. - The host header to bind to / use for the new site.
- For state absent, you can use c('*') here to remove all bindings for a particular - If you are creating/removing a catch-all binding, omit this parameter rather than defining it as '*'.
protocol/ip/port combination.
protocol: protocol:
description: description:
- The protocol to be used for the Web binding (usually HTTP, HTTPS, or FTP). - The protocol to be used for the Web binding (usually HTTP, HTTPS, or FTP).
@ -80,11 +79,19 @@ EXAMPLES = r'''
port: 9090 port: 9090
state: absent state: absent
- name: Remove the default http binding
win_iis_webbinding:
name: Default Web Site
port: 80
ip: '*'
state: absent
- name: Add a HTTPS binding - name: Add a HTTPS binding
win_iis_webbinding: win_iis_webbinding:
name: Default Web Site name: Default Web Site
protocol: https protocol: https
port: 443 port: 443
ip: 127.0.0.1
certificate_hash: B0D0FA8408FC67B230338FCA584D03792DA73F4C certificate_hash: B0D0FA8408FC67B230338FCA584D03792DA73F4C
state: present state: present
@ -97,31 +104,9 @@ EXAMPLES = r'''
ssl_flags: 1 ssl_flags: 1
certificate_hash: D1A3AF8988FD32D1A3AF8988FD323792DA73F4C certificate_hash: D1A3AF8988FD32D1A3AF8988FD323792DA73F4C
state: present state: present
- name: Remove all https bindings on port 443
win_iis_webbinding:
name: Default Web Site
protocol: https
port: 443
host_header: '*'
state: absent
''' '''
RETURN = r''' RETURN = r'''
cert_is_wildcard:
description:
- Tells you if the certificate you are using is a wildcard
returned: when certificate_hash is defined
type: boolean
sample: false
version_added: "2.5"
certificate_subjects:
description:
- All of the subject names for the certificate you are using
returned: when certificate_hash is defined
type: list
sample: ["*.test.com","test.com"]
version_added: "2.5"
website_state: website_state:
description: description:
- The state of the website being targetted - The state of the website being targetted

@ -4,24 +4,18 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#Requires -Module Ansible.ModuleUtils.Legacy #Requires -Module Ansible.ModuleUtils.Legacy
#
$params = Parse-Args -arguments $args -supports_check_mode $true $params = Parse-Args -arguments $args -supports_check_mode $true
$check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -type "bool" -default $false
$name = Get-AnsibleParam $params -name "name" -type str -failifempty $true -aliases 'website' $name = Get-AnsibleParam $params -name "name" -type str -failifempty $true -aliases 'website'
#$state = Get-AnsibleParam $params "state" -default "present" -validateSet "present","absent"
$host_header = Get-AnsibleParam $params -name "host_header" -type str $host_header = Get-AnsibleParam $params -name "host_header" -type str
$protocol = Get-AnsibleParam $params -name "protocol" -type str -default 'http' $protocol = Get-AnsibleParam $params -name "protocol" -type str -default 'http'
$port = Get-AnsibleParam $params -name "port" -type int -default '80' $port = Get-AnsibleParam $params -name "port" -type int -default '80'
$ip = Get-AnsibleParam $params -name "ip" -default '*' $ip = Get-AnsibleParam $params -name "ip" -default '*'
$certificateHash = Get-AnsibleParam $params -name "certificate_hash" -type str
$certificateStoreName = Get-AnsibleParam $params -name "certificate_store_name" -type str
$sslFlags = Get-AnsibleParam $params -name "ssl_flags" -type int -default '0' -ValidateSet '0','1','2','3'
$result = @{ $result = @{
changed = $false changed = $false
} }
function Create-BindingInfo { function Create-BindingInfo {
$ht = @{ $ht = @{
'bindingInformation' = $args[0].bindingInformation 'bindingInformation' = $args[0].bindingInformation
@ -50,38 +44,31 @@ function Create-BindingInfo {
# Used instead of get-webbinding to ensure we always return a single binding # Used instead of get-webbinding to ensure we always return a single binding
# pass it $binding_parameters hashtable # pass it $binding_parameters hashtable
function Get-SingleWebBinding { function Get-SingleWebBinding {
$bind_search_splat = @{
'name' = $args[0].name
'protocol' = $args[0].protocol
'port' = $args[0].port
'ip' = $args[0].ip
'hostheader' = $args[0].hostheader
}
# if no bindings exist, get-webbinding fails with an error that can't be ignored via error actions on older systems
# let's ignore that specific error
If (-not $bind_search_splat['hostheader'])
{
Try { Try {
Get-WebBinding @bind_search_splat | Where-Object {$_.BindingInformation.Split(':')[-1] -eq [string]::Empty} $site_bindings = get-webbinding -name $args[0].name
} }
Catch { Catch {
# 2k8r2 throws this error when you run get-webbinding with no bindings in iis
If (-not $_.Exception.Message.CompareTo('Cannot process argument because the value of argument "obj" is null. Change the value of argument "obj" to a non-null value')) If (-not $_.Exception.Message.CompareTo('Cannot process argument because the value of argument "obj" is null. Change the value of argument "obj" to a non-null value'))
{ {
Throw $_.Exception.Message Throw $_.Exception.Message
} }
Else { return }
} }
}
Else Foreach ($binding in $site_bindings)
{ {
Try { $splits = $binding.bindingInformation -split ':'
Get-WebBinding @bind_search_splat
} if (
Catch { $args[0].protocol -eq $binding.protocol -and
If (-not $_.Exception.Message.CompareTo('Cannot process argument because the value of argument "obj" is null. Change the value of argument "obj" to a non-null value')) $args[0].ipaddress -eq $splits[0] -and
$args[0].port -eq $splits[1] -and
$args[0].hostheader -eq $splits[2]
)
{ {
Throw $_.Exception.Message Return $binding
}
} }
} }
} }
@ -99,6 +86,10 @@ If ($host_header)
{ {
$binding_parameters.HostHeader = $host_header $binding_parameters.HostHeader = $host_header
} }
Else
{
$binding_parameters.HostHeader = [string]::Empty
}
# Get bindings matching parameters # Get bindings matching parameters
Try { Try {

@ -1,17 +1,12 @@
- name: failure check bind with host header but no wc or sni - name: failure check define * for host header
win_iis_webbinding: win_iis_webbinding:
name: "{{ test_iis_site_name }}" name: "{{ test_iis_site_name }}"
state: present state: present
host_header: test.com host_header: '*'
protocol: https protocol: http
ip: '*' ip: '*'
port: 443
certificate_hash: "{{ thumbprint1.stdout_lines[0] }}"
ssl_flags: 0
register: failure register: failure
failed_when: failed_when: failure.msg != "To make or remove a catch-all binding, please omit the host_header parameter entirely rather than specify host_header *"
- failure.msg != "You cannot specify host headers with SSL unless it is a wildcard certificate."
- failure.msg != "You cannot specify host headers with SSL unless it is a wildcard certificate or SNI is enabled."
- debug: - debug:
var: failure var: failure
@ -29,46 +24,47 @@
with_items: with_items:
- "{{ existing_sites.stdout_lines }}" - "{{ existing_sites.stdout_lines }}"
- name: add sites - name: add testremove site
win_iis_website: win_iis_website:
name: "{{ item.name }}" name: testremove
state: started state: started
ip: 127.0.0.1
port: "{{ item.port }}"
physical_path: c:\inetpub\wwwroot physical_path: c:\inetpub\wwwroot
with_items:
- {name: testconflict1, port: 8080}
- {name: testconflict2, port: 8081}
- name: add https binding to testconflict1 - name: add bindings to testremove
win_iis_webbinding: win_iis_webbinding:
name: testconflict1 name: testremove
state: present ip: "{{ item.ip }}"
protocol: https port: "{{ item.port }}"
port: 443 with_items:
ip: 127.0.0.1 - {ip: 127.0.0.1, port: 80}
certificate_hash: "{{ thumbprint1.stdout_lines[0] }}" - {ip: '*', port: 80}
- name: add https binding to testconflict2 (expect failure) - name: remove ip * binding from testremove
win_iis_webbinding: win_iis_webbinding:
name: testconflict2 name: testremove
state: present state: absent
protocol: https port: 80
ip: '*'
- name: get the remaining binding from testremove
test_get_webbindings:
name: testremove
port: 80
ip: 127.0.0.1 ip: 127.0.0.1
port: 443 register: test_result
certificate_hash: "{{ thumbprint1.stdout_lines[0] }}"
register: failure
failed_when: '"A conflicting binding has been found on the same ip" not in failure.msg'
- debug: - debug:
var: failure var: test_result
verbosity: 1 verbosity: 1
- name: assert that remove *:80 doesn't also remove 127.0.0.1:80
assert:
that:
- test_result.binding.ip == '127.0.0.1'
- test_result.binding.port == 80
always: always:
- name: remove websites - name: remove websites
win_iis_website: win_iis_website:
name: "{{ item }}" name: testremove
state: absent state: absent
with_items:
- testconflict1
- testconflict2

@ -315,58 +315,3 @@
- http_header is not changed - http_header is not changed
- http_header.binding_info is not defined - http_header.binding_info is not defined
- get_http_header.binding is not defined - get_http_header.binding is not defined
#bulk remove cm
#add multiple bindings - verify they're present
- name: bulk add http binding with header
win_iis_webbinding:
name: "{{ test_iis_site_name }}"
state: present
host_header: "{{ item }}"
protocol: http
ip: '*'
port: 80
register: http_header
with_items:
- test1.com
- test2.com
- test3.com
- name: assert that 3 bindings were added
assert:
that:
- http_header is changed
- http_header | json_query('results[*].binding_info') | length == 3
#cm remove with host_header: '*' - verify changed true and that bulk remove tries to get them all
#remove with host_header: '*'
- name: bulk remove http binding with header
win_iis_webbinding:
name: "{{ test_iis_site_name }}"
state: absent
host_header: '*'
protocol: http
ip: '*'
port: 80
register: http_header
- name: get binding info header
test_get_webbindings:
name: "{{ test_iis_site_name }}"
host_header: "{{ item }}"
protocol: http
ip: '*'
port: 80
register: get_http_header
changed_when: false
with_items:
- test1.com
- test2.com
- test3.com
- name: bulk remove assert that bindings are gone
assert:
that:
- http_header is changed
- http_header.binding_info | length == 3

@ -35,7 +35,6 @@
state: absent state: absent
protocol: "{{ item.protocol }}" protocol: "{{ item.protocol }}"
port: "{{ item.port }}" port: "{{ item.port }}"
host_header: '*'
with_items: with_items:
- {protocol: http, port: 80} - {protocol: http, port: 80}
- {protocol: https, port: 443} - {protocol: https, port: 443}
@ -83,6 +82,12 @@
raw: '(gci Cert:\LocalMachine\my | ? {$_.subject -eq "CN=*.test.com"})[0].Thumbprint' raw: '(gci Cert:\LocalMachine\my | ? {$_.subject -eq "CN=*.test.com"})[0].Thumbprint'
register: thumbprint_wc register: thumbprint_wc
- debug: var=thumbprint1.stdout - debug:
- debug: var=thumbprint2.stdout var: thumbprint1.stdout
- debug: var=thumbprint_wc.stdout verbosity: 1
- debug:
var: thumbprint2.stdout
verbosity: 1
- debug:
var: thumbprint_wc.stdout
verbosity: 1

Loading…
Cancel
Save