Classes/Main/PrtgServer.Class.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
class PrtgServer {
    [string]$Hostname

    [ValidateRange(1, 65535)]
    [int]$Port = 443

    [ValidateSet('http', 'https')]
    [string]$Protocol = "https"

    [string]$UserName
    [string]$PassHash

    # Track usage
    [int]$ReturnCount = 500
    [int]$CurrentStartPosition = 0
    hidden [bool]$Connected
    [array]$UrlHistory
    [array]$RawQueryResultHistory
    [array]$QueryHistory
    $LastError
    $LastResult

    # Status Properties
    [int]$NewAlarms
    [int]$Alarms
    [int]$AckAlarms
    [int]$NewToDos
    [string]$Clock
    [datetime]$ClockasDateTime
    [string]$ActivationStatusMessage
    [int]$BackgroundTasks
    [int]$CorrelationTasks
    [int]$AutoDiscoTasks
    [string]$Version
    [bool]$PRTGUpdateAvailable
    [bool]$IsAdminUser
    [bool]$IsCluster
    [bool]$ReadOnlyUser
    [bool]$ReadOnlyAllowAcknowledge

    # Generate Api URL
    [String] getApiUrl([hashtable]$queryHashtable, [string]$queryPage) {
        $formattedQueryString = [HelperWeb]::createQueryString($queryHashtable)
        if ($this.Hostname) {
            $url = $this.Protocol + "://" + $this.Hostname + ':' + $this.Port + "/api/" + $queryPage + $formattedQueryString
            return $url
        } else {
            return $null
        }
    }


    # Test Connection
    [bool] testConnection() {
        $result = $this.invokeApiQuery(@{}, 'getstatus.xml')
        $this.Connected = $true
        $this.NewAlarms = $result.status.NewAlarms
        $this.Alarms = $result.status.Alarms
        $this.AckAlarms = $result.status.AckAlarms
        $this.NewToDos = $result.status.NewToDos
        $this.Clock = $result.status.Clock
        $this.ClockasDateTime = $result.status.Clock
        $this.ActivationStatusMessage = $result.status.ActivationStatusMessage
        $this.BackgroundTasks = $result.status.BackgroundTasks
        $this.CorrelationTasks = $result.status.CorrelationTasks
        $this.AutoDiscoTasks = $result.status.AutoDiscoTasks
        $this.Version = $result.status.Version
        $this.PRTGUpdateAvailable = $result.status.PRTGUpdateAvailable
        $this.IsAdminUser = $result.status.IsAdminUser
        $this.IsCluster = $result.status.IsCluster
        $this.ReadOnlyUser = $result.status.ReadOnlyUser
        $this.ReadOnlyAllowAcknowledge = $result.status.ReadOnlyAllowAcknowledge
        return $true
    }

    #region ApiQueryFunctions
    ###################################################################################################
    #region GetPassHashQuery
    # example: https://prtg.example.com/api/getpasshash.htm?username=JohnDoe&password=TopSecret
    [xml] invokeGetPassHashQuery([PSCredential]$credential) {
        $queryString = @{}
        $queryPage = "getpasshash.htm"
        $queryString.username = $credential.UserName
        $queryString.password = $Credential.getnetworkcredential().password
        $result = $this.invokeApiQuery($queryString, $queryPage)
        $this.UserName = $credential.UserName
        $this.PassHash = $result.objects.object.'#text'
        return $result
    }
    #endregion GetPassHashQuery

