Skip to main content

Script - Arbitrary Backends

The script backend type is merely a script the agent can run, that takes a fixed set of arguments.

In Bash parlance, the syntax is always like this: 

# Check arguments
if [ "$#" -lt 3 ]; then
    echo "Usage: $0 <ACTION> <IP_ADDRESS> <ACL_NAME>"
    exit 1
fi

So, the agent expects to run the script with 3 arguments:

  •  ACTION - eg ADD or REVOKE,
  • IP _ADDRESS - the IP that the User has been detected coming from by the server (passed on from the server)
  • ACL_NAME - the name of the ACL for validation, or for example the AWS security_group_id

Your script may or may not implement the Name function, however it has to implement the ACTION and IP_ADDRESS arguments, ideally idempotently.

Here is a copy of the example ipsetter.sh script included with the knocknoc-agent:

#!/bin/bash
# Wrapper script to allow safe parsing of an ipset command line from sudo
# sudo is run in this scrip itself, so you need to enable the ipset command in sudoers
# like so:
# make a file in /etc/sudoers.d/knocknoc-agent with this contents:
# knocknoc-agent ALL=(ALL:ALL) NOPASSWD: /usr/sbin/ipset *
# 
# This will allow this script to run the ipset command as root.


set -e -o pipefail

# Validate IP address
function validate_ip() {
    local ip=$1
    if [[ $ip =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]]; then
        return 0
    else
        echo "Invalid IP address"
        exit 1
    fi
}

# Validate setname
function validate_setname() {
    local setname=$1
    if [[ $setname =~ ^[A-Za-z0-9_]+$ ]]; then
        return 0
    else
        echo "Invalid setname"
        exit 1
    fi
}

# Validate operation
function validate_op() {
    local op=$1
    if [[ $op =~ ^(add|del|flush)$ ]]; then
        return 0
    else
        echo "Invalid operation"
        exit 1
    fi
}

# Validate and assign operation
validate_op "$1"
op="$1"

# Validate and assign setname
validate_setname "$2"
setname="$2"

# Execute ipset command
if [[ "$op" = "flush" ]]; then
    exec sudo /usr/sbin/ipset "$op" "$setname"
else
    # Validate and assign IP address
    validate_ip "$3"
    ip="$3"
    exec sudo /usr/sbin/ipset "$op" "$setname" "$ip"
fi

There are many ways admins are able to customise this setup to suit their needs and security profiles.