-
Notifications
You must be signed in to change notification settings - Fork 100
/
SMTPBannerReport.ps1
95 lines (90 loc) · 3.79 KB
/
SMTPBannerReport.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
function Invoke-GetSMTPBannerVersion{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$Domain,
[Parameter(Mandatory = $false)]
[int]
$Port = 25
)
Process {
Clear-DnsClientCache
$rptCollection = @()
$buffer = New-Object System.Byte[] 20240
$encoding = New-Object System.Text.AsciiEncoding
try{
$mxRecords = Resolve-DnsName -Name $Domain -Type MX -ErrorAction Stop
Write-Verbose ("Number of MX Records for $Domain " + $mxRecords.Count)
foreach($mxRecord in $mxRecords){
if($mxRecord.Type = 15 -band (![String]::IsNullOrEmpty($mxRecord.NameExchange))){
$rptObj = "" | select Domain,Server,MXPreference,Banner
$rptObj.Domain = $Domain
$rptObj.Server = $mxRecord.NameExchange
$rptObj.MXPreference = $mxRecord.Preference
Write-Verbose("Testing $mxRecord.NameExchange")
$client = new-object System.Net.Sockets.TcpClient
$client.ConnectAsync($mxRecord.NameExchange, $Port).Wait(5000).Result | Out-Null
if($client.Connected){
Write-Verbose("Connection Sucess")
$stream = $client.GetStream()
$streamWriter = new-object System.IO.StreamWriter($stream)
$streamReader = new-object System.IO.StreamReader($stream)
$stream.ReadTimeout = 5000
$stream.WriteTimeout = 5000
$streamWriter.AutoFlush = $true
try{
$read = $streamReader.BaseStream.Read($buffer,0,20240)
$ConnectResponse = ($encoding.GetString($buffer, 0, $read))
$buffer = New-Object System.Byte[] 20240
Write-Verbose($ConnectResponse)
$rptObj.Banner = $ConnectResponse
if(!$ConnectResponse.StartsWith("220")){
throw "Error connecting to the SMTP Server " + $ConnectResponse
}
}catch{
$ExceptionMessage = Invoke-GetExceptionMessage $PSItem.Exception
Write-Verbose $ExceptionMessage
}
$streamReader.Close()
$streamReader.Dispose()
$streamWriter.Close()
$streamWriter.Dispose()
$client.Close()
$rptCollection += $rptObj
}else{
Write-Verbose("Connection Failed")
}
Write-Verbose("Done")
}
}
}catch{
Write-Output $PSItem.Exception.Message
}
return $rptCollection
}
}
function Invoke-GetExceptionMessage{
[CmdletBinding()]
param (
[Parameter()]
[PSObject]
$Exception
)
Process{
if(!$Exception.Message){
$exceptionMsg = $Exception.Message
while ($Exception.InnerException) {
$Exception = $Exception.InnerException
if(!$Exception.Message){
if(!$exceptionMsg.Contains($Exception.Message)){
$exceptionMsg += " " + $Exception.Message
}
}
}
}else{
$exceptionMsg = $Exception
}
return $exceptionMsg
}
}