scan.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
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# Scan APIs

function New-ICQuery {
  Param(
    [parameter(Mandatory=$True)]
    [String]$TargetGroupId,

    [parameter(Mandatory=$True)]
    [String]$credentialId,

    [String]$sshCredentialId,

    [parameter(Mandatory=$True)]
    [ValidateNotNullorEmpty()]
    [String]$Query,

    [String]$QueryName
    )

  $Credential = Get-ICCredential -CredentialId $CredentialId
  $TargetGroup = Get-ICTargetGroup -TargetGroupId $TargetGroupId
    Write-Host "Creating new Query ($query) in TargetGroup $TargetGroup.name using credential $($Credential.name) [$($Credential.username)]"
  $Endpoint = "queries"
  $data = @{
    value = $query
    targetId = $TargetGroupId
        name = $QueryName
  }
  if ($credentialId) {
    $data['credentialId'] = $CredentialId
  }
  if ($sshCredentialId) {
    $data['sshCredential'] = $sshCredentialId
  }
  $body = @{
    data = $data
  }
  _ICRestMethod -url $HuntServerAddress/api/$Endpoint -body $body -method POST
}

function Get-ICQuery ([String]$TargetGroupId) {
  $Endpoint = "queries"
  $filter =  @{
    limit = $resultlimit
    skip = 0
  }
  if ($TargetGroupId) {
    $filter['where'] = @{ targetId = $TargetGroupId }
    Write-Verbose "Getting Queries for Target Group Id: $TargetGroupId"
  }
  #Write-Verbose "Getting all Queries from TargetGroup $TargetGroup"
  _ICGetMethod -url $HuntServerAddress/api/$Endpoint -filter $filter -NoLimit:$true
}

function Remove-ICQuery {
  param(
    [parameter(Mandatory=$true, Position=0)]
    [ValidateNotNullOrEmpty()]
    [String]$QueryId
  )

  $Endpoint = "queries/$QueryId"
  Write-Warning "Removing query [$HuntServerAddress/api/$Endpoint]."
  _ICRestMethod -url $HuntServerAddress/api/$Endpoint -method 'DELETE'
}

function Invoke-ICFindHosts {
    [cmdletbinding()]
    param(
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [String]$TargetGroupId,

        [String]$QueryId
    )
    $TargetGroup = Get-ICTargetGroup -TargetGroupId $TargetGroupId
    $Queries = Get-ICQuery -TargetGroupId $TargetGroupId
    if (-NOT $Queries) {
        Throw "Target Group not found or does not have any Queries associated with it"
    }
    $Endpoint = "targets/$TargetGroupId/Enumerate"
    $body = @{
        queries = @()
    }
    if ($QueryId) {
        Write-Verbose "Starting Enumeration of $($TargetGroup.name) with Query $QueryId"
        $body['queries'] += $QueryId
        _ICRestMethod -url $HuntServerAddress/api/$Endpoint -body $body -method POST
    } else {
        $Queries | foreach {
            Write-Verbose "Starting Enumeration of $($TargetGroup.name) with Query $($Queries.id)"
            $body['queries'] += $Queries.Id
        }
        _ICRestMethod -url $HuntServerAddress/api/$Endpoint -body $body -method POST
    }
}

function Invoke-ICScan {
    [cmdletbinding()]
    param(
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [Alias("targetId")]
        [String]$TargetGroupId,

        [PSObject]$ScanOptions,

        [Switch]$PerformDiscovery
    )
    $TargetGroup = Get-ICTargetGroup -TargetGroupId $TargetGroupId
    if (-NOT $TargetGroup) {
        Throw "TargetGroup with id $TargetGroupId does not exist!"
    }
    if ($PerformDiscovery) {
        Write-Host "Performing discovery on $($TargetGroup.name)"
        $stillactive = $true
        $UserTask = Invoke-ICFindHosts -TargetGroupId $TargetGroupId
        While ($stillactive) {
            Start-Sleep 10
            $taskstatus = Get-ICUserTask -UserTaskId $UserTask.userTaskId
            if ($taskstatus.status -eq "Active") {
                    Write-Host "Waiting on Discovery. Progress: $($taskstatus.progress)%"
            } elseif ($taskstatus.status -eq "Completed") {
                    $stillactive = $false
            } else {
                Throw "Something went wrong in enumeration. Last Status: $($taskstatus.status)"
            }
        }

    }
    $Endpoint = "targets/$TargetGroupId/scan"
    Write-Verbose "Starting Scan of TargetGroup $($TargetGroup.name)"
  $body = @{ options = $ScanOptions }
    _ICRestMethod -url $HuntServerAddress/api/$Endpoint -body $body -method POST
}

