Firewall

Enable or disable a firewall rule

Since 7.1.0
PUT/servers/{serverId}/firewall/{interfaceRef}/rules/{ruleId}

Enable or disable a rule. apply: true pushes the interface's rules to the running server; the status then follows the push.

Request

Authorization
Provide your bearer token in the Authorization header when making requests to protected resources.
Example: Authorization: Bearer ********************
Path Params#
serverIdinteger#required

A valid server ID as shown in VirtFusion.

Example: 1
interfaceRefstring#required

Which interface: primary, secondary, or the interface's tag, the ten-digit identifier shown as tag in GET /servers/{serverId}/interfaces (it is also the interface's device name on the hypervisor).

Example: primary
ruleIdinteger#required

The rule's id from the list.

Example: 42
Body Paramsapplication/json#

The flag, plus apply.

object
enabledboolean#required
applyboolean#
Example
{
    "enabled": false
}

Request Code Samples

curl --location --request PUT 'https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42' \
--header 'Authorization: Bearer <token>' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data-raw '{
    "enabled": false
}'
wget --quiet --output-document=- \
  --method=PUT \
  --header='Authorization: Bearer <token>' \
  --header='Accept: application/json' \
  --header='Content-Type: application/json' \
  --body-data='{
    "enabled": false
}' \
  'https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42'
http PUT 'https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42' \
  'Authorization: Bearer <token>' \
  'Accept: application/json' \
  'Content-Type: application/json' <<< '{
    "enabled": false
}'
const response = await fetch("https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42", {
    method: "PUT",
    headers: {
        "Authorization": "Bearer <token>",
        "Accept": "application/json",
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        "enabled": false
    }),
});

const data = await response.json();
console.log(response.status, data);
import axios from "axios";

const response = await axios({
    method: "put",
    url: "https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42",
    headers: {
        "Authorization": "Bearer <token>",
        "Accept": "application/json",
        "Content-Type": "application/json",
    },
    data: {
        "enabled": false
    },
});

console.log(response.status, response.data);
const https = require("https");

const payload = JSON.stringify({
    "enabled": false
});

const req = https.request({
    hostname: "cp.domain.com",
    path: "/api/v1/servers/1/firewall/primary/rules/42",
    method: "PUT",
    headers: {
        "Authorization": "Bearer <token>",
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(payload),
    },
}, (res) => {
    let data = "";
    res.on("data", (chunk) => (data += chunk));
    res.on("end", () => console.log(res.statusCode, JSON.parse(data)));
});

req.on("error", (err) => console.error(err));
req.write(payload);
req.end();
import requests

url = "https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42"
headers = {
    "Authorization": "Bearer <token>",
    "Accept": "application/json",
    "Content-Type": "application/json",
}
payload = {
    "enabled": False,
}

response = requests.request("PUT", url, headers=headers, json=payload)

print(response.status_code)
print(response.json())
import http.client
import json

conn = http.client.HTTPSConnection("cp.domain.com")
headers = {
    "Authorization": "Bearer <token>",
    "Accept": "application/json",
    "Content-Type": "application/json",
}
payload = json.dumps({
    "enabled": False,
})

conn.request("PUT", "/api/v1/servers/1/firewall/primary/rules/42", payload, headers)
response = conn.getresponse()

print(response.status)
print(json.loads(response.read()))
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'PUT',
    CURLOPT_POSTFIELDS => json_encode([
        'enabled' => false,
    ]),
    CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer <token>',
        'Accept: application/json',
        'Content-Type: application/json'
    ),
));

$response = curl_exec($curl);
curl_close($curl);

echo $response;
<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();

$response = $client->request('PUT', 'https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42', [
    'headers' => [
        'Authorization' => 'Bearer <token>',
        'Accept' => 'application/json',
    ],
    'json' => [
        'enabled' => false,
    ],
]);

echo $response->getStatusCode() . "\n";
echo $response->getBody();
package main

import (
    "fmt"
    "io"
    "net/http"
    "strings"
)

