Posts Tagged ‘remediation’

I spend a considerable amount of time in the QualysGuard web interface editing remediation tickets. It’s one of those admin tasks that you dread doing, but have to do.

If you’ve ever used the QualysGuard web user interface, you’ll know that it’s not particularly fast. Aside from the speed of the UI, there are also functional limitations. For example, you can only display 500 tickets per page. So, to edit 5,000 tickets, you need to browse through 10 pages and select all tickets on each page. Also, if you want to select tickets by ticket number or QID, you can only select one ticket number or QID at a time.

Thankfully, Qualys have provided a powerful API that overcomes these limitations. I have written a PowerShell script that takes full advantage of the ticket_edit.php API function to edit up to 20,000 remediation tickets at a time.

A detailed help section is provided in the script. In a PowerShell console, type: get-help .\edit-qualysticket.ps1 –detailed

You will need to configure the $urlQualysLocation variable to set the QualysGuard URL for your location. For more information on the Qualys API, visit here: https://community.qualys.com/community/developer

<#
.SYNOPSIS
This Powershell script uses the QualysGuard API to edit remedation tickets.

.DESCRIPTION
The script uses the ticket_edit.php API function in QualysGuard to edit remediation tickets in a QualysGuard subscription. This function allows you to change the ticket assignee, open and close tickets, and add comments to tickets. Several input parameters are available for ticket selection. At least one ticket selection parameter is required, and one edit parameter is required.

The API is more powerful than the QualysGuard User Interface in how you can select tickets for editing, e.g. ability to select multiple ticket numbers or QIDs at a time, ability to select up to 20,000 tickets at a time without having to browse and select 500 tickets per page using the web UI. 

.PARAMETER TicketNumbers
Tickets with certain ticket numbers. Specify one or more ticket numbers and/or ranges. Use a comma (,) to separate multiple tickets

.PARAMETER SinceTicketNumber
Tickets since a certain ticket number. Specify the lowest ticket number to be selected. Selected tickets will have numbers greater than or equal to the ticket number specified.

.PARAMETER UntilTicketNumber
Tickets until a certain ticket number. Specify the highest ticket number to be selected. Selected tickets will have numbers less than or equal to the ticket number specified.

.PARAMETER Overdue
Tickets that are overdue or not overdue. When not specified, overdue and non-overdue tickets are selected. Specify 1 to select only overdue tickets. Specify 0 to select only tickets that are not overdue.

.PARAMETER Invalid
Tickets that are invalid or valid. When not specified, both valid and invalid tickets are selected. Specify 1 to select only invalid tickets. Specify 0 to select only valid tickets. You can select invalid tickets owned by other users, not yourself.

.PARAMETER ModifiedSinceDateTime
Tickets modified since a certain date/time. Specify a date (required) and time (optional) since tickets were modified. Tickets modified on or after the date/time are selected. The start date/time is specified in YYYY-MMDD[THH:MM:SSZ] format (UTC/GMT), like “2006-01-01” or “2006-05-25T23:12:00Z”.

.PARAMETER UnModifiedSinceDateTime
Tickets not modified since a certain date/time. Specify a date (required) and time (optional) since tickets were not modified. Tickets not modified on or after the date/time are selected. The date/time is specified in YYYY-MM-DD[THH:MM:SSZ] format (UTC/GMT), like “2006-01-01” or “2006-05-25T23:12:00Z”.

.PARAMETER IPs
Tickets on hosts with certain IP addresses. Specify one or more IP addresses and/or ranges. Multiple entries are comma separated.

.PARAMETER DNSContains
Tickets on hosts that have a NetBIOS host name which contains a certain text string. Specify a text string to be used. This string may include a maximum of 100 characters.

.PARAMETER NETBIOSContains
Tickets on hosts that have a NetBIOS host name which contains a certain text string. Specify a text string to be used. This string may include a maximum of 100 characters.

.PARAMETER VendorRefContains
Tickets for vulnerabilities that have a vendor reference which contains a certain text string. Specify a text string. This string may include a maximum of 100 characters.

