DnsPlugins/Windows.ps1

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
#Requires -Modules DnsServer, CimCmdlets

function Add-DnsTxtWindows {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory,Position=0)]
        [string]$RecordName,
        [Parameter(Mandatory,Position=1)]
        [string]$TxtValue,
        [Parameter(Mandatory,Position=2)]
        [string]$WinServer,
        [Parameter(Position=3)]
        [pscredential]$WinCred,
        [switch]$WinUseSSL,
        [string]$WinZoneScope,
        [Parameter(ValueFromRemainingArguments)]
        $ExtraParams
    )

    $cim = Connect-WinDns @PSBoundParameters
    Write-Verbose "Connected to $WinServer"

    $dnsParams = @{ ComputerName=$WinServer; CimSession=$cim }

    Write-Debug "Attempting to find zone for $RecordName"
    if (!($zoneName = Find-WinZone $RecordName $dnsParams)) {
        throw "Unable to find zone for $RecordName"
    }
    Write-Verbose "Found $zoneName"
    $zone = Get-DnsServerZone $zoneName @dnsParams -EA Stop

    # separate the portion of the name that doesn't contain the zone name
    $recShort = $RecordName -ireplace [regex]::Escape(".$zoneName"), [string]::Empty
    Write-Verbose "Record short name: $recShort"

    # check for zone scope usage
    $zoneScope = @{}
    if (-not [String]::IsNullOrWhiteSpace($WinZoneScope)) {
        if ('ZoneScope' -notin (Get-Command Get-DnsServerResourceRecord).Parameters.Keys) {
            throw "ZoneScope is not supported in the version of the DnsServer module currently installed."
        } else {
            $zoneScope.ZoneScope = $WinZoneScope
        }
    }

    $recs = @($zone | Get-DnsServerResourceRecord -Name $recShort -RRType Txt @dnsParams @zoneScope -EA Ignore)

    if ($recs.Count -eq 0 -or $TxtValue -notin $recs.RecordData.DescriptiveText) {
        # create new
        Write-Verbose "Adding a TXT record for $RecordName with value $TxtValue"
        $zone | Add-DnsServerResourceRecord -Txt -Name $recShort -DescriptiveText $TxtValue -TimeToLive 00:00:10 @dnsParams @zoneScope
    } else {
        # nothing to do
        Write-Debug "Record $RecordName already contains $TxtValue. Nothing to do."
    }

    <#
    .SYNOPSIS
        Add a DNS TXT record to a Windows DNS server.
 
    .DESCRIPTION
        This plugin requires the "DnsServer" PowerShell module to be installed. On Windows Server OSes, you can install it with "Install-WindowsFeature RSAT-DNS-Server". On Windows client OSes, you will need to download and install the RSAT tools for your OS.
 
    .PARAMETER RecordName
        The fully qualified name of the TXT record.
 
    .PARAMETER TxtValue
        The value of the TXT record.
 
    .PARAMETER WinServer
        The hostname or IP address of the Windows DNS server.
 
    .PARAMETER WinCred
        Credentials with permissions to modify TXT records in the specified zone. This is optional if the current user has the proper permissions already.
 
    .PARAMETER WinUseSSL
        Forces the PowerShell remoting session to run over HTTPS. Requires the server have a valid certificate that is installed and trusted by the client or added to the client's TrustedHosts list. This is primarily used when connecting to a non-domain joined DNS server.
 
    .PARAMETER WinZoneScope
        The name of the zone scope to modify. This is generally only necessary in split-brain DNS configurations where the default scope is not external facing.
 
    .PARAMETER ExtraParams
        This parameter can be ignored and is only used to prevent errors when splatting with more parameters than this function supports.
 
    .EXAMPLE
        Add-DnsTxtWindows '_acme-challenge.site1.example.com' 'asdfqwer12345678' -WinServer 'dns1.example.com'
 
        Adds a TXT record using the credentials of the calling process.
 
    .EXAMPLE
        Add-DnsTxtWindows '_acme-challenge.site1.example.com' 'asdfqwer12345678' -WinServer 'dns1.example.com' -WinCred (Get-Credential) -WinUseSSL
 
        Adds a TXT record using explicit credentials and connecting over HTTPS.
    #>

}

