-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-DnsRecord.ps1
More file actions
443 lines (369 loc) · 16.8 KB
/
Copy pathGet-DnsRecord.ps1
File metadata and controls
443 lines (369 loc) · 16.8 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
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
function Get-DnsRecord
{
<#
.SYNOPSIS
Retrieves DNS records for a specified domain name.
.DESCRIPTION
Queries DNS records for a domain name supporting all common record types (A, AAAA, MX, TXT, NS, CNAME, SOA, SRV, PTR, CAA).
This function provides cross-platform DNS resolution using DNS-over-HTTPS (DoH) APIs for comprehensive record type support.
The default ANY query fans out to each forward record type included in the expansion because most resolvers restrict direct
ANY responses per RFC 8482.
Native .NET DNS resolution is also available for A and AAAA queries; native ANY returns both available address families.
Uses Cloudflare's DNS-over-HTTPS API (1.1.1.1) by default for maximum compatibility and privacy.
Compatible with PowerShell Desktop 5.1+ on Windows, macOS, and Linux.
.PARAMETER Name
The domain name to query for DNS records.
Accepts pipeline input for querying multiple domains.
.PARAMETER Type
The DNS record type to query.
Valid values: A, AAAA, MX, TXT, NS, CNAME, SOA, SRV, PTR, CAA, ANY
Default is 'ANY', which queries each forward record type included in the expansion when using DNS-over-HTTPS.
.PARAMETER Server
The DNS server to use for queries. Supports standard DNS servers and DNS-over-HTTPS endpoints.
Default is 'cloudflare' which uses Cloudflare's 1.1.1.1 DoH service.
Other options: 'google' (8.8.8.8), or specify a custom DoH URL.
.PARAMETER UseDNS
Use native DNS resolution instead of DNS-over-HTTPS.
Native DNS supports A and AAAA record types reliably across platforms.
When Type is ANY, both available address families are returned. Other record types produce a warning and no output.
.PARAMETER Timeout
Request timeout in seconds for DNS-over-HTTPS queries.
Default is 10 seconds. Valid range: 1-60 seconds.
.EXAMPLE
PS > Get-DnsRecord -Name 'bing.com'
Name Type TTL Data
---- ---- --- ----
bing.com A 29 142.251.167.139
bing.com A 29 142.251.167.101
bing.com NS 3599 ns1.msft.net.
bing.com MX 85 10 smtp.bing.com.
bing.com TXT 201 v=spf1 include:_spf.bing.com ~all
...
Retrieves all available DNS records for bing.com using Cloudflare DoH.
.EXAMPLE
PS > Get-DnsRecord -Name 'bing.com' -Type MX
Name Type TTL Data
---- ---- --- ----
bing.com MX 85 10 smtp.bing.com.
Retrieves MX (mail exchange) records for bing.com.
.EXAMPLE
PS > Get-DnsRecord -Name 'bing.com' -Type TXT
Name Type TTL Data
---- ---- --- ----
bing.com TXT 201 docusign=1b0a6754-49b1-4db5-8540-d2c12664b289
bing.com TXT 201 onetrust-domain-verification=de01ed21f2fa4d8781cbc3ffb89cf4ef
...
...
Retrieves TXT records (often used for SPF, DKIM, domain verification).
.EXAMPLE
PS > @('bing.com', 'github.com', 'microsoft.com') | Get-DnsRecord -Type A
Retrieves A records for multiple domains using pipeline input.
.EXAMPLE
PS > Get-DnsRecord -Name 'bing.com' -Type AAAA -Server google
Retrieves IPv6 (AAAA) records using Google's DNS-over-HTTPS service.
.EXAMPLE
PS > Get-DnsRecord -Name '_dmarc.bing.com' -Type TXT
Retrieves DMARC policy TXT record.
.EXAMPLE
PS > Get-DnsRecord -Name 'bing.com' -Type NS
Retrieves nameserver (NS) records for bing.com.
.EXAMPLE
PS > Get-DnsRecord -Name 'bing.com' -Type SOA
Retrieves Start of Authority (SOA) record.
.EXAMPLE
PS > Get-DnsRecord -Name '_ldap._tcp.dc._msdcs.example.com' -Type SRV
Retrieves SRV (service) records.
.EXAMPLE
PS > Get-DnsRecord -Name 'localhost' -UseDNS
Name Type TTL Data
---- ---- --- ----
localhost AAAA ::1
localhost A 127.0.0.1
Uses native DNS resolution with the default ANY type to return locally resolved A and AAAA addresses.
.EXAMPLE
PS > Get-DnsRecord -Name 'example.com' -Type MX
Query MX records using an alternative DoH provider.
.EXAMPLE
PS > $env:DOMAIN | Get-DnsRecord -Type TXT -Server cloudflare | Where-Object { $_.Name -like '_acme-challenge*' }
Verifies that ACME TXT challenges have propagated before letting an automated certificate renewal continue.
.OUTPUTS
System.Management.Automation.PSCustomObject
Returns objects with Name, Type, TTL, and Data properties for each DNS record found.
.LINK
https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/
.LINK
https://developers.google.com/speed/public-dns/docs/doh
.NOTES
DNS-over-HTTPS Providers:
- Cloudflare: https://cloudflare-dns.com/dns-query
- Google: https://dns.google/resolve
Network Requirements:
- Requires internet connectivity to reach DoH providers
- If DoH is blocked, use -UseDNS for native A or AAAA resolution; the default ANY type returns both
For air-gapped or restricted environments, use -UseDNS with A, AAAA, or ANY.
Author: Jon LaBelle
License: MIT
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/NetworkAndDns/Get-DnsRecord.ps1
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/NetworkAndDns/Get-DnsRecord.ps1
#>
[CmdletBinding(DefaultParameterSetName = 'DoH')]
[OutputType([System.Management.Automation.PSCustomObject])]
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, Position = 0)]
[ValidateNotNullOrEmpty()]
[Alias('Domain', 'HostName')]
[String]$Name,
[Parameter(Position = 1)]
[ValidateSet('A', 'AAAA', 'MX', 'TXT', 'NS', 'CNAME', 'SOA', 'SRV', 'PTR', 'CAA', 'ANY')]
[String]$Type = 'ANY',
[Parameter(ParameterSetName = 'DoH')]
[ValidateSet('cloudflare', 'google')]
[String]$Server = 'cloudflare',
[Parameter(ParameterSetName = 'Native')]
[Switch]$UseDNS,
[Parameter()]
[ValidateRange(1, 60)]
[Int32]$Timeout = 10
)
begin
{
Write-Verbose 'Initializing DNS query'
# DNS-over-HTTPS (DoH) endpoints
$dohEndpoints = @{
cloudflare = 'https://cloudflare-dns.com/dns-query'
google = 'https://dns.google/resolve'
}
# DNS record type numeric codes (for DoH API)
$recordTypes = @{
A = 1
NS = 2
CNAME = 5
SOA = 6
PTR = 12
MX = 15
TXT = 16
AAAA = 28
SRV = 33
CAA = 257
ANY = 255
}
}
process
{
Write-Verbose "Querying DNS records for '$Name' (Type: $Type)"
try
{
if ($UseDNS)
{
# Use native .NET DNS resolution (limited to A/AAAA)
Write-Verbose 'Using native DNS resolution'
if ($Type -notin @('A', 'AAAA', 'ANY'))
{
Write-Warning "Native DNS resolution only supports A, AAAA, and ANY records. Use DNS-over-HTTPS (default) for $Type records."
return
}
$addresses = [System.Net.Dns]::GetHostAddresses($Name)
if ($Type -eq 'A')
{
$addresses = $addresses | Where-Object { $_.AddressFamily -eq 'InterNetwork' }
}
elseif ($Type -eq 'AAAA')
{
$addresses = $addresses | Where-Object { $_.AddressFamily -eq 'InterNetworkV6' }
}
foreach ($addr in $addresses)
{
$resolvedType = if ($Type -eq 'ANY')
{
if ($addr.AddressFamily -eq 'InterNetwork') { 'A' } else { 'AAAA' }
}
else
{
$Type
}
[PSCustomObject]@{
Name = $Name
Type = $resolvedType
TTL = $null
Data = $addr.ToString()
}
}
}
else
{
# When ANY is requested, expand to individual queries per type since RFC 8482
# restricts ANY responses - most DoH resolvers return nothing or HINFO.
if ($Type -eq 'ANY')
{
Write-Verbose 'ANY type requested - querying all record types individually (RFC 8482)'
$allTypes = @('A', 'AAAA', 'MX', 'TXT', 'NS', 'CNAME', 'SOA', 'SRV', 'CAA')
foreach ($queryType in $allTypes)
{
Get-DnsRecord -Name $Name -Type $queryType -Server $Server -Timeout $Timeout -WarningAction SilentlyContinue
}
return
}
# Use DNS-over-HTTPS
$dohUrl = $dohEndpoints[$Server]
Write-Verbose "Using DNS-over-HTTPS: $dohUrl"
# Prepare HTTP client without proxy (try direct connection first)
$handler = [System.Net.Http.HttpClientHandler]::new()
$handler.UseProxy = $false
$httpClient = [System.Net.Http.HttpClient]::new($handler)
$httpClient.Timeout = [TimeSpan]::FromSeconds($Timeout)
$httpClient.DefaultRequestHeaders.Accept.Add([System.Net.Http.Headers.MediaTypeWithQualityHeaderValue]::new('application/dns-json'))
# Build query URL
$recordTypeCode = $recordTypes[$Type]
$queryUrl = "${dohUrl}?name=${Name}&type=${recordTypeCode}"
Write-Verbose "Query URL: $queryUrl"
# Send request with proxy retry logic
$response = $null
$proxyRetryNeeded = $false
try
{
$response = $httpClient.GetAsync($queryUrl).GetAwaiter().GetResult()
}
catch [System.Net.Http.HttpRequestException]
{
# Check if it's a proxy-related error or connection failure that might need proxy
if ($_.Exception.Message -match 'proxy.*required|407|connection.*refused|unable to connect')
{
Write-Verbose "Direct connection failed, retrying with system proxy: $($_.Exception.Message)"
$proxyRetryNeeded = $true
}
else
{
throw
}
}
# Retry with system proxy if direct connection failed
if ($proxyRetryNeeded)
{
# Dispose previous client and handler
$httpClient.Dispose()
$handler.Dispose()
# Create new client with system proxy enabled
$handler = [System.Net.Http.HttpClientHandler]::new()
$handler.UseProxy = $true
$handler.Proxy = [System.Net.WebRequest]::GetSystemWebProxy()
$handler.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
$httpClient = [System.Net.Http.HttpClient]::new($handler)
$httpClient.Timeout = [TimeSpan]::FromSeconds($Timeout)
$httpClient.DefaultRequestHeaders.Accept.Add([System.Net.Http.Headers.MediaTypeWithQualityHeaderValue]::new('application/dns-json'))
Write-Verbose 'Retrying request with system proxy'
$response = $httpClient.GetAsync($queryUrl).GetAwaiter().GetResult()
}
if ($response.IsSuccessStatusCode)
{
$jsonContent = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
$dnsResponse = $jsonContent | ConvertFrom-Json
Write-Verbose "DNS query status: $($dnsResponse.Status)"
# Status codes: 0=NOERROR, 2=SERVFAIL, 3=NXDOMAIN
if ($dnsResponse.Status -eq 0 -and $dnsResponse.Answer)
{
foreach ($record in $dnsResponse.Answer)
{
# Parse the data field based on record type
$recordData = switch ($Type)
{
'MX'
{
# MX records have priority and exchange
"$($record.data)"
}
'SRV'
{
# SRV records have priority, weight, port, target
"$($record.data)"
}
'SOA'
{
# SOA records have multiple fields
"$($record.data)"
}
'TXT'
{
# TXT records may need quotes removed
$record.data -replace '^"(.*)"$', '$1'
}
default
{
$record.data
}
}
[PSCustomObject]@{
Name = $record.name
Type = switch ($record.type)
{
1 { 'A' }
2 { 'NS' }
5 { 'CNAME' }
6 { 'SOA' }
12 { 'PTR' }
15 { 'MX' }
16 { 'TXT' }
28 { 'AAAA' }
33 { 'SRV' }
257 { 'CAA' }
default { "TYPE$($record.type)" }
}
TTL = $record.TTL
Data = $recordData
}
}
}
elseif ($dnsResponse.Status -eq 3)
{
Write-Verbose "Domain not found (NXDOMAIN): $Name"
Write-Warning "DNS query returned NXDOMAIN: '$Name' does not exist"
}
elseif ($dnsResponse.Status -eq 2)
{
Write-Verbose "Server failure (SERVFAIL) for: $Name"
Write-Warning "DNS query returned SERVFAIL for '$Name'"
}
else
{
Write-Verbose "No records found for $Name (Type: $Type)"
if ($dnsResponse.Status -eq 0)
{
Write-Warning "No $Type records found for '$Name'"
}
}
}
else
{
Write-Error "DNS-over-HTTPS request failed with status code: $($response.StatusCode)"
}
# Cleanup
if ($response) { $response.Dispose() }
if ($httpClient) { $httpClient.Dispose() }
if ($handler) { $handler.Dispose() }
}
}
catch [System.Net.Sockets.SocketException]
{
Write-Verbose "Socket exception: $($_.Exception.Message)"
Write-Error "DNS resolution failed for '$Name': $($_.Exception.Message)"
}
catch [System.Net.Http.HttpRequestException]
{
Write-Verbose "HTTP request exception: $($_.Exception.Message)"
if ($_.Exception.InnerException)
{
Write-Verbose "Inner exception: $($_.Exception.InnerException.Message)"
}
Write-Error "DNS-over-HTTPS request failed for '$Name': $($_.Exception.Message)"
}
catch
{
Write-Verbose "Unexpected error: $($_.Exception.Message)"
Write-Error "DNS query error for '$Name': $($_.Exception.Message)"
}
}
end
{
Write-Verbose 'DNS query completed'
}
}