.PARAMETER TicketAssignee
Tickets with a certain assignee. Specify the user login of an active user account.

.PARAMETER States
Tickets with certain ticket state/status. Specify one or more state/status codes from (OPEN,RESOLVED,CLOSED,IGNORED). Use a comma (,) to separate multiple. A valid value is OPEN (for state/status Open or Open/Reopened), RESOLVED (for state Resolved), CLOSED(for state/status Closed/Fixed), or IGNORED (for state/status Closed/Ignored). 

.PARAMETER AssetGroups
Tickets on hosts with IP addresses which are defined in certain asset groups. Specify the title of one or more asset groups. Multiple asset groups are comma separated. The title “All” may be specified to select all IP addresses in the user account.

.PARAMETER VulnSevereties
Tickets for vulnerabilities with certain severity levels. Specify one or more severity levels. Multiple levels are comma separated. (1,2,3,4,5)

.PARAMETER PotVulnSevereties
Tickets for potential vulnerabilities with certain severity levels. Specify one or more severity levels. Multiple levels are comma separated. (1,2,3,4,5)

.PARAMETER QIDs
Tickets for vulnerabilities with certain QIDs (Qualys IDs). Specify one or more QIDs. A maximum of 10 QIDs may be specified. Multiple QIDs are comma separated.

.PARAMETER VulnTitleContains
Tickets for vulnerabilities that have a title which contains a certain text string. The vulnerability title is defined in the KnowledgeBase. Specify a text string and enclose in double quotes ("insert text here"). This string may include a maximum of 100 characters.

.PARAMETER VulnDetailsContains
Tickets for vulnerabilities that have vulnerability details which contain a certain text string. Vulnerability details provide descriptions for threat, impact, solution and results (scan test results, when available). Specify a text string and enclose in double quotes ("insert text here"). This string may include a maximum of 100 characters.

.PARAMETER ChangeAssignee
Used to change the ticket assignee, specified by user login, in all selected tickets. The assignee’s account must have a user role other than Contact, and the hosts associated with the selected tickets must be in the user account.

.PARAMETER ChangeState
Used to change the ticket state/status to the specified state/status in all selected tickets.(OPEN,RESOLVED,IGNORED) A valid value is OPEN (for state/status Open and Open/Reopened),RESOLVED (for state Resolved), or IGNORED (for state/status Closed/Ignored). 

.PARAMETER AddComment
Used to add a comment in all selected tickets. The comment text may include a maximum of 2,000 characters. Enclose all comments in double quotes ("insert text here").

.EXAMPLE
Edit-QualysTickets.ps1 -QIDs 76543 -ChangeState RESOLVED -AddComment "This vulnerability has been addressed. Changing ticket state to RESOLVED." 

.EXAMPLE
Edit-QualysTickets.ps1 -TicketNumbers 12345,23456 -Assignee usrts-ab -States OPEN,RESOLVED -ChangeAssignee usrts-bc -ChangeState IGNORED -AddComment "Re-assigning tickets from user usrts-ab to usrts-bc and changing state to IGNORED." 

.EXAMPLE
Edit-QualysTickets.ps1 -IPs 192.168.1,192.168.2 -ModifiedSinceDateTime 2011-09-16T00:00:00Z -States RESOLVED -VulnSevereties 4,5 -VulnTitleContains "Adobe Reader" -ChangeState OPEN

.NOTES
Requires a QualysGuard account with permission to edit tickets for a given asset group. Managers and Unit Managers have permission to run this API function.

A maximum of 20,000 tickets can be edited in one request. The QualysGuard credentials are transmitted using the "Basic Authentication Scheme" over HTTPS.

The Script saves the Qualys response in XML format and writes output to a log file. These files are saved in the %temp% directory. The $urlQualysLocation variable must be configured with the QualysGuard URL for your subscription location.

.LINK
https://powersheller.wordpress.com

#>