func main() {
    url := "https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42"
    payload := strings.NewReader(`{
    "enabled": false
}`)
    req, _ := http.NewRequest("PUT", url, payload)
    req.Header.Add("Authorization", "Bearer <token>")
    req.Header.Add("Accept", "application/json")
    req.Header.Add("Content-Type", "application/json")

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()

    body, _ := io.ReadAll(res.Body)
    fmt.Println(res.StatusCode, string(body))
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42"))
            .header("Authorization", "Bearer <token>")
            .header("Accept", "application/json")
            .header("Content-Type", "application/json")
            .method("PUT", HttpRequest.BodyPublishers.ofString("{\"enabled\":false}"))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode());
        System.out.println(response.body());
    }
}
import okhttp3.*;

public class Main {
    public static void main(String[] args) throws Exception {
        OkHttpClient client = new OkHttpClient();

        MediaType json = MediaType.get("application/json");
        RequestBody body = RequestBody.create("{\"enabled\":false}", json);

        Request request = new Request.Builder()
            .url("https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42")
            .method("PUT", body)
            .addHeader("Authorization", "Bearer <token>")
            .addHeader("Accept", "application/json")
            .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.code());
            System.out.println(response.body().string());
        }
    }
}
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

var client = new HttpClient();
var request = new HttpRequestMessage(new HttpMethod("PUT"), "https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "<token>");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Content = new StringContent("{\"enabled\":false}", Encoding.UTF8, "application/json");

var response = await client.SendAsync(request);
Console.WriteLine((int)response.StatusCode);
Console.WriteLine(await response.Content.ReadAsStringAsync());
require "net/http"
require "json"

uri = URI("https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42")
request = Net::HTTP::Put.new(uri)
request["Authorization"] = "Bearer <token>"
request["Accept"] = "application/json"
request["Content-Type"] = "application/json"
request.body = "{\"enabled\":false}"

response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
  http.request(request)
end

puts response.code
puts JSON.pretty_generate(JSON.parse(response.body))
import Foundation

var request = URLRequest(url: URL(string: "https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42")!)
request.httpMethod = "PUT"
request.setValue("Bearer <token>", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = "{\"enabled\":false}".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else { print(error ?? "request failed"); return }
    print((response as! HTTPURLResponse).statusCode)
    print(String(data: data, encoding: .utf8) ?? "")
}
task.resume()
// Cargo.toml: reqwest = { version = "0.12", features = ["blocking", "json"] }, serde_json = "1"
use reqwest::blocking::Client;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    let response = client
        .request(reqwest::Method::PUT, "https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42")
        .bearer_auth("<token>")
        .header("Accept", "application/json")
        .header("Content-Type", "application/json")
        .body(r#"{
    "enabled": false
}"#)
        .send()?;

    println!("{}", response.status());
    let json: serde_json::Value = response.json()?;
    println!("{}", serde_json::to_string_pretty(&json)?);
    Ok(())
}
// Cargo.toml: reqwest = { version = "0.12", features = ["json"] }, tokio = { version = "1", features = ["full"] }, serde_json = "1"
use reqwest::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    let response = client
        .request(reqwest::Method::PUT, "https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42")
        .bearer_auth("<token>")
        .header("Accept", "application/json")
        .header("Content-Type", "application/json")
        .body(r#"{
    "enabled": false
}"#)
        .send()
        .await?;

    println!("{}", response.status());
    let json: serde_json::Value = response.json().await?;
    println!("{}", serde_json::to_string_pretty(&json)?);
    Ok(())
}
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody

fun main() {
    val client = OkHttpClient()
    val body = """{
    "enabled": false
}""".toRequestBody("application/json".toMediaType())
    val request = Request.Builder()
        .url("https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42")
        .method("PUT", body)
        .addHeader("Authorization", "Bearer <token>")
        .addHeader("Accept", "application/json")
        .build()

    client.newCall(request).execute().use { response ->
        println(response.code)
        println(response.body?.string())
    }
}
// pubspec.yaml: http: ^1.2.0
import 'dart:convert';
import 'package:http/http.dart' as http;

