Fortify API Start Scan with Default - How to send package - api

I am trying to use the API from https://api.emea.fortify.com/swagger/ui/index#/
called Start Scan with Default.
I cannot find any documentation to suggest how to set the post up.
This is what I have so far, but I get an error and of course I am not sending the files to scan either, so I know it is not right.
I have tried a Get request, which works so I know it is authenticated etc.
I just need to know are the parameters correctly formatted and how do I upload the actual files to scan.
POST /api/v3/releases/43579/static-scans/start-scan-with-defaults?releaseId=43579& fragNo=22& offset=22& isRemediationScan=false& notes=hello HTTP/1.1
Host: api.emea.fortify.com
Content-Type: application/json
Authorization: Bearer [TOKEN HERE]
User-Agent: PostmanRuntime/7.13.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 57e40c1d-c99c-40a4-a79b-06ef9a678a07,8ef4ad1e-327f-4eee-b6bb-bddb21b18d50
Host: api.emea.fortify.com
accept-encoding: gzip, deflate
content-length:
Connection: keep-alive
cache-control: no-cache
Response:
{
"errors": [
{
"errorCode": null,
"message": "Unexpected error processing request"
}
]
}
UPDATE
I have found this repo on Git written in Java, which I have tried to recreate in PowerShell with no success.
https://github.com/fod-dev/fod-uploader-java
My PowerShell:
[System.Net.WebRequest]::DefaultWebProxy = [System.Net.WebRequest]::GetSystemWebProxy()
[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$zipDetails = Get-Content C:\Users\patemanc\Desktop\types.zip -Encoding Byte
Write-Host $zipDetails.Length
$releaseId = "43576"
$url = "https://api.emea.fortify.com/api/v3/releases/$releaseId/static-scans/start-scan-with-defaults?"
$url += "releaseId=$releaseId"
$url += "&fragNo=-1"
$url += "&offset=0"
$url += "&isRemediationScan=false"
$url += "&notes=PowrShell Test"
$long_lived_access_token = "ENTER TOKEN HERE"
$headers = #{Authorization = "bearer:$long_lived_access_token"}
$response = Invoke-WebRequest -ContentType "application/octet-stream" -Uri $url -Method POST -Body $zipDetails -Headers $headers -UseBasicParsing
Write-Host "Here is the end"
Write-Host $response
Error Response:
79212
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At line:22 char:13
+ $response = Invoke-WebRequest -ContentType "application/json" -Uri $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Why postman? If you use some plugin to run it, from Jenkins for example, it works fine. I don't know how the plugins call it from the API.

Related

EDIT the Azure databrics cluster's SPARK configuration using PowerShell and REST API

I am trying to EDIT the Azure databrics cluster's SPARK configuration using PowerShell and REST API. However I am getting an error which I am unable to understand/fix. I have provided the 'required' fields as parameters, however, the error states that I haven't passed them
CODE:
$DBAPIRootUrl = "dec" # example: https://uksouth.azuredatabricks.net
$DBAPIKey = "abc" # Example dapi601e67891a9d1f7886e40916479aaa
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
$ClustersAPIListUrl = $DBAPIRootUrl.Trim('/') + "/api/2.0/clusters/list"
$ClustersAPIEditUrl = $DBAPIRootUrl.Trim('/') + "/api/2.0/clusters/edit"
$headers = #{
Authorization = "Bearer $DBAPIKey"
"Content-Type" = "application/json"
}
$response = Invoke-WebRequest -Uri $ClustersAPIListUrl -Method GET -Headers $headers #-Body $parameters
$json_response = ($response.Content | ConvertFrom-Json)
$jsonDoc = [pscustomobject]#{
cluster_id = $json_response.clusters.cluster_id
spark_version = $json_response.clusters.spark_version
node_type_id = $json_response.clusters.node_type_id
spark_conf = "
javax.jdo.option.ConnectionPassword
datanucleus.fixedDatastore false
javax.jdo.option.ConnectionURL jdbc:sqlserver://metadatasrvr.database.windows.net:1433;database=emptydb
datanucleus.schema.autoCreateAll true
spark.hadoop.hive.metastore.schema.verification false
datanucleus.autoCreateSchema true
spark.sql.hive.metastore.jars maven
javax.jdo.option.ConnectionDriverName com.microsoft.sqlserver.jdbc.SQLServerDriver
spark.sql.hive.metastore.version 1.2.0
javax.jdo.option.ConnectionUserName"
}
$jsonDoc | ConvertTo-Json
#$parameters | ConvertTo-Json
$response = Invoke-WebRequest -Uri $ClustersAPIEditUrl -Method POST -Headers $headers -Body $jsonDoc
ERROR:
Invoke-WebRequest : {"error_code":"INVALID_PARAMETER_VALUE","message":"Missing required fields: cluster_id, size"}
At line:21 char:13
+ $response = Invoke-WebRequest -Uri $ClustersAPIEditUrl -Method POST - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
The error message clearly explains ""error_code":"INVALID_PARAMETER_VALUE","message":"Missing required fields: cluster_id, size"}".
Note: While editing Databricks cluster, make sure to pass the "cluster_id" and "node_type_id" as a mandatory expecting fields.
To Edit the configuration of a cluster to match the provided attributes and size.
An example request:
{
"cluster_id": "1202-211320-brick1",
"num_workers": 10,
"spark_version": "5.3.x-scala2.11",
"node_type_id": "Standard_D3_v2"
}
Reference: Databricks - REST API EDIT clusters
Hope this helps.