Param ([ValidateCount(1,1000)]
[string[]]$TicketNumbers,
[string]$SinceTicketNumber,
[string]$UntilTicketNumber,
[string]$TicketAssignee,
[ValidateSet("0","1")]
[string]$Overdue,
[ValidateSet("0","1")]
[string]$Invalid,
[ValidateSet("OPEN","RESOLVED","CLOSED","IGNORED")] 
[string[]]$States,
[string]$ModifiedSinceDateTime,
[string]$UnModifiedSinceDateTime,
[string[]]$IPs,
[string[]]$AssetGroups,
[ValidateLength(1,100)]
[string]$DNSContains,
[ValidateLength(1,100)]
[string]$NetbiosContains,
[ValidateSet("1","2","3","4","5")]
[string[]]$VulnSevereties,
[ValidateSet("1","2","3","4","5")]
[string[]]$PotVulnSevereties,
[ValidateCount(1,10)]
[string[]]$QIDs,
[ValidateLength(1,100)]
[string]$VulnTitleContains,
[ValidateLength(1,100)]
[string]$VulnDetailsContains,
[ValidateLength(1,100)]
[string]$VendorRefContains,
[string]$ChangeAssignee,
[ValidateSet("OPEN","RESOLVED","IGNORED")] 
[string]$ChangeState,
[ValidateLength(1,2000)]
[string]$AddComment
)

#*=============================================
#* VARIABLE DECLARATION
#*=============================================

# Variables: Qualys URLs
$urlQualysLocation = "qualysapi.qualys.eu"
#$urlQualysLocation = "qualysapi.qualys.com"
$urlQualys = "https://$urlQualysLocation/msp"
$urlQualysTicketEdit = "$urlQualys/ticket_edit.php?"
$xmlTicketEdit = Join-path $env:temp "Edit-QualysTicket.xml"

# Set the parameters to be passed to the Ticket_edit.php function if they are specified as script parameters.
### Ticket Selection parameters ###
If ($ticketNumbers -ne $null) { $paramTicketNumbers = "&ticket_numbers="+($ticketNumbers -join ",") }
If ($sinceTicketNumber -ne "") { $paramSinceTicketNumber = "&since_ticket_number="+$sinceTicketNumber }
If ($untilticketNumber -ne "") { $paramUntilticketNumber = "&since_ticket_number="+$untilticketNumber }
If ($overdue -ne "") { $paramOverdue = "&overdue="+$overdue }
If ($invalid -ne "") { $paramInvalid = "&overdue="+$invalid }
If ($ticketAssignee -ne "") { $paramAssignee = "&ticket_assignee="+$ticketAssignee }
If ($states -ne $null) { $paramStates = "&states="+($states -join ",") }
If ($modifiedSinceDateTime -ne "") { $parammodifiedSinceDateTime = "&modified_since_datetime="+$modifiedSinceDateTime }
If ($unmodifiedSinceDateTime -ne "") { $paramUnmodifiedSinceDateTime = "&unmodified_since_datetime="+$unmodifiedSinceDateTime }
If ($ips -ne $null) { $paramIps = "&ips="+($ips -join ",") }
If ($assetGroups -ne $null) { $paramAssetGroups = "&asset_groups="+($assetGroups -join ",") }
If ($dnsContains -ne "") { $paramDnsContains = "&dns_contains="+$dnsContains }
If ($netbiosContains -ne "") { $paramNetbiosContains = "&netbios_contains="+$netbiosContains }
If ($vulnSevereties -ne $null) { $paramVulnSevereties = "&vuln_severities="+($vulnSevereties -join ",") }
If ($potVulnSevereties -ne $null) { $paramPotVulnSevereties = "&potential_vuln_severities="+($potVulnSevereties -join ",") }
If ($qids -ne $null) { $paramQids = "&qids="+($qids -join ",") }
If ($vulnTitleContains -ne "") { $paramVulnTitleContains = "&vuln_title_contains="+$vulnTitleContains }
If ($vulnDetailsContains -ne "") { $paramVulnDetailsContains = "&vuln_details_contains="+$vulnDetailsContains }
If ($vendorRefContains -ne "") { $paramVendorRefContains = "&vendor_ref_contains="+$vendorRefContains }
### Ticket Action parameters ###
If ($changeAssignee -ne "") { $paramChangeAssignee = "&change_assignee="+$changeAssignee }
If ($changeState -ne "") { $paramChangeState = "&change_state="+$changeState }
If ($addComment -ne "") { $paramAddComment = "&add_comment="+$addComment }