function Invoke-ICScanTarget {
    [cmdletbinding()]
    param(
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$target,

        [String]$TargetGroupId,
        [String]$TargetGroupName = "OnDemand",

        [String]$CredentialId,
        [String]$CredentialName = "DefaultCredential",

    [String]$sshCredentialId,
        [String]$sshCredentialName,

    [PSObject]$ScanOptions
    )

  $body = @{
    target = $target
  }

    # Select Target targetgroup
    if ($TargetGroupId) {
        $TargetGroup = Get-ICTargetGroup -TargetGroupId $TargetGroupId
        if (-NOT $TargetGroup) {
                    Throw "TargetGroup with id $TargetGroupid does not exist!"
        } else {
      $body['targetGroup'] = @{id = $targetGroupId}
    }
    } else {
    Write-Verbose "Using Target Group Name [$TargetGroupName] -- will be created if it does not exist."
    $body['targetGroup'] = @{name = $TargetGroupName}
  }

    # Select Credential
    if ($CredentialId) {
        $Credential = Get-ICCredential -CredentialId $credentialId
        if (-NOT $Credential) {
            Throw "Credential with id $credentialId does not exist!"
        } else {
      $body['credential'] = @{ id = $credentialId }
    }
    } else {
    # Use Credentialname
    $Credential =  Get-ICCredential | where { $_.name -eq $CredentialName }
        if (-NOT $CredentialName) {
            Throw "Credential with name [$CredentialName] does not exist! Please create it or specify a different credential (referenced by id or name)"
      $body['credential'] = @{ name = $CredentialName }
      }
  }

  # Select Credential
  if ($sshCredentialId) {
      $body['sshcredential'] = @{ id = $credentialId }
  } elseif ($sshCredentialName) {
      $body['sshcredential'] = @{ name = $sshCredentialName }
  }

  if ($ScanOptions) {
        $body['options'] = $ScanOptions
    }
  <#
  EXAMPLE PAYLOAD
  {
    target: 'w12-01-infected.ca.galactica.int', // required
    targetGroup: { // optional
      id: null,
      name: '',
      scanAllAccessibleHosts: false
    },
    credential: { // required id or name
      id: null,
      name: 'service'
    },
    sshCredential: { // optional
      id: null,
      name: null
    },
    options: {}
  }
  #>


    # Initiating Scan
    $Endpoint = "targets/scan"
    Write-Verbose "Starting Scan of target $($target)"
    _ICRestMethod -url $HuntServerAddress/api/$Endpoint -body $body -method POST
}

function New-ICScanOptions {
    Write-Host 'ScanOption object properties should be set ($True or $False) and then passed into Invoke-ICScan or Add-ICScanSchedule'
    $options = @{
      EnableProcess = $true
        EnableAccount = $true
        EnableMemory = $true
        EnableModule = $true
        EnableDriver = $true
        EnableArtifact = $true
        EnableAutostart = $true
        EnableApplication = $true
        EnableHook = $true
        EnableNetwork = $true
        EnableLogDelete = $true
      EnableSurveyDelete = $true
        LowerPriority = $false
  }
    return $options
}

function Add-ICScanSchedule {
    [cmdletbinding()]
    param(
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [String]$TargetGroupId,

        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [String]$CronExpression,

        [PSObject]$ScanOptions
    )
    $TargetGroup = Get-ICTargetGroup -TargetGroupId $TargetGroupId
    if (-NOT $TargetGroup) {
        Throw "No such target group with id $TargetGroupId"
    }
    $Endpoint = "scheduledJobs"
    Write-Verbose "Creating new schedule for TargetGroup: $($TargetGroup.name) with Cron Express: $CronExpression"
  $body = @{
        name = 'scan-scheduled'
        relatedId = $TargetGroupId
        schedule = $CronExpression
        data = @{
            targetId = $TargetGroupId
        }
    }
    if ($ScanOptions) {
        if ($ScanOptions.EnableProcess -eq $True) {
                $body.data['options'] = $ScanOptions
        } else {
            Throw "ScanScheduleOptions format is invalid -- use New-ICScanScheduleOptions to create an options object"
        }
    }
    _ICRestMethod -url $HuntServerAddress/api/$Endpoint -body $body -method POST
}