Loop CSV and post data through REST API

I have simple CSV file like:
device,template
dlinkrouter,DLink DGS Switch
cisco, DLink DGS Switch
And simple script like below:
$csv = Import-Csv "C:\Users\m.zurek\Desktop\devices.csv"
$csv.device | ForEach-Object {
Write-Host $_
$action = "http://localhost:8090/api/json/ncmsettings/addDevice"
$hash = #{}
$hash.Add("apiKey", "cb464d185c0cdf785295a6a0a1d227a2")
$hash.Add("IPADDRESS", $($_))
$hash.Add("DEVICE_BEHAVIOUR", "DLink DGS Switch")
$adddev = Invoke-WebRequest -Uri $action -UseBasicParsing -Body $hash -Method Post
return $adddev
}
Problem is that the script adds only the first device from the CSV file. On the rest I have response from API about error. Not sure if it's a problem with API or with my script.
StatusCode : 200
StatusDescription :
Content : {"Message":"Error in adding device. Zip the logs folder and send it to support.","isSuccess":false,"statusMsg":"Failure","bulkResourceIds":[]}
RawContent : HTTP/1.1 200
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST
Access-Control-Max-Age: 5000
Transfer-Encoding: chunked
Vary: Accept-Encoding
Content-Type: application/json;c...
Forms :
Headers : {[Access-Control-Allow-Origin, *], [Access-Control-Allow-Methods, GET,POST], [Access-Control-Max-Age, 5000], [Transfer-Encoding, chunked]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml :
RawContentLength : 144
Write-Host works fine and write name of all devices from CSV.

Invoking Rest API using Powershell - CosmosDb

I was trying to deploy cosmos database using Cosmos DB REST Api. I'm using a function to build the authorisation header and I got the script from https://gallery.technet.microsoft.com/scriptcenter/How-to-query-Azure-Cosmos-0a9aa517 link. It works perfectly fine for GET & POST however when I tried to execute a PUT command I'm always getting below error.
Invoke-RestMethod : The remote server returned an error: (401)
Unauthorized.
Im trying to update the offer for Cosmos collection but it always ends with the error and I couldn't understand whats the reason. I also checked my headers and authorisation with Microsoft documentation and looks fine to me. Refer https://learn.microsoft.com/en-us/rest/api/documentdb/replace-an-offer for Uri and headers required. My request and response are below
Request
PUT https: //mycosmosdb.documents.azure.com:443/offers/mycollection HTTP/1.1
authorization: type % 3dmaster % 26ver % 3d1.0 % 26sig % 3dIgWkszNS % 2b94fUEyrG8frByB2PWSc1ZEszc06GUeuW7s % 3d
x - ms - version: 2017 - 02 - 22
x - ms - date: Wed, 02 Aug 2017 08: 40: 37 GMT
User - Agent: Mozilla / 5.0(Windows NT; Windows NT 10.0; en - US)WindowsPowerShell / 5.1.15063.483
Content - Type: application / json
Host: mycosmosdb.documents.azure.com
Content - Length: 269
{
"offerVersion": "V2",
"offerType": "Invalid",
"content": {
"offerThroughput": 500,
"offerIsRUPerMinuteThroughputEnabled": false
},
"resource": "dbs/xterf==/colls/STuexopre=/",
"offerResourceId": "STuexopre=",
"id": "xiZw",
"_rid": "xiZw"
}
Response
HTTP / 1.1 401 Unauthorized
Transfer - Encoding: chunked
Content - Type: application / json
Content - Location: https: //mycosmosdb.documents.azure.com/offers/variantstockquantity
Server: Microsoft - HTTPAPI / 2.0
x - ms - activity - id: 6f7be3c8 - cfa2 - 4d5e - ad69 - fb14ef218980
Strict - Transport - Security: max - age = 31536000
x - ms - gatewayversion: version = 1.14.57.1
Date: Wed, 02 Aug 2017 08: 40: 35 GMT
163{
"code": "Unauthorized",
"message": "The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'put\noffers\mycollection\nwed, 02 aug 2017 08:40:37 gmt\n\n'\r\nActivityId: 6f7be3c8-cfa2-4d5e-ad69-fb14ef218980"
}
0
My Powershell Code
Function Generate-MasterKeyAuthorizationSignature
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String]$verb,
[Parameter(Mandatory=$true)][String]$resourceLink,
[Parameter(Mandatory=$true)][String]$resourceType,
[Parameter(Mandatory=$true)][String]$dateTime,
[Parameter(Mandatory=$true)][String]$key,
[Parameter(Mandatory=$true)][String]$keyType,
[Parameter(Mandatory=$true)][String]$tokenVersion
)
$hmacSha256 = New-Object System.Security.Cryptography.HMACSHA256
$hmacSha256.Key = [System.Convert]::FromBase64String($key)
If ($resourceLink -eq $resourceType) {
$resourceLink = ""
}
$payload = "$($verb.ToLowerInvariant())`n$($resourceType.ToLowerInvariant())`n$resourceLink`n$($dateTime.ToLowerInvariant())`n`n"
$hashPayload = $hmacSha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($payload))
$signature = [System.Convert]::ToBase64String($hashPayload);
[System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$signature")
}
Function Modify-Offer
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String]$DocumentDBApi,
[Parameter(Mandatory=$true)][String]$EndPoint,
[Parameter(Mandatory=$true)][String]$MasterKey,
[Parameter(Mandatory=$true)][String]$CollectionName
)
$Verb = "PUT"
$ResourceType = "offers";
$ResourceLink = "offers"
$body = '{
"offerVersion": "V2",
"offerType": "Invalid",
"content": {
"offerThroughput": 500,
"offerIsRUPerMinuteThroughputEnabled": false
},
"resource": "dbs/xterf==/colls/STuexopre=/",
"offerResourceId": "STuexopre=",
"id": "xiZw",
"_rid": "xiZw"
}'
$dateTime = [DateTime]::UtcNow.ToString("r")
$authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb -resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
$header = #{authorization=$authHeader;"x-ms-version"=$DocumentDBApi;"x-ms-date"=$dateTime}
$contentType= "application/json"
$queryUri = "$EndPoint$ResourceLink/$CollectionName"
$result = Invoke-RestMethod -Method $Verb -ContentType $contentType -Uri $queryUri -Headers $header -Body $body
$result | ConvertTo-Json -Depth 10
}
Modify-Offer -EndPoint $CosmosDBEndPoint -MasterKey $MasterKey -DocumentDBApi $DocumentDBApiVersion -CollectionName $ColName
Can someone throw me some help as why my PUT requests are failed with authorisation error, what I'm missing and how can I correct it.
Response message clearly states used payload for verification. Tracing '$payLoad' in Generate-MasterKeyAuthorizationSignature will quickly revel the issue.
You need to address at-least below two issues for this to work
RepalceOffer documentation states RID of the offer, instead you are
passing the collection name.
ResourceLin hardcoded: $ResourceLink
= "offers" in Modify-Offer where as it needs to point to the RID of the resource.
Here is slightly modified code which should do job
Function Generate-MasterKeyAuthorizationSignature
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String]$verb,
[Parameter(Mandatory=$true)][String]$resourceLink,
[Parameter(Mandatory=$true)][String]$resourceType,
[Parameter(Mandatory=$true)][String]$dateTime,
[Parameter(Mandatory=$true)][String]$key,
[Parameter(Mandatory=$true)][String]$keyType,
[Parameter(Mandatory=$true)][String]$tokenVersion
)
$hmacSha256 = New-Object System.Security.Cryptography.HMACSHA256
$hmacSha256.Key = [System.Convert]::FromBase64String($key)
If ($resourceLink -eq $resourceType) {
$resourceLink = ""
}
$payLoad = "$($verb.ToLowerInvariant())`n$($resourceType.ToLowerInvariant())`n$resourceLink`n$($dateTime.ToLowerInvariant())`n`n"
$hashPayLoad = $hmacSha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($payLoad))
$signature = [System.Convert]::ToBase64String($hashPayLoad);
Write-Host $payLoad
[System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$signature")
}
Function Modify-Offer
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String]$DocumentDBApi,
[Parameter(Mandatory=$true)][String]$EndPoint,
[Parameter(Mandatory=$true)][String]$MasterKey,
[Parameter(Mandatory=$true)][String]$OfferRID
)
$Verb = "PUT"
$ResourceType = "offers";
$body = '{
"offerVersion": "V2",
"offerType": "Invalid",
"content": {
"offerThroughput": 600,
"offerIsRUPerMinuteThroughputEnabled": false
},
"resource": "dbs/xterf==/colls/STuexopre=/",
"offerResourceId": "STuexopre=",
"id": "xiZw",
"_rid": "xiZw"
}'
$dateTime = [DateTime]::UtcNow.ToString("r")
$authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb -resourceLink $OfferRID -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
$header = #{authorization=$authHeader;"x-ms-version"=$DocumentDBApi;"x-ms-date"=$dateTime}
$contentType= "application/json"
$queryUri = "$EndPoint$ResourceType/$OfferRID"
$result = Invoke-RestMethod -Method $Verb -ContentType $contentType -Uri $queryUri -Headers $header -Body $body
$result | ConvertTo-Json -Depth 10
}
Modify-Offer -EndPoint $CosmosDBEndPoint -MasterKey $MasterKey -DocumentDBApi $DocumentDBApiVersion -OfferRID $ColName
Other alternative recommended approach if possible is to consume client SDK in Powershell. Here is a sample code which updates first offer of the account.
Add-Type -Path "...\Microsoft.Azure.Documents.Client.dll"
$client=New-Object Microsoft.Azure.Documents.Client.DocumentClient($CosmosDBEndPoint, $MasterKey)
$offersEnum=$client.ReadOffersFeedAsync().Result.GetEnumerator();
if ($offersEnum.MoveNext())
{
$targetOffer=$offersEnum.Current
$offerUpdated=New-Object Microsoft.Azure.Documents.OfferV2($targetOffer, 600, $FALSE)
$client.ReplaceOfferAsync($offerUpdated).Result
}