$urlQualysTicketEditFinal = $urlQualysTicketEdit+$paramTicketNumbers+$paramSinceTicketNumber+$paramUntilticketNumber+$paramOverdue+$paramInvalid+$parammodifiedSinceDateTime+$paramUnmodifiedSinceDateTime+$paramIps+$paramTicketAssignee+$paramStates+$paramAssetGroups+$paramDnsContains+$paramNetbiosContains+$paramVulnSevereties+$paramPotVulnSevereties+$paramQids+$paramVulnTitleContains+$paramVulnDetailsContains+$paramVendorRefContains+$paramChangeAssignee+$paramChangeState+$paramAddComment

#*=============================================
#* END VARIABLE DECLARATION
#*=============================================

#*=============================================
#* FUNCTION LISTINGS
#*=============================================

Function Exit-Script {
Write-Log -Message "Exiting Script."
Exit
}

# Function to write output to the console and to log file
Function Write-Log {
	PARAM(
	[String]$Message,
	[String]$Path = "$env:temp\$(Split-Path $MyInvocation.ScriptName -Leaf).log"
	)
	
	Write-Host $message 
	$message | Out-File -FilePath $Path -Append -NoClobber
	} #end function

# Function to authenticate to Qualys, POST a URL request and retreive the response.
Function Connect-QualysAPI {
	# Parameters required: Qualys URL string and output XML file
	param($url,$xml)
	Write-Log -Message "URL request: $url"
	Write-Log -Message "Sending Request to Qualys API.."
	# Call Web Service and ignore erros with invalid, untrusted or expired SSL CertIficates (we know we are dealing with Qualys) - this only affects the current PowerShell runspace
	[System.Net.ServicePointManager]::ServerCertIficateValidationCallback = {$true}
	# Set up the webclient
	$webClient = new-object System.Net.WebClient
	$webClient.Credentials = new-object System.Net.NetworkCredential($username,$password)

	# Trap exceptions when calling DownloadString and call the Exit-Script function
	trap [System.Net.WebException] { 
		$exceptionMessage = $_.Exception.Message
		$exceptionName = $_.Exception.GetType().FullName
		Write-Log -Message "$exceptionName: $exceptionMessage"
		Exit-Script 
		}
	
	# Send request URL to Qualys, then wait until the request has been processed and downloaded fully.
	$xml = $webClient.DownloadString($url) | Out-File -FilePath $xml
	
} # End Function Connect-QualysAPI

