Balanced

Brain dump for at least semi-good ideas

Fortigate API – FortiOS 6.2

Recently I changed my firewall from Sophos UTM to a Fortigate. Since I have a decent lab setup at home with a bunch of services I decided to try out the Fortigate API. However, to my surprise there was no API documentation openly available online. To get hold of it one had to be a part of the Fortinet Developer Network which requires endorsement from two Fortinet employees. Personally I’m not a bit fan of keeping these things behind closed doors. I think it benefits neither the company, nor the customer.

So in case someone else is in the same situation that I was I thought I’d write a short intro on how to use the API using an admin account using Powershell.

Authentication

First step is to do send a post against /logincheck using form data:

# Authentication against the box
$PostParameters = @{
    "username" = $FortigateSettings.user;
    "secretkey" = $FortigateSettings.password;
}

$Result = Invoke-WebRequest -Method POST "https://10.1.1.1/logincheck" -Body $PostParameters -SessionVariable FortigateSession

The code above also saves the cookies from the response into a session variable called FortigateSession. From this variable we will also extract the CSRFTOKEN cookie value which is required when one wants to change things on the device.

$CSRFTOKEN = ($FortigateSession.Cookies.GetCookies("https://10.1.1.1") | Where-Object { $_.name -eq "ccsrftoken" }).value.replace("`"", "")

Now we’re set to run commands against the Fortigate API by using the session variable.

Examples

# Get the DHCP configuration
Invoke-WebRequest "https://10.1.1.1/api/v2/cmdb/system.dhcp/server/1" -WebSession $FortigateSession

# Get a list of the DNS databases
Invoke-WebRequest "https://10.1.1.1/api/v2/cmdb/system/dns-database/" -WebSession $FortigateSession -Method "GET"

# Get a list of the address objects
Invoke-WebRequest "https://10.1.1.1/api/v2/cmdb/firewall/address" -WebSession $FortigateSession

# Add an address object
$SHost = @{
    "name" = "CloudFlare-1";
    "subnet" = "1.1.1.1/32";
} | ConvertTo-Json -Compress

Invoke-WebRequest "https://10.1.1.1/api/v2/cmdb/firewall/address" -Headers @{"Content-Type" = "application/json"; "X-CSRFTOKEN" = $CSRFTOKEN} -WebSession $FortigateSession -Method "POST" -Body $SHost -ErrorAction SilentlyContinue

Please note that while these examples covers authentication using a normal admin account the Fortigate devices also has support for dedicated REST accounts using tokens. For frequent/production integrations you’d want to look there instead.

The script I used to migrate from Sophos to Fortigate is available here.

Previous

BigIp Report – 2019 Survey

Next

Writing a custom integration for the Google assistant

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Powered by WordPress & Theme by Anders Norén