Need to get required http post

I am following Huddle Api instructions to get the Access Token. I am using powershell to post the method which is as follows:
POST /token HTTP/1.1
Host: login.huddle.net
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&client_id=s6BhdRkqt&redirect_uri=MyAppServer.com/receiveAuthCode&code=i1WsRn1uB1
Powershell Command which I am using is:
$body = { '#grant_type' = 'authorization_code'; client_id = 'xxxxx';
redirect_uri = 'myAppServer.com'; code = '123abcdef' }
Invoke-WebRequest -Uri "login.huddle.com" -ContentType "application/x-www-form-urlencoded" -Method Post
This works and I get the response of "200 OK" and also shows the activation of Access Token. How would I retrieve the Access Token number. For example, I need the output as they mentioned in instruction which is:
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{
"access_token":"S1AV32hkKG",
"expires_in":300,
"refresh_token":"8xLOxBtZp8"
}
I think it has something to do ContentType. So I did try, "application/Json" but that was not it. Any suggestions?
You're using the wrong cmdlet. Since you mentiond getting back values for StatusCode, Content, RawContent, etc, that tells us that you're using Invoke-WebRequest. This cmdlets awesome...but not for working with APIs, which are commonly REST formatted and use JSON. IWR can handle the request but you have to dig into the $Response.Content and convert from JSON.
Instead of Invoke-WebRequest, try using Invoke-RestMethod. It's likely that you are getting the AccessCode returned, but as a JSON formatted property. Invoke-RestMethod will natively parse and convert JSON into PowerShell objects. You can just sub it in for Invoke-WebRequest and it should just work.
Invoke-RestMethod -Uri "login.huddle.com" -ContentType "application/x-www-form-urlencoded" -Method Post -body $body
If you use Invoke-RestMethod you can set the response when making the call
$response = Invoke-RestMethod -Uri "login.huddle.com" -ContentType "application/x-www-form-urlencoded" -Method Post"
then $response.access_token or $response.expires_in or $response.refresh_token