# Function to parse the XML response response from Edit-QualysTicket
Function Get-QualysResponse {
	Param ($xmlResponse)
	Write-Log -Message "Checking response from Qualys..."
	# Read the Qualys XML response
	[xml]$xml = (Get-Content $xmlResponse)
		# If the request to edit the ticket resulted in a change, parse the results.
		If ($xml.Ticket_Edit_Output) {
			If ($xml.Ticket_Edit_Output[1].Changes)	{
				Write-Log -Message "Parsing response from Qualys..."
				$ticketNetbios = $xml.Ticket_Edit_Output[1].Header.Where.Netbios_Contains.InnerText
				$ticketChangesCount = $xml.Ticket_Edit_Output[1].Changes.getAttribute("count")
				$ticketChanges = $xml.Ticket_Edit_Output[1].Changes.TICKET_NUMBER_LIST
				$ticketSkippedCount = $xml.Ticket_Edit_Output[1].Skipped.getAttribute("count")
				$ticketSkipped = $xml.Ticket_Edit_Output[1].Skipped.TICKET_LIST.TICKET
					
				# If there was a change to one or more tickets, get the details
				If ($ticketChangesCount -gt 0) {
					$ticketChangesArray = @()
					Foreach ($ticketNumber in $ticketChanges.TICKET_NUMBER.InnerText) {			
						$ticketChangesNumber = $ticketChanges.TICKET_NUMBER
						$ticketChangesArray += $ticketChangesNumber
					}
					
					# Format the ticket numbers changed in to comma separated string (for printing on one line of log file).	
					$ticketChangesString = [string]::join(",", $ticketChangesArray)
					Write-Log -Message "$ticketChangesCount tickets edited."
					Write-Log -Message "Ticket Numbers changed: $ticketChangesString"										
				}
					
				# If editing one or more tickets was skipped, get the details and reason why.
				ElseIf ($ticketSkippedCount -gt 0) {
					$ticketSkippedArray = @()
					Write-Log -Message "$ticketNetbios - `nNumber of Tickets Skipped:$ticketCountSkipped `nTicket Numbers skipped:"
						Foreach ($ticketNumber in $ticketSkipped) {
							$ticketSkippedNumber = $ticketSkipped.Number.InnerText
							$ticketSkippedReason = $ticketSkipped.Reason.InnerText
							$ticketSkippedArray += "$ticketSkippedNumber:$ticketSkippedReason"
						}
					# Format the ticket numbers skipped along with the reason for skipping as a string.		
					$ticketSkippedString = [string]::join(",", $ticketSkippedArray)
					Write-Log -Message "The following tickets were skipped: $ticketSkippedString"
				}		
					
				# If no tickets were changed or skipped, something was wrong with the request, e.g. ticket state not Uppercase
				Else {
					Write-Log -Message "$ticketNetbios - No tickets were altered. There may not be any open tickets to edit."
				}
			}
			# If Qualys Returns an error, parse the error output
			ElseIf ($xml.Ticket_Edit_Output[1].Error) {
				Write-Log -Message "Parsing the Qualys XML error response..."
				$errorNumber = $xml.Ticket_Edit_Output[1].Error.getAttribute("number")
				$errorResponse = $xml.Ticket_Edit_Output[1].Error.InnerXml
				Write-Log -Message "Error: $errorNumber:$errorResponse"
				Exit-Script
			}	
		}
		
		# If Qualys returned a Generic Return form, call the Get-QualysGenericReturn function
		ElseIf ($xml.GENERIC_RETURN) {	
			Write-Log -Message "Parsing the Qualys XML generic response..."
			$genericApiName = $xml.GENERIC_RETURN[1].API.getAttribute("name")
			$genericapiUserName = $xml.GENERIC_RETURN[1].API.getAttribute("username")
			$genericApiTime = $xml.GENERIC_RETURN[1].API.getAttribute("at")
			$genericReturnStatus = $xml.GENERIC_RETURN[1].Return.getAttribute("status")
			$genericReturnNumber = $xml.GENERIC_RETURN[1].Return.getAttribute("number")
			$genericReturnDetails = $xml.GENERIC_RETURN[1].Return.InnerXml
			Write-Log -Message "API failure: $genericApiName `nUser: $genericapiUserName `nTime: $genericApiTime"
			Write-Log -Message "Status: $genericReturnStatus `nError Number: $genericReturnNumber `nDetails: $genericReturnDetails"

			# Call the script exit function If the return status is "failed"
			If ($genericReturnStatus -imatch "FAILED") {	
				Exit-Script
			} 
		}
		
		Else {
			Write-Log -Message "Error: Qualys request was unsuccessful. Check parameters."
			Exit-Script
		}	

} # End Function Get-QualysResponse

Function Invoke-QualysTicketEdit {

Try {
	$credential = Get-Credential
}
Catch {
	Write-Log -Message "Error: Credentials are required to authenticate to Qualys"
	Exit-Script
}
$networkCredential = $credential.GetNetworkCredential()
$username = $networkCredential.UserName
$password = $networkCredential.Password

Connect-QualysAPI $urlQualysTicketEditFinal $xmlTicketEdit

Get-QualysResponse $xmlTicketEdit

Exit-Script
}

#*=============================================
#* END FUNCTION LISTINGS
#*=============================================


#*=============================================
#* SCRIPT BODY
#*=============================================

Invoke-QualysTicketEdit

#*=============================================
#* END SCRIPT BODY
#*=============================================