function Get-ICScanchedule ($TargetGroupId) {
  $Endpoint = "ScheduledJobs"
  $filter =  @{
    order = @("relatedId")
    limit = $resultlimit
    skip = 0
  }
    if ($TargetGroupId) {
        $TargetGroups = Get-ICTargetGroup -TargetGroupId $TargetGroupId
        $ScheduledJobs = _ICGetMethod -url $HuntServerAddress/api/$Endpoint -filter $filter -NoLimit:$true | where { $_.relatedId -eq $TargetGroupId}
    } else {
        $TargetGroups = Get-ICTargetGroup
        $ScheduledJobs = _ICGetMethod -url $HuntServerAddress/api/$Endpoint -filter $filter -NoLimit:$true
    }

    $ScheduledJobs | % {
        if ($_.relatedId) {
             $tgid = $_.relatedId
             $tg = $TargetGroups | where { $_.id -eq $tgid }
             if ($tg) {
                 $_ | Add-Member -MemberType "NoteProperty" -name "targetGroup" -value $tg.name
             } else {
                 $_ | Add-Member -MemberType "NoteProperty" -name "targetGroup" -value $Null
             }
        }
    }
    $ScheduledJobs
}

function Remove-ICScanSchedule {
    [cmdletbinding(DefaultParameterSetName = 'scheduleId')]
    param(
        [parameter(
                Mandatory,
                ParameterSetName  = 'scheduleId',
                Position = 0,
                ValueFromPipeline,
                ValueFromPipelineByPropertyName
        )]
        [ValidateNotNullOrEmpty()]
        [string]$scheduleId,

        [parameter(
                Mandatory,
                ParameterSetName  = 'TargetGroupId'
        )]
        [ValidateNotNullOrEmpty()]
        [Alias("targetId")]
        $targetGroupId
    )

    $Schedules = Get-ICScanchedule
    if ($ScheduleId) {
        $schedule = $Schedules | where { $_.id -eq $ScheduleId}
    }
    elseif ($TargetGroupId) {
        $schedule = $Schedules | where { $_.relatedId -eq $TargetGroupId}
        $ScheduleId    = $schedule.id
    } else {
        throw "Incorrect input!"
    }
    $tgname = $schedule.targetGroup
    if (-NOT $tgname) { throw "TargetGroupId not found!"}
    $Endpoint = "scheduledJobs/$ScheduleId"
    Write-Host "Unscheduling collection for Target Group $tgname"
    _ICRestMethod -url $HuntServerAddress/api/$Endpoint -body $body -method DELETE
}