Forward an email using rest api and powershell (Azure Automation)

I'm trying to forward emails with attachments to a specific email address via Azure Automation (with message ID). I get the error message at the bottom after I run the code. I'm not really sure am I on the right track here (both with email sending and sending of attachments). Perhaps there's a better way to do this.
Could anyone lend a hand?
$credObject = Get-AutomationPSCredential -Name "Myscreds"
$url = "https://outlook.office365.com/api/v1.0/me/AAMkADA1MTAAAH5JaL/forward"
$body = "{
""Message"":{
""Subject"": ""This is a test"",
""Importance"": ""Low"",
""Body"": {
""ContentType"": ""HTML"",
""Content"": ""This is great!""
},
""ToRecipients"": [
{
""EmailAddress"":{
""Address"": ""myname#test.com""
}
}
]
}}"
Invoke-RestMethod -Uri $url -Method Post -Credential $credobject -ContentType "application/json" -Body $Body
I get the following error message:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:24 char:1
+ Invoke-RestMethod -Uri $url -Method Post -Credential $credobject -Con ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod],
WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Thanks.
Per the Microsoft documentation, you need to modify your request.
https://outlook.office.com/api/v1.0/me/messages/AAMkAGE0Mz8DmAAA=/forward
It looks like you forgot to include /messages/ in your request.
However, it looks like you want to change the body of a message when you forward it. This is more complicated, and you need to follow this workflow instead:
Alternatively, if you need to modify any updateable properties in the message to be forwarded, you can first create a draft forward message, update the message properties, and then send the reply.
Here's how that would look.
First, make a Draft of the message you want to forward
$request = "https://outlook.office365.com/api/v1.0/me/messages/AAMkADA1MTAAAH5JaL/createforward"
$body = {
"ToRecipients":[
{
""EmailAddress"":{
""Address"": ""myname#test.com""
}
}
],
"Comment": "Your sample message here"
}
The response back is going to include some properties, including the ID of the new message. You then use that to edit the Draft (to change the subject, etc) and then send it off. Let me know if you need any further help.
Ok. I had the incorrect message ID, that was my main problem. It's all resolved. I can forward messages with attachments using the message ID. Thanks again.
$credObject = Get-AutomationPSCredential -Name "mycreds"
$url = "https://outlook.office365.com/api/v1.0/Users('it-test#test.com')/messages/ASHJFKHFUISDFWIzLT=/forward"
$body = "{
""Comment"": ""A mail with some attachments (hopefully)"",
""ToRecipients"": [
{
""EmailAddress"":{
""Address"": ""myname#test.com""
}
}
]
}"
Invoke-RestMethod -Uri $url -Method Post -Credential $credobject -ContentType "application/json" -body $body