    #region invokeApiQueryBatches
    [array] invokeApiQuery([hashtable]$queryHashtable, [string]$queryPage, [string]$itemNode = $null) {
        Write-Verbose "Calling invokeapiquery with itemNode: $itemNode"
        Write-Verbose "ReturnCount: $($this.ReturnCount)"
        Write-Verbose "CurrentStartPosition: $($this.CurrentStartPosition)"
        $ContinueLoop = $true
        $allResults = @()
        $checkResults = @{}
        $queryHashtable.returncount = $this.ReturnCount
        $result = $this.invokeApiQuery($queryHashtable, $queryPage)
        $result = $result.$itemNode.item
        $allResults += $result
        foreach ($r in $result) {
            $thisId = $r.objid
            $checkResults.$thisId = $r
        }
        do {
            $this.CurrentStartPosition = $this.CurrentStartPosition + $this.ReturnCount
            $queryHashtable.start = $this.CurrentStartPosition
            Write-Verbose "CurrentStartPosition: $($this.CurrentStartPosition)"
            Write-Verbose "allResults Count: $($allResults.Count)"
            $result = $this.invokeApiQuery($queryHashtable, $queryPage)
            $result = $result.$itemNode.item
            foreach ($r in $result) {
                $thisId = $r.objid
                if ($checkResults.$thisId) {
                    $ContinueLoop = $false
                } else {
                    $checkResults.$thisId = $r
                    $allResults += $r
                }
            }
        } while ($ContinueLoop)
        $this.CurrentStartPosition = 0
        $this.LastResult = $allResults
        return $allResults
    }
    #endregion invokeApiQueryBatches

    #region invokeApiQuery
    [xml] invokeApiQuery([hashtable]$queryHashtable, [string]$queryPage) {
        # If the query is not a GetPassHash query we need to append the PassHash and UserName to the query string
        if ($queryPage -ne "getpasshash.htm") {
            $queryHashtable.username = $this.UserName
            $queryHashtable.passhash = $this.PassHash
        }

        $url = $this.getApiUrl($queryHashtable, $queryPage)

        #region trackHistory
        # Populate Query/Url History
        # Redact password if it's a keygen query
        if ($queryPage -ne "getpasshash.htm") {
            $this.UrlHistory += $url
        } else {
            $EncodedPassword = [System.Uri]::EscapeDataString($queryHashtable.password)
            $queryHashtable.password = 'PASSWORDREDACTED'
            $this.UrlHistory += $url.Replace($EncodedPassword, "PASSWORDREDACTED")
        }

        # add query object to QueryHistory
        $this.QueryHistory += $queryHashtable
        #endregion trackHistory



        # try query
        try {
            $QueryParams = @{}
            $QueryParams.Uri = $url
            $QueryParams.UseBasicParsing = $true

            switch ($global:PSVersionTable.PSEdition) {
                'Core' {
                    $QueryParams.SkipCertificateCheck = $true
                    continue
                }
                default {
                    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
                    try {
                        add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@

                    } catch {

                    }
                    [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
                    continue
                }
            }

            $rawResult = Invoke-WebRequest @QueryParams -Verbose:$false # doing this mostly to prevent plaintext password from being displayed by accident.
        } catch {
            Throw $_
        }

        $this.RawQueryResultHistory += $rawResult

        if ($queryPage -eq "getpasshash.htm") {
            $result = @{'passhash' = $rawResult.Content}
            $result = [xml]($result.passhash | ConvertTo-Xml)
        } else {
            $result = [xml]($rawResult.Content)
        }

        $this.LastResult = $result

        return $result

        <#

        $result = [xml]($rawResult.Content)


        $proccessedResult = $this.processQueryResult($result)

        return $proccessedResult #>

    }
    #endregion invokeApiQuery
    ###################################################################################################
    #endregion ApiQueryFunctions

    #region Initiators
    ###################################################################################################
    # Blank Initiator
    PrtgServer() {
    }

    # Initiator with PassHash
    PrtgServer([string]$Hostname, [string]$UserName, [string]$PassHash, [string]$Protocol = "https", [int]$Port = 443) {
        $this.Hostname = $Hostname
        $this.UserName = $UserName
        $this.PassHash = $PassHash
        $this.Protocol = $Protocol
        $this.Port = $Port
    }

    # Initiator with Credential
    PrtgServer([string]$Hostname, [PSCredential]$Credential, [string]$Protocol = "https", [int]$Port = 443) {
        $this.Hostname = $Hostname
        $this.Protocol = $Protocol
        $this.Port = $Port
        $this.invokeGetPassHashQuery($Credential)
    }
    #endregion Initiators
}