function Remove-DnsTxtWindows {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory,Position=0)]
        [string]$RecordName,
        [Parameter(Mandatory,Position=1)]
        [string]$TxtValue,
        [Parameter(Mandatory,Position=2)]
        [string]$WinServer,
        [Parameter(Position=3)]
        [pscredential]$WinCred,
        [switch]$WinUseSSL,
        [string]$WinZoneScope,
        [Parameter(ValueFromRemainingArguments)]
        $ExtraParams
    )

    $cim = Connect-WinDns @PSBoundParameters
    Write-Verbose "Connected to $WinServer"

    $dnsParams = @{ ComputerName=$WinServer; CimSession=$cim }

    Write-Debug "Attempting to find zone for $RecordName"
    if (!($zoneName = Find-WinZone $RecordName $dnsParams)) {
        throw "Unable to find zone for $RecordName"
    }
    $zone = Get-DnsServerZone $zoneName @dnsParams -EA Stop

    # separate the portion of the name that doesn't contain the zone name
    $recShort = $RecordName -ireplace [regex]::Escape(".$zoneName"), [string]::Empty

    # check for zone scope usage
    $zoneScope = @{}
    if (-not [String]::IsNullOrWhiteSpace($WinZoneScope)) {
        if ('ZoneScope' -notin (Get-Command Get-DnsServerResourceRecord).Parameters.Keys) {
            throw "ZoneScope is not supported in the version of the DnsServer module currently installed."
        } else {
            $zoneScope.ZoneScope = $WinZoneScope
        }
    }

    $recs = @($zone | Get-DnsServerResourceRecord -Name $recShort -RRType Txt @dnsParams @zoneScope -EA Ignore)

    if ($recs.Count -gt 0 -and $TxtValue -in $recs.RecordData.DescriptiveText) {
        # remove the record that has the right value
        $toDelete = $recs | Where-Object { $_.RecordData.DescriptiveText -eq $TxtValue }
        Write-Verbose "Deleting $RecordName with value $TxtValue"
        $zone | Remove-DnsServerResourceRecord -InputObject $toDelete -Force @dnsParams @zoneScope
    } else {
        # nothing to do
        Write-Debug "Record $RecordName with value $TxtValue doesn't exist. Nothing to do."
    }

    <#
    .SYNOPSIS
        Remove a DNS TXT record from a Windows DNS server.
 
    .DESCRIPTION
        This plugin requires the "DnsServer" PowerShell module to be installed. On Windows Server OSes, you can install it with "Install-WindowsFeature RSAT-DNS-Server". On Windows client OSes, you will need to download and install the RSAT tools for your OS.
 
    .PARAMETER RecordName
        The fully qualified name of the TXT record.
 
    .PARAMETER TxtValue
        The value of the TXT record.
 
    .PARAMETER WinServer
        The hostname or IP address of the Windows DNS server.
 
    .PARAMETER WinCred
        Credentials with permissions to modify TXT records in the specified zone. This is optional if the current user has the proper permissions already.
 
    .PARAMETER WinUseSSL
        Forces the PowerShell remoting session to run over HTTPS. Requires the server have a valid certificate that is installed and trusted by the client or added to the client's TrustedHosts list. This is primarily used when connecting to a non-domain joined DNS server.
 
    .PARAMETER WinZoneScope
        The name of the zone scope to modify. This is generally only necessary in split-brain DNS configurations where the default scope is not external facing.
 
    .PARAMETER ExtraParams
        This parameter can be ignored and is only used to prevent errors when splatting with more parameters than this function supports.
 
    .EXAMPLE
        Remove-DnsTxtWindows '_acme-challenge.site1.example.com' 'asdfqwer12345678' -WinServer 'dns1.example.com'
 
        Removes a TXT record using the credentials of the calling process.
 
    .EXAMPLE
        Remove-DnsTxtWindows '_acme-challenge.site1.example.com' 'asdfqwer12345678' -WinServer 'dns1.example.com' -WinCred (Get-Credential) -WinUseSSL
 
        Removes a TXT record using explicit credentials and connecting over HTTPS.
    #>

}

function Save-DnsTxtWindows {
    [CmdletBinding()]
    param(
        [Parameter(ValueFromRemainingArguments)]
        $ExtraParams
    )
    <#
    .SYNOPSIS
        Not required.
 
    .DESCRIPTION
        This provider does not require calling this function to commit changes to DNS records.
 
    .PARAMETER ExtraParams
        This parameter can be ignored and is only used to prevent errors when splatting with more parameters than this function supports.
    #>

}

############################
# Helper Functions
############################

function Connect-WinDns {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory,Position=0)]
        [string]$WinServer,
        [Parameter(Position=1)]
        [pscredential]$WinCred,
        [switch]$WinUseSSL,
        [Parameter(ValueFromRemainingArguments)]
        $ExtraConnectParams
    )

    # create a new CimSession if necessary
    if (Get-CimSession -ComputerName $WinServer -EA Ignore) {
        Write-Debug "Using existing CimSession for $WinServer"
        return ((Get-CimSession -ComputerName $WinServer)[0])
    } else {
        Write-Debug "Connecting to $WinServer"
        $cimParams = @{ ComputerName=$WinServer }
        if ($WinCred) { $cimParams.Credential = $WinCred }
        if ($WinUseSSL) { $cimParams.SessionOption = (New-CimSessionOption -UseSsl) }
        return (New-CimSession @cimParams)
    }

}

function Find-WinZone {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory,Position=0)]
        [string]$RecordName,
        [Parameter(Mandatory,Position=1)]
        [hashtable]$DnsParams
    )

    # setup a module variable to cache the record to zone mapping
    # so it's quicker to find later
    if (!$script:WinRecordZones) { $script:WinRecordZones = @{} }

    # check for the record in the cache
    if ($script:WinRecordZones.ContainsKey($RecordName)) {
        return $script:WinRecordZones.$RecordName
    }

    # get the zone list
    $zones = @(Get-DnsServerZone @DnsParams -EA Stop | Where-Object { !$_.IsAutoCreated -and $_.ZoneName -ne 'TrustAnchors' })

    # Since Windows could be hosting both apex and sub-zones, we need to find the closest/deepest
    # sub-zone that would hold the record rather than just adding it to the apex. So for something
    # like _acme-challenge.site1.sub1.sub2.example.com, we'd look for zone matches in the following
    # order:
    # - site1.sub1.sub2.example.com
    # - sub1.sub2.example.com
    # - sub2.example.com
    # - example.com

    $pieces = $RecordName.Split('.')
    for ($i=1; $i -lt ($pieces.Count-1); $i++) {
        $zoneTest = "$( $pieces[$i..($pieces.Count-1)] -join '.' )"
        Write-Debug "Checking $zoneTest"

        if ($zoneTest -in $zones.ZoneName) {
            $script:WinRecordZones.$RecordName = $zoneTest
            return $zoneTest
        }
    }

    return $null
}