function Import-ICSurvey {
  # example script to upload a survey file to HUNT (2.10+)
  # Script to upload manual .bz2 file to hunt server.
    [cmdletbinding(DefaultParameterSetName = 'Path')]
    param(
        [parameter(
                Mandatory,
                ParameterSetName  = 'Path',
                Position = 0,
                ValueFromPipeline,
                ValueFromPipelineByPropertyName
        )]
        [ValidateNotNullOrEmpty()]
        [SupportsWildcards()]
        [string[]]$Path, # <paths of the survey results (.bz2) files to upload>

        [parameter(
                Mandatory,
                ParameterSetName = 'LiteralPath',
                Position = 0,
                ValueFromPipelineByPropertyName
        )]
        [ValidateNotNullOrEmpty()]
        [Alias('PSPath')]
        [string[]]$LiteralPath,

        [String]
        $ScanId,

        [String]
        $TargetGroupId,

          [String]
          $TargetGroupName = "OfflineScans"
  )

  BEGIN {
      # INITIALIZE
      $survey = "HostSurvey.json.gz"
      $surveyext = "*.json.gz"

      function Upload-ICSurveys ([String]$FilePath, [String]$ScanId){
          Write-Verbose "Uploading Surveys"
            $headers = @{
            Authorization = $Global:ICToken
                scanid = $ScanId
            }
          try {
              $objects = Invoke-RestMethod $HuntServerAddress/api/survey -Headers $headers -Method POST -InFile $FilePath -ContentType "application/octet-stream"
          } catch {
              Write-Warning "Error: $_"
              throw "ERROR: $($_.Exception.Message)"
          }
          $objects
      }

    if ($ScanId) {
        # Check for existing ScanId and use it
        $scans = Get-ICScan -NoLimit
        if ($scans.id -contains $ScanId) {
            $TargetGroupName = ($Scans | where { $_.scanId -eq $ScanId}).targetList
        } else {
            Throw "No scan exists with ScanId $ScanId. Specify an existing ScanId to add this survey result to or use other parameters to generate one."
        }
    }
    elseif ($TargetGroupId) {
        # Check TargetGroupId and create new ScanId for that group
        Write-Host "Checking for existance of target group with TargetGroupId: '$TargetGroupId' and generating new ScanId"
        $TargetGroups = Get-ICTargetGroup
        if ($TargetGroups.id -contains $TargetGroupId) {
            $TargetGroupName = ($TargetGroups | where { $_.id -eq $TargetGroupId }).name
        } else {
            Throw "No Target Group exists with TargetGroupId $TargetGroupId. Specify an existing TargetGroupId to add this survey to or use other parameters to generate one."
        }
    }
    else {
        Write-Host "No ScanId or TargetGroupId specified. Checking for existance of target group: '$TargetGroupName'"
          $TargetGroups = Get-ICTargetGroup
          if ($TargetGroups.name -contains $TargetGroupName) {
              Write-Host "$TargetGroupName Exists."
            $TargetGroupId = ($targetGroups | where { $_.name -eq $TargetGroupName}).id
          } else {
            Write-Host "$TargetGroupName does not exist. Creating new Target Group '$TargetGroupName'"
            $g = Get-ICControllerGroup
            if ($g.id.count -eq 1) {
                $ControllerGroupId = $g.id
            } else {
                $ControllerGroupId = $g[0].id
            }
            $TargetGroupId = (New-ICTargetGroup -Name $TargetGroupName -ControllerGroupId $ControllerGroupId).id
          }
    }

    # Creating ScanId
    if (-NOT $ScanId) {
        $ScanName = "Offline-" + (get-date).toString("yyyyMMdd-HHmm")
        Write-Host "Creating scan named $ScanName [$TargetGroupName-$ScanName]..."
        $StartTime = _Get-ICTimeStampUTC
        $body = @{
            name = $scanName;
            targetId = $TargetGroupId;
            startedOn = $StartTime
        }
        $newscan = _ICRestMethod -url $HuntServerAddress/api/scans -body $body -Method 'POST'
        Start-Sleep 1
        $ScanId = $newscan.id
    }


    Write-Host "Importing Survey Results into $TargetGroupName-$ScanName [ScanId: $ScanId] [TargetGroupId: $TargetGroupId]"
  }

  PROCESS {
        # Resolve path(s)
        if ($PSCmdlet.ParameterSetName -eq 'Path') {
            $resolvedPaths = Resolve-Path -Path $Path | Select-Object -ExpandProperty Path
        } elseif ($PSCmdlet.ParameterSetName -eq 'LiteralPath') {
            $resolvedPaths = Resolve-Path -LiteralPath $LiteralPath | Select-Object -ExpandProperty Path
        }

                # Process each item in resolved paths
                foreach ($file in $resolvedPaths) {
                     Write-Host "Uploading survey [$file]..."
                     if ((Test-Path $file -type Leaf) -AND ($file -like $surveyext)) {
                         Upload-ICSurveys -FilePath $file -ScanId $ScanId
                   } else {
                       Write-Warning "$file does not exist or is not a $surveyext file"
                   }
               }
    }

  END {
      # TODO: detect when scan is no longer processing submissions, then mark as completed
      #Write-Host "Closing scan..."
      #Invoke-RestMethod -Headers @{ Authorization = $token } -Uri "$HuntServerAddress/api/scans/$scanId/complete" -Method Post
  }

}