Future<void> main() async {
  final request = http.Request('PUT', Uri.parse('https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42'));
  request.headers['Authorization'] = 'Bearer <token>';
  request.headers['Accept'] = 'application/json';
  request.headers['Content-Type'] = 'application/json';
  request.body = r'''{
    "enabled": false
}''';

  final response = await http.Response.fromStream(await request.send());
  print(response.statusCode);
  print(const JsonEncoder.withIndent('  ').convert(jsonDecode(response.body)));
}
#include <stdio.h>
#include <curl/curl.h>

int main(void) {
    CURL *curl = curl_easy_init();
    if (!curl) return 1;

    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Authorization: Bearer <token>");
    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");

    curl_easy_setopt(curl, CURLOPT_URL, "https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"enabled\":false}");

    CURLcode result = curl_easy_perform(curl);
    if (result != CURLE_OK) fprintf(stderr, "%s\n", curl_easy_strerror(result));

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    return result == CURLE_OK ? 0 : 1;
}
$headers = @{
    Authorization = "Bearer <token>"
    Accept        = "application/json"
}

$body = @'
{
    "enabled": false
}
'@

$response = Invoke-RestMethod -Uri "https://cp.domain.com/api/v1/servers/1/firewall/primary/rules/42" -Method PUT -Headers $headers -ContentType "application/json" -Body $body
$response | ConvertTo-Json -Depth 10
PUT /api/v1/servers/1/firewall/primary/rules/42 HTTP/1.1
Host: cp.domain.com
Authorization: Bearer <token>
Accept: application/json
Content-Type: application/json
Content-Length: 24

{
    "enabled": false
}

Responses

200

The rule as it now stands.

#
application/json
object

A firewall rule, on a server interface or in a ruleset. The same object is accepted by the add endpoint (without id), so a GET round-trips into a POST.

FirewallRule fields
idinteger#
protocolstring#
Allowed values:tcpudpicmpallsctp
directionstring#

Which way the traffic is heading from the server's point of view.

Allowed values:bothinout
actionstring#
Allowed values:allowdeny
ipTypeinteger#
Allowed values:46
priorityinteger#

Higher is evaluated first.

Range: 500 to 1000
sourcePortstring#nullable

A port or a range start-end; null for any. Always null for ICMP and all.

destinationPortstring#nullable
sourceAddressstring#nullable

address/cidr; null for any. IPv6 is returned uncompressed.

destinationAddressstring#nullable
enabledboolean#
appliedboolean#nullable

Only when apply was sent: true applied, false the hypervisor did not apply it, null the outcome is unknown (timeout or lost answer). null when apply was not sent. The saved change stands whatever the value.

errorsarray[string]#

Present when apply was sent and did not succeed.

Example
{
    "data": {
        "id": 42,
        "protocol": "tcp",
        "direction": "in",
        "action": "allow",
        "ipType": 4,
        "priority": 500,
        "sourcePort": null,
        "destinationPort": "22",
        "sourceAddress": "203.0.113.0/24",
        "destinationAddress": null,
        "enabled": false
    },
    "applied": null
}
401

The bearer token is missing, invalid, or expired. The response has no body.

#
No response body.
404

The server, the interface or the rule was not found.

#
application/json
msgstring#
Example
{
    "msg": "rule not found"
}
422

enabled is missing, not a boolean, or not the only field.

#
application/json
errorsobject#
Example
{
    "errors": {
        "enabled": [
            "must be true or false, and the only field"
        ]
    }
}
429

Too many requests. Either the token's requests per minute are used up (see the `X-RateL…

#
application/json

Too many requests. Either the token's requests per minute are used up (see the X-RateLimit-* headers) or the calling address has failed authentication 10 times in a minute (the body then includes retry_after_seconds). Retry-After gives the seconds to wait.

object
errorsarray[string]#
retry_after_secondsinteger#

Seconds to wait before retrying. Present on the failed-authentication limit only.

Response headers
Retry-Afterinteger

Seconds to wait before retrying.

X-RateLimit-Limitinteger

The token's requests per minute (token limit only).

X-RateLimit-Remaininginteger

Requests left in the current minute (token limit only).

X-RateLimit-Resetinteger

Unix timestamp at which the minute resets (token limit only).

Examples
{
    "errors": [
        "Too Many Requests"
    ]
}
{
    "errors": [
        "Too many authentication attempts. Try again later."
    ],
    "retry_after_seconds": 42
}