Fortinet black logo

Handbook

Predefined Commands

Predefined commands

Predefined commands provides the syntax, usage, and examples of the predefined commands that are useful for writing scripts.

Predefined commands

Syntax Usage and Example
Global
debug(“msg”, …) Write the message to the debug buffer. For example:

debug("HTTP Request method is %s.\n", HTTP:method_get())

Debug strings can be written to the console when the event is triggered. This is helpful when you are testing your scripts.

To enable debug strings to be written to the console, use the following CLI commands:

diagnose debug enable

diagnose debug application httproxy scripting

cmp_addr(addr, addr_group)

Used to match one IP address against a group of IP addresses. It can automatically detect IPv4 and IPv6 and can be used to compare IPv4 addresses with IPv6 addresses.

For example:

cmp_addr(“192.3.2.1/24”, “192.3.2.0/32”)

cmp_addr(“::ffff:192.3.2.1/120”, “::ffff:192.3.2.0/128”)

cmp_addr(“192.3.2.1/24”, “::ffff:192.3.2.0/128”)

Input format:

For an IPv4 ip_addr/[mask], the mask can be a number between 0 and 32 or a dotted format like 255.255.255.0

For an IPv6 ip_addr/[mask], the mask can be a number between 0 and 128.

FortiADC supports address group for the second argument.

when RULE_INIT{

--initialize the address group here

addr_group = "192.168.1.0/24" --first network address

addr_group = addr_group..",::ffff:172.30.1.0/120" --second network address

--so on and so forth

}

when HTTP_REQUEST{

client_ip=HTTP:client_addr()

match_ip=cmp_addr(client_ip, addr_group)

}

log("fmt", ...)

Writes log messages into the SLB log category in the script log part. You must enable Script log and SLB sub-category under the Script log on the log setting page. For example:

log("This HTTP Request method is %s.\n", HTTP:method_get())

Note: \ and % are handled in a unique way. Special characters that the log supports are :~!@#$^&*()_+{}][. If you want to print out % in the log, you must use %%; if you want to print out \, you must use \\.

rand() Generates a random number. For example:

a = rand()

debug(“a=%d\n”,a)

time()

Returns the current time as an integer. For example:

The following code will return the current time, in Unix time format, as an integer and store it in variable "t".


t=time()

ctime()

Returns the current time as a string. For example:

The following code will return the current time as a string and store it in variable "ct".


ct=ctime()

md5()

Calculates the MD5 of a string input and stores the results in an intermediate variable. For example:

The following code will calculate the MD5 of the string provided and store it in variable "Md".


Str="test string\1\2"

Md=md5(str)

md5_hex()

Calculates the MD5 of a string input of a string input and outputs the results in HEX format.

The following code will calculate the MD5 of the string provided and store it, in HEX format, in variable "re_hex".


Str="abc"

re_hex=md5_hex(str)

sha1()

Calculates the SHA1 of a string input of a string input and stores the results in an intermediate variable.

The following code will calculate the SHA1 of the string provided and store it in variable "sha".


Str="abc"

sha=sha1(str)

sha1_hex()

Calculates the SHA1 of a string input of a string input and outputs the results in HEX format.


The following code will calculate the SHA1 of the string provided and store it, in HEX format, in variable "sha".

Str="abc"

sha=sha1_hex(str)


b64_enc()

Encodes a string input in base64 and outputs the results in string format.

The following code will encode the string provided and store it in the variable "en".

Str="abc"

en=b64_enc(str)

b64_dec()

Decodes a base64 encoded string input and outputs the results in string format.

The following code will encode the string provided and store it in the variable "en".

Str="abc"

en=b64_dec(str)

htonl()

Converts a long integer input into network byte order and outputs the results in string format.


The following code will convert the integer provided and store it, as a string, in the variable "b".

a=32

b=htonl(a)

ntohl()

Converts a long integer input into host byte order and outputs the results in string format.

The following code will convert the integer provided and store it, as a string, in the variable "b".

a=32

b=ntohl(a)

htons()

Converts a short integer input into network byte order and outputs the results in string format.

The following code will convert the integer provided and store it, as a string, in the variable "b".

a=32

b=htons(a)

ntohs()

Converts a short integer input into host byte order and outputs the results in string format.

The following code will convert the integer provided and store it, as a string, in the variable "b".

a=32

b=ntohs(a)

string.format()

Converts an integer to string format.

The following code will convert the integer provided and store it, as a string, in the variable "b".

a=32

b=string.format(a)

You may also use the function as shown in the code below. The string "12,pi=3.14" will be stored in variable "b".

a=12

b=string.format("%s,pi=%.4f",a,3.14);

string.char()

Converts a number in string format to its corresponding ASCII char.

The following code will convert the string provided and store it in the variable "test". In this case, string.char() will return "a".

str=97

test=string.char(str)

{<variable>:byte(1,-1)}

Creates a table with the codes of all characters in the variable. This table can be used to recreate the original string using the table_to_string() command.

The following code will create a table, then store the variable 'str" in the table. In this case,variable "t" is the table, and t[1] is 97, t[2] is 98, t[3] is 99, t[4] is 1, t[5] is 2, t[6] is 0.

str="abc\1\2\0"

t={str:byte(1,-1)}

{<variable>:sub(i,j)}

Returns a sub-string of the variable indexed from i to j.

The following code will return the string "abc" and store it into variable "t".

str="abc\1\2\0"

t={str:sub(1,3)}

table_to_string()

Converts a table to string format.

The following code will convert the table "t" and store it, as a string, in the variable "str".The string stored in "str" at the end is "abc\1".

t={};

t[1]=97;

t[2]=98;

t[3]=99;

t[4]=1;

str=table_to_string(t);

to_HEX

Converts a string to HEX format.

The following code will convert the string "str" and store it to "hex" in HEX format.

str="\0\123\3"

hex=to_HEX(str);

crc32(str);

Returns the crc32 check value of the string, or 0 if it is an empty string, For example:

when HTTP_REQUEST {

str = "any string for crc32 calculation"

crc = crc32(str);

debug("rc is %d\n", crc);

}

new_key = key_gen(str_pass, str_salt, iter_num, len_num); "

Creates an AES key to encrypt/decrypt data, either generated by password or user specific defined. For example:

when HTTP_REQUEST {

new_key = key_gen("pass", "salt", 32, 32);

debug("new key in hex is %s\n", to_HEX(new_key));

}

aes_enc(t)

Encrypts a string using AES algorithm, For example:

when HTTP_REQUEST { t={}; t["message"] = "value";

t["key"] = "aaaaaaaaaabbbbbb";

t["size"]=128 enc = aes_enc(t) debug("encrypted in hex is %s, after b64 encoding %s\n", to_HEX(enc), b64_enc_str(enc));

}

aes_dec(t)

Dencrypts a string using AES algorithm. For example:

when HTTP_REQUEST { t={}; t["message"] = enc;

t["key"] = "aaaaaaaaaabbbbbb";

t["size"]=128 dec = aes_dec(t);

debug("decrypted in hex is %s\n", to_HEX(dec));

}

EVP_Digest(alg, str)

EVP_Digest for oneshot digest calculation. For example:

when HTTP_REQUEST { alg = "MD5"; data = "your data" re = EVP_Digest(alg, data);

debug("the digest in hex is %s\n", to_HEX(re));

}

HMAC(alg, str, key)

HMAC message authentication code. For example:

when HTTP_REQUEST { alg = "MD5"; --must be "MD5", "SHA1", "SHA256", "SHA384", "SHA512" data = "your data" key = "11234567890ab";

re = HMAC(alg, data, key);

debug("the HMAC in hex is %s\n", to_HEX(re)); }

HMAC_verify(alg, data, key, verify)

Check if the signature is same as the current digest.

when HTTP_REQUEST { alg = "MD5"; data = "your data" verify = "your result to compare" key = "11234567890ab";

re = HMAC_verify(alg, data, key, verify);

if re then debug("verified\n") else debug("not verified\n") end }

G2F(alg, key)

Returns a G2F random value . For example:

when HTTP_REQUEST { alg = "MD5"; key = "11234567890ab";

re = G2F(alg, key);

debug("the G2F value is %d\n", re); }

class_match(str, method, list);

Used to match the string against an element in list:

when HTTP_REQUEST { url = HTTP:uri_get() status, count, t = class_match(url, "starts_with", url_list);

debug("status %s, count %s\n", status, count);

for k,v in pairs(t) do debug("index %s, value %s\n", k,v); end }

class_search(list, method, str);

Used to search the an element in the list against a string:

when HTTP_REQUEST { status, count, t = class_search(url_list, "starts_with", url);

--or "ends_with", "equals", "contains" for k,v in pairs(t) do debug("index %s, value %s\n", k,v); end }

ip2country_name(ip)

Return the GEO information (country name) of an IP address.

when HTTP_REQUEST { cip = IP:client_addr(); cnm = ip2country_name(cip); debug("cname %s\n", cnm); }

ip2countryProv_name(ip)

Return the the GEO information (country name + possible province name) of an IP address.

when HTTP_REQUEST { cip = IP:client_addr(); cnm = ip2countryProv_name(cip); debug("cname %s\n", cnm); }

url_enc(str)

Converted the url into a valid ASCII format.

when HTTP_REQUEST { url = "http://foor bar/@!"; enc = url_enc(url); debug("encoded url is %s\n", enc); }

url_dec(str)

converted the encoding-url into a orignal url.

when HTTP_REQUEST { url = "http://foor.bar/test/"; enc = url_enc(url); debug("encoded url is %s\n", enc); }

url_parser(str)

Extracte the url and host are converted to lower case letters.

when HTTP_REQUEST { url = "http://foo:bar@w1.superman.com/very/long/path.html?p1=v1&p2=v2#more-details" purl = url_parser(url); if purl then debug("parsed url scheme %s, host %s, port %s, path %s, query %s, fragment %s, username %s, passowrd %s\n", purl["scheme"], purl["host"], purl["port"],purl["path"], purl["query"], purl["fragment"], purl["username"], purl["password"]); end }

url_compare(url1, url2)

Compare two url string, return true if it's the same.

when HTTP_REQUEST { url1 = "http://www.example.com/url/path/data" url2 = "httP://WWW.example.com:80/url/path/data" if url_compare(url1, url2) then debug("url match\n"); else debug("url not match\n"); end }

rand_hex(int)

Generate a random number in HEX:

str = rand_hex(16);

rand_alphanum(int)

Generate a random alphabet+number sequence:

str = rand_alphanum(16);

rand_seq(int)

Generate a random in sequence:

str = rand_seq(16)

md5_str(str)

Calculate the MD5 of a string input and stores the results in an intermediate variable, In some cases you need a this version to deal with it. For example:

Md=md5_str(input); --input can be a cert in DER format

md5_hex_str(str)

Calculates the MD5 of a string input of a string input and outputs the results in HEX format, In some cases you need a this version to deal with it. For example:

Md=md5_hex_str(input); --input can be a cert in DER format

sha1_str()

Calculates the SHA1 of a string input of a string input and stores the results in an intermediate variable, In some cases you need a this version to deal with it. For example:

result=sha1_str(input); --input can be a cert in DER format

sha1_hex_str()

Calculates the SHA1 of a string input of a string input and outputs the results in HEX format, In some cases you need a this version to deal with it. For example:

result=sha1_hex_str(input); --input can be a cert in DER format

sha256()

Calculates the SHA256 of a string input of a string input and stores the results in an intermediate variable. The following code will calculate the SHA256 of the string provided and store it in variable "sha256".

Str="abc" sha256=sha256(str)

sha256_hex()

Calculates the SHA256 of a string input of a string input and outputs the results in HEX format. The following code will calculate the SHA256 of the string provided and store it, in HEX format, in variable "sha256".

Str="abc" sha256=sha256_hex(str)

sha256_str()

Calculates the SHA256 of a string input of a string input and stores the results in an intermediate variable. In some cases you need a this version to deal with it. For example:

result=sha256_str(input); --input can be a cert in DER format

sha256_hex_str()

Calculates the SHA256 of a string input of a string input and outputs the results in HEX format. In some cases you need a this version to deal with it. For example:

result=sha256_hex_str(input); --input can be a cert in DER format

sha384()

Calculates the SHA384 of a string input of a string input and stores the results in an intermediate variable. The following code will calculate the SHA384 of the string provided and store it in variable "sha384".

Str="abc" sha384=sha384(str)

sha384_hex()

Calculates the SHA384 of a string input of a string input and outputs the results in HEX format. The following code will calculate the SHA384 of the string provided and store it, in HEX format, in variable "sha384".

Str="abc" sha384=sha384_hex(str)

sha384_str()

Calculates the SHA384 of a string input of a string input and stores the results in an intermediate variable. In some cases you need a this version to deal with it. For example:

result=sha384_str(input); --input can be a cert in DER format

sha384_hex_str()

Calculates the SHA384 of a string input of a string input and outputs the results in HEX format. In some cases you need a this version to deal with it. For example:

result=sha384_hex_str(input); --input can be a cert in DER format

sha512()

Calculates the SHA512 of a string input of a string input and stores the results in an intermediate variable. The following code will calculate the SHA512 of the string provided and store it in variable "sha512".

Str="abc" sha512=sha512(str)

sha512_hex()

Calculates the SHA512 of a string input of a string input and outputs the results in HEX format. The following code will calculate the SHA512 of the string provided and store it, in HEX format, in variable "sha512".

Str="abc" sha512=sha512_hex(str)

sha512_str()

Calculates the SHA512 of a string input of a string input and stores the results in an intermediate variable. In some cases you need a this version to deal with it. For example:

result=sha512_str(input); --input can be a cert in DER format

sha512_hex_str()

Calculates the SHA512 of a string input of a string input and outputs the results in HEX format. In some cases you need a this version to deal with it. For example:

result=sha512_hex_str(input); --input can be a cert in DER format

b32_enc()

Encodes a string input in base32 and outputs the results in string format. The following code will encode the string provided and store it in the variable "en".

Str="abc" en=b32_enc(str)

b32_enc_str(str)

Encodes a string input in base32 and outputs the results in string format. In some cases you need a this version to deal with it. For example:

result=b32_enc_str(input); --input can be a cert in DER format

b32_dec()

Decodes a base32 encoded string input and outputs the results in string format. The following code will encode the string provided and store it in the variable "dec".

Str="abc" dec=b32_dec(str)

b32_dec_str()

Decodes a base32 encoded string input and outputs the results in string format. In some cases you need a this version to deal with it. For example:

result=b32_dec_str(input); --input can be a cert in DER format

get_pid()

Return the PID value of the VS process. For exmaple:

debug("VS PID is : %d\n", get_pid());

HTTP
cookie_list

Returns a list of cookies: their names and values. For example:

ret=HTTP:cookie_list()

for k,v in pairs(ret)

do debug("cookie name %s, value %s\n", k,v);

end

cookie

Allows you to GET/SET its value and its attribute, REMOVE a whole cookie, GET the whole cookie in HTTP RESPONSE, and INSERT a new cookie. For example:

t={};

t["name"]="test" t["parameter"]="value";--value, cookie, path, domain, expires, secure, maxage, max-age, httponly, version, port

t["action"]="get"--get, set, remove, insert ret = HTTP:cookie(t)

if ret then

debug("get cookie value succeed %s\n",ret);

else

debug("get cookie value failed\n");

end

cookie_crypto

The provided function response_encrypt_cookie can be used to perform cookie encryption in HTTP RESPONSE and request_decrypt_cookie can be used to perform cookie decryption in HTTP REQUEST. For example:

--Decrypt cookie "test" in HTTP REQUEST before forwarding to real servers local t={};

t["name"]="cookiename"

t["action"]="encrypt"--encrypt, or decrypt

t["key"]="0123456789ABCDEF";

t["prefix"]="XXXX";

t["size"]=size-- 128, 192, or 256, the corresponding key length is 16, 24, and 32 if HTTP:

cookie_crypto(t) then debug("Encrypt cookie succeed\n");

else

debug("Encrypt cookie failed\n");

end

respond

Allows you to return a customized page, For example:

when HTTP_REQUEST{ tt={} tt["code"] = 200;

tt["content"] = "XXXXX Test Page XXXXXXX\r\n\r\n";

status = HTTP:respond(tt);

debug("HTTP_respond() status: %s\n", status);

}

header_get_names() Returns a list of all the headers present in the request or response. For example:

--use header and value

headers = HTTP:header_get_names()

for k, v in pairs(headers) do

debug("The value of header %s is %s.\n", k, v)

end

--only use the header name

for name in pairs(headers) do

debug("The request/response includes header %s.\n", name)

end

header_get_values(header_name) Returns a list of value(s) of the HTTP header named <header_name>, with a count for each value. Note that the command returns all the values in the headers as a list if there are multiple headers with the same name. For example:

cookies=HTTP:header_get_values("Cookie")

for k, cnt in pairs(cookies) do

debug("initially include cookie %s cnt %d\n", k, v)

end

header_get_value(header_name) Returns the value of the HTTP header named <header_name>.

Returns false if the HTTP header named <header_name> does not exist. Note: The command operates on the value of the last header if there are multiple headers with the same name. For example:

host = HTTP:header_get_value("Host")

header_remove(header_name) Removes all headers names with the name <header_name>. For example:

HTTP:header_remove("Cookie")

header_remove2(header_name,countid) header_get_values() returns a count ID for each item. This count ID can be used in both header_remove2() and header_replace2() to remove and replace a certain header of a given name referenced by the count ID. For example:

cookies=HTTP:header_get_values("Set-Cookie")

for k, v in pairs(cookies) do

debug("include cookie %s cnt %d\n", k, v)

end

if HTTP:header_remove2("Set-Cookie", 1) then

debug("remove 1st cookie\n")

end

header_insert(header_name, value) Inserts the named HTTP header(s) and value(s) into the end of the HTTP request or response. For example:

HTTP:header_insert("Cookie", "cookie=server1")

header_replace(header_name, value) Replaces the value of the last occurrence of the header named <header_name> with the string <value>. Performs a header insertion if the header is not present. For example:

HTTP:header_replace("Host", "www.fortinet.com")

header_replace2(header_name, value,countid) header_get_values() returns a count ID for each item. This count ID can be used in both header_remove2() and header_replace2() to remove and replace a certain header of a given name referenced by the count ID. For example:

cookies=HTTP:header_get_values("Set-Cookie")

for k, v in pairs(cookies) do

debug("include cookie %s cnt %d\n", k, v)

end

if HTTP:header_replace2("Set-Cookie", "new2=value2", 2) then

debug("replace 2nd cookie by new2=value2\n")

end

header_exists(header_name) Returns true if the named header is present and not empty on the request or response. For example:

if HTTP:header_exists("Cookie") then

end

header_count(header_name) Returns the number of HTTP headers present in the request or response. For example:

count = HTTP:header_count("Cookie")

method_get() Return the string of the HTTP request method. For example:

method = HTTP:method_get()

method_set(string) Set the HTTP request method to the string "value". For example:

HTTP:method_set("POST")

path_get() Returns the path part of the HTTP request. For example:

path = HTTP:path_get()

path_set(string) Sets the path part of the HTTP request. The client will not see the update unless the web application uses the requested path to generate response headers and/or content. If you want the client to see the update to the path in the browser's address bar, you can send an HTTP redirect using HTTP:redirect or HTTP:respond. For example:

HTTP:path_set("/other.html")

uri_get() Returns the URI given in the request. For example:

uri = HTTP:uri_get()

uri_set(string) Changes the URI passed to the server. It should always start with a slash. For example:

HTTP:uri_set("/index.html?value=xxxx")

query_get() Returns the query part of the HTTP request. For example:

query = HTTP:query_get()

query_set(string) Sets the query part of the HTTP request. For example:

HTTP:query_set("value=xxx")

redirect(“URL”, …) Redirects an HTTP request or response to the specified URL. For example:

Host = HTTP:header_get_value("host")

Path = HTTP:path_get()

HTTP:redirect("https://%s%s", Host, Path)

redirect_with_cookie(URL, cookie) Redirects an HTTP request or response to the specified URL with Cookie. For example:

HTTP:redirect_with_cookie(“www.example.com”, “server=nginx”)

redirect_t Redirects an HTTP request or response to the URL specified in the table. For example:

a={}

a["url"]="http://192.168.1.7"

a["code"]="303"

a["cookie"]="test=server"

HTTP:redirect_t(a)

version_get() Returns the HTTP version of the request or response. For example:

vers = HTTP:version_get()

version_set(string) Sets the HTTP version of the request or response. For example:

HTTP:version_set("1.0")

status_code_get() Returns the response status code output as string. For example:

responsestatus=HTTP:status_code_get()

status_code_set(string) Sets the response status code. For example:

HTTP:status_code_set("301")

code_get() Returns the response status code,output as integer. For example:

responsestatus=HTTP:code_get()

code_set(integer) Sets the response status code. For example:

HTTP:code_set(301)

reason_get() Returns the response reason. For example:

HTTP:reason_get()

reason_set(string) Sets the response reason. For example:

HTTP:reason_set(string)

rand_id() Returns a random string of 32-long in hex format, which can be inserted directly as an HTTP header. For example:

ID=HTTP:rand_id()

HTTP:header_insert("Message-ID", ID)

client_addr() Returns the client IP address of a connection for an HTTP_REQUEST packet, which is the source address for the HTTP_REQUEST packet. It's a destination address. For example:

CIP=HTTP:client_addr()

local_addr() For HTTP_REQUEST, returns the IP address of the virtual server the client is connected to; for HTTP_RESPONSE, returns the incoming interface IP address of the return packet. For example:

LIP=HTTP:local_addr()

remote_addr() Returns the IP address of the host on the far end of the connection. For example:

RIP=HTTP:remote_addr()

server_addr() Returns the IP address of the server in HTTP_RESPONSE.

SIP=HTTP:server_addr()

close() Closes an HTTP connection using code 503. For example:

HTTP:close()

client_port() Returns the client port number in a string format. For example:

HTTP:client_port()

local_port() Returns the local port number in a string format. For example:

HTTP:local_port()

remote_port() Returns the remote port number in a string format. For example:

HTTP:local_port()

server_port() Returns the server port number in a string format. For example:

HTTP:server_port()

client_ip_ver() Returns the client IP version number. For example:

HTTP:client_ip_ver()

server_ip_ver() Returns the server IP version number. For example:

HTTP:server_ip_ver()

collect

Collects data. You may specify a specific amount using the length argument. Used in HTTP_REQUEST or HTTP_RESPONSE. For example:

t={};

t["size"]=1000; --optional

HTTP:collect(t);

payload (size)

Returns the size of the buffered content. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE. For example:

t={};

t["operation"]="size"

sz=HTTP:payload(t); --return value is an int

payload (content)

Returns the buffered content in a string. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE. For example:

t={};

t[“operation”]=”content”

t[“offset”]=12; --optional

t[“size”]=20; --optional

ct = HTTP:payload(t); --return value is a string

payload (set)

Replaces the buffered data with new data. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE.For example:

t={};

t[“operation”]=”set”

t[“offset”]=12; --optional

t[“size”]=20; --optional

t[“data”]= ”new data to insert”;

ret = HTTP:payload(t); --returns true if operation succeeds

payload (find)

Searches for a particular string in the buffered data. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE.For example:

t={};

t[“operation”]=”find”

t[“data”]=”sth”; -- can also be a regular expression, like (s.h)

t[“offset”]=12; --optional

t[“size”]=20; --optional

t[“scope”]=”first” -- the scope field can be either “first” or “all”

ct = HTTP:payload(t); --returns the number of occurences found

payload (remove)

Removes a particular string from the buffered data. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE.For example:

t={};

t[“operation”]=”remove”

t[“data”]=”sth”; -- can also be a regular expression, like (s.h)

t[“offset”]=12;

t[“size”]=20;

t[“scope”]=”first” -- or “all”

ct = HTTP:payload(t); --returns number of occurrences removed

payload (replace)

Replaces a particular string or regular expression with a new string. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE. For example:

t={};

t[“operation”]=”replace”

t[“data”]=”sth”; -- can be a regular expression, like (s.h)

t[“new_data”]=”sth new”;

t[“offset”]=12; --optional

t[“size”]=20; --optional

t[“scope”]=”first” -- or “all”

ct = HTTP:payload(t); --returns number of occurrences replaced

set_event

Sets a request or response event. For example:

t={};

t["event"] = "data_res"; --can be req,res,data_req, or data_res

t["operation"] = "disable";

HTTP:set_event(t)

set_auto

Sets an automatic request or response event. For example:

t={};

t["event"] = "data_res"; --can be req, res, data_req, or data_res

t["operation"] = "disable";

HTTP:set_auto(t)

lookup_tbl

Input a hash value to look up the persistence session table and dispatches it in ADC if the hash value matches the one in the persistence table.

t[“hash_value”] = “hash”

persist

HTTP:persist() : (operate in PERSISTENCE and POST_PERSIST)

  1. Operation #1. Save the entry to stick table:
  2. Input:

    t[“operation”] = “save_tbl”

    t[“hash_value”] = “hash”

    t[“srv_name”]= “srv name”

    Output:

    true: success, false: failed

  3. Operation #2. Read the tbl entry:
  4. Input:

    t[“operation”] = “read_tbl”

    t[“hash_value”] = “hash”

    Output:

    server name of the entry, or false if no entry found

  5. Operation #3. Dump the tbl entry:
  6. Input

    t[“operation”] = “dump_tbl”

    t[“index”] = 50

    t[“count”] = 1000

    Output:

    A table include hash and server name

  7. Operation #4. Get the list o freal server and status:
  8. Input

    t[“operation”] = “get_valid_server”

    Output

    Return the table of usable real server and server state(enable, disable, maintain, backup)

  9. Operation #5 Calculate the real server from hash:
  10. Input

    t[“operation”] = “cal_server_from_hash”

    t[“hash_value”] = “hash”

    Output

    Return the real server name according to the hash value using our algorithm or False if failed.

  11. Operation #6. Get the real server currently assigned to this session:
  12. Input

    t[“operation”] = “get_current_assigned_server”

    Output

    Return the real server name which is assigned to current session or False if no server is assigned right now.

Load Balance
routing(content_route) Selects a content route. For example:

LB:routing("content2")

TCP
reject()

Allow you to reject a TCP connection from a client. Can be used in TCP_ACCEPTED event. For example:

when TCP_ACCEPTED {

--Check if the st is true or false

if st then

TCP:reject();

end }

set_snat_ip(str)

Allows user to set the backend TCP connection's source address and port. For example:

when TCP_ACCEPTED {

addr_group = "172.24.172.60/32"

client_ip = IP:client_addr()

matched = cmp_addr(client_ip, addr_group)

if matched then

if TCP:set_snat_ip("10.106.3.124") then

debug("set SNAT ip to 10.106.3.124\n");

end

end }

clear_snat_ip()

Allows you to clear whatever customized ip you ever set using set_snat_ip(). For example:

when TCP_ACCEPTED {

if TCP:clear_snat_ip() then

debug("Clear SNAT IP !\n");

end }

sockopt(t)

Allows user to customize the send buffer and receive buffer size. For example:

when VS_LISTENER_BIND {

local t = {};

t["op"] = "get";

t["message"] = "snd_buf" --"snd_buf" or "rcv_buf"

if TCP:sockopt(t) then

debug("tcp send buffer is %d\n", tcp_snd_buf);

else

debug("get tcp send buffer failed\n");

end }

SSL
version()

Allows you to GET the SSL version, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

ver=SSL:version();

cipher()

Allows you to GET the SSL cipher, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

ci=SSL:cipher();

alg_keysize()

Allows you to GET the SSL key size, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

alg_keysize=SSL:alg_keysize()

npn()

Allows you to GET the SSL NPN extension, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

npn=SSL:npn();

alpn

Allows you to GET the SSL ALPN extension, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

alpn=SSL:alpn();

sni()

Allows you to GET the SSL SNI, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

sni=SSL:sni();

client_cert()

Returns the client certificate status, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

client_cert=SSL:client_cert()

session(t)

Allows you to GET SSL session id / Reused / Remove from cache, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

t={}

t["operation"]="get_id"--or "remove" "reused"

sess_id=SSL:session(t);

if sess_id then

sess_id=to_HEX(sess_id)

debug("client sess id %s\n", sess_id);

else

sess_id="FALSE"

end

cert(t)

Allows you to GET the cert info between local or remote, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

t={} t["direction"]="remote";--or "local"

t["operation"]="count";-- or "index", or "issuer"

cert=SSL:cert(t)

if cert then

debug("has %s certs\n", cert)

else

debug("no cert\n")

end

peer_cert(str)

Returns the peer certificate, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example

cder=SSL:peer_cert("der");--for remote leaf certificate, the input parameter can be "info" or "der" or "pem".

if cder then

hash=sha1_hex_str(cder);

debug("whole cert sha1 hash is %s\n", hash);

end

IP
client_addr()

Returns the client IP address, can be used in all events except VS_LISTENER_BIND. For example:

cip=IP:client_addr()

local_addr()

Returns the local IP address, can be used in all events except VS_LISTENER_BIND / SERVER_BEFORE_CONNECT. For example:

lip=IP:local_addr()

remote_addr()

Returns the remote IP address, can be used in all events except VS_LISTENER_BIND / SERVER_BEFORE_CONNECT. For example:

rip=IP:remote_addr()

client_port()

Returns the client IP port number, can be used in all events except VS_LISTENER_BIND. For example:

cp=IP:client_port()

local_port()

Returns the local port number, can be used in all events except VS_LISTENER_BIND / SERVER_BEFORE_CONNECT. For example:

lp=IP:local_port()

remote_port()

Returns the remote port number can be used in all events except VS_LISTENER_BIND / SERVER_BEFORE_CONNECT. For example:

rp=IP:remote_port()

client_ip_ver()

Returns the client IP version, can be used in all events except VS_LISTENER_BIND. For example:

cipv=IP:client_ip_ver();

server_addr()

Returns the server IP address, can be used in server-side events. For example:

sip=IP:server_addr()

server_port()

Returns the server port number, can be used in server-side events. For example:

sp=IP:server_port()

server_ip_ver()

Returns the server IP version, can be used in server-side events. For example:

sipv=IP:server_ip_ver();

Management
get_session_id()

Returns the session id, can be used in all events except VS_LISTENER_BIND. For example:

sid=MGM:get_session_id()

debug("sess id %s\n", sid);

rand_id()

Returns the rand id, can be used in all events except VS_LISTENER_BIND. For example:

sid=MGM:get_session_id()

debug("rand id %s\n", rid);

set_event(t)

Allow user to disable/enable rest of theevents from executing by disabling this event. For example:

t={};

t["event"]="req"; -- can be "req", "res", "data_req", "data_res", "ssl_client", "ssl_server", "tcp_accept", "tcp_close", "ssl_renego_client", "ssl_renego_server", "server_connected", "server_close", "server_before_connect", "vs_listener_bind", "auth_result", "cookie_bake"

t["operation"]="disable"; -- can be "enable", and "disable"

MGM:set_event(t);

debug("disable rest of the HTTP_REQUEST events\n");

set_auto(t)

Allow user to enable/disable automatic re-enabling. For example:

t={};

t["event"]="req"; -- can be "req", "res", "data_req", "data_res", "ssl_server", "ssl_renego_server", "server_connected", "server_close", "server_before_connect" t["operation"]="disable"; -- can be "enable", and "disable"

MGM:set_auto(t);

debug("disable automatic re-enabling of the HTTP_REQUEST events\n");

Auth
get_baked_cookie()

Allows you to retrieve the baked cookie, For example:

when COOKIE_BAKE { cookie = AUTH:get_baked_cookie() debug("baked cookie %s\n", cookie); }

set_baked_cookie(cookie)

Allows you to customize cookie attributes the baked cookie, For example:

when COOKIE_BAKE { cookie = AUTH:get_baked_cookie() --add new attribute HttpOnly new_cookie = cookie.."; HttpOnly"; AUTH:set_baked_cookie(new_cookie); }

on_off()

Returns the authentication is required or not, For example:

on_off = AUTH:on_off();

success()

Returns the authentication is successful or not, For example:

succ = AUTH:success();

form_based()

Returns the authentication is HTTP form based or not , For example:

fm = AUTH:form_based()

user()

Returns the authentication of the user name , For

example:user = AUTH:user()

pass()

Returns the authentication of the password , For

example:pass = AUTH:pass()

usergroup()

Returns the authentication of the user group , For

example:userg = AUTH:usergroup()

realm()

Returns the authentication of the realm , For

example:userg = AUTH:usergroup()

host()

Returns the authentication of the host , For

example:host = AUTH:host()

Proxy
set_auth_key(str)

Allows user to customize the crypto key FADC used for encrypt/decrypt authentication cookie, For example:

when VS_LISTENER_BIND {

AUTH_KEY = ""0123456789ABCDEF0123456789ABCDEF""

if PROXY:set_auth_key(AUTH_KEY) then

debug(""set auth key succeed\n"");

end

}

Init_stick_tbl_timeout()

Allow user to set the timeout of stick table for persistence.

when RULE_INIT{

env={}

PROXY:init_stick_tbl_timeout(500)

}

Predefined commands

Predefined commands provides the syntax, usage, and examples of the predefined commands that are useful for writing scripts.

Predefined commands

Syntax Usage and Example
Global
debug(“msg”, …) Write the message to the debug buffer. For example:

debug("HTTP Request method is %s.\n", HTTP:method_get())

Debug strings can be written to the console when the event is triggered. This is helpful when you are testing your scripts.

To enable debug strings to be written to the console, use the following CLI commands:

diagnose debug enable

diagnose debug application httproxy scripting

cmp_addr(addr, addr_group)

Used to match one IP address against a group of IP addresses. It can automatically detect IPv4 and IPv6 and can be used to compare IPv4 addresses with IPv6 addresses.

For example:

cmp_addr(“192.3.2.1/24”, “192.3.2.0/32”)

cmp_addr(“::ffff:192.3.2.1/120”, “::ffff:192.3.2.0/128”)

cmp_addr(“192.3.2.1/24”, “::ffff:192.3.2.0/128”)

Input format:

For an IPv4 ip_addr/[mask], the mask can be a number between 0 and 32 or a dotted format like 255.255.255.0

For an IPv6 ip_addr/[mask], the mask can be a number between 0 and 128.

FortiADC supports address group for the second argument.

when RULE_INIT{

--initialize the address group here

addr_group = "192.168.1.0/24" --first network address

addr_group = addr_group..",::ffff:172.30.1.0/120" --second network address

--so on and so forth

}

when HTTP_REQUEST{

client_ip=HTTP:client_addr()

match_ip=cmp_addr(client_ip, addr_group)

}

log("fmt", ...)

Writes log messages into the SLB log category in the script log part. You must enable Script log and SLB sub-category under the Script log on the log setting page. For example:

log("This HTTP Request method is %s.\n", HTTP:method_get())

Note: \ and % are handled in a unique way. Special characters that the log supports are :~!@#$^&*()_+{}][. If you want to print out % in the log, you must use %%; if you want to print out \, you must use \\.

rand() Generates a random number. For example:

a = rand()

debug(“a=%d\n”,a)

time()

Returns the current time as an integer. For example:

The following code will return the current time, in Unix time format, as an integer and store it in variable "t".


t=time()

ctime()

Returns the current time as a string. For example:

The following code will return the current time as a string and store it in variable "ct".


ct=ctime()

md5()

Calculates the MD5 of a string input and stores the results in an intermediate variable. For example:

The following code will calculate the MD5 of the string provided and store it in variable "Md".


Str="test string\1\2"

Md=md5(str)

md5_hex()

Calculates the MD5 of a string input of a string input and outputs the results in HEX format.

The following code will calculate the MD5 of the string provided and store it, in HEX format, in variable "re_hex".


Str="abc"

re_hex=md5_hex(str)

sha1()

Calculates the SHA1 of a string input of a string input and stores the results in an intermediate variable.

The following code will calculate the SHA1 of the string provided and store it in variable "sha".


Str="abc"

sha=sha1(str)

sha1_hex()

Calculates the SHA1 of a string input of a string input and outputs the results in HEX format.


The following code will calculate the SHA1 of the string provided and store it, in HEX format, in variable "sha".

Str="abc"

sha=sha1_hex(str)


b64_enc()

Encodes a string input in base64 and outputs the results in string format.

The following code will encode the string provided and store it in the variable "en".

Str="abc"

en=b64_enc(str)

b64_dec()

Decodes a base64 encoded string input and outputs the results in string format.

The following code will encode the string provided and store it in the variable "en".

Str="abc"

en=b64_dec(str)

htonl()

Converts a long integer input into network byte order and outputs the results in string format.


The following code will convert the integer provided and store it, as a string, in the variable "b".

a=32

b=htonl(a)

ntohl()

Converts a long integer input into host byte order and outputs the results in string format.

The following code will convert the integer provided and store it, as a string, in the variable "b".

a=32

b=ntohl(a)

htons()

Converts a short integer input into network byte order and outputs the results in string format.

The following code will convert the integer provided and store it, as a string, in the variable "b".

a=32

b=htons(a)

ntohs()

Converts a short integer input into host byte order and outputs the results in string format.

The following code will convert the integer provided and store it, as a string, in the variable "b".

a=32

b=ntohs(a)

string.format()

Converts an integer to string format.

The following code will convert the integer provided and store it, as a string, in the variable "b".

a=32

b=string.format(a)

You may also use the function as shown in the code below. The string "12,pi=3.14" will be stored in variable "b".

a=12

b=string.format("%s,pi=%.4f",a,3.14);

string.char()

Converts a number in string format to its corresponding ASCII char.

The following code will convert the string provided and store it in the variable "test". In this case, string.char() will return "a".

str=97

test=string.char(str)

{<variable>:byte(1,-1)}

Creates a table with the codes of all characters in the variable. This table can be used to recreate the original string using the table_to_string() command.

The following code will create a table, then store the variable 'str" in the table. In this case,variable "t" is the table, and t[1] is 97, t[2] is 98, t[3] is 99, t[4] is 1, t[5] is 2, t[6] is 0.

str="abc\1\2\0"

t={str:byte(1,-1)}

{<variable>:sub(i,j)}

Returns a sub-string of the variable indexed from i to j.

The following code will return the string "abc" and store it into variable "t".

str="abc\1\2\0"

t={str:sub(1,3)}

table_to_string()

Converts a table to string format.

The following code will convert the table "t" and store it, as a string, in the variable "str".The string stored in "str" at the end is "abc\1".

t={};

t[1]=97;

t[2]=98;

t[3]=99;

t[4]=1;

str=table_to_string(t);

to_HEX

Converts a string to HEX format.

The following code will convert the string "str" and store it to "hex" in HEX format.

str="\0\123\3"

hex=to_HEX(str);

crc32(str);

Returns the crc32 check value of the string, or 0 if it is an empty string, For example:

when HTTP_REQUEST {

str = "any string for crc32 calculation"

crc = crc32(str);

debug("rc is %d\n", crc);

}

new_key = key_gen(str_pass, str_salt, iter_num, len_num); "

Creates an AES key to encrypt/decrypt data, either generated by password or user specific defined. For example:

when HTTP_REQUEST {

new_key = key_gen("pass", "salt", 32, 32);

debug("new key in hex is %s\n", to_HEX(new_key));

}

aes_enc(t)

Encrypts a string using AES algorithm, For example:

when HTTP_REQUEST { t={}; t["message"] = "value";

t["key"] = "aaaaaaaaaabbbbbb";

t["size"]=128 enc = aes_enc(t) debug("encrypted in hex is %s, after b64 encoding %s\n", to_HEX(enc), b64_enc_str(enc));

}

aes_dec(t)

Dencrypts a string using AES algorithm. For example:

when HTTP_REQUEST { t={}; t["message"] = enc;

t["key"] = "aaaaaaaaaabbbbbb";

t["size"]=128 dec = aes_dec(t);

debug("decrypted in hex is %s\n", to_HEX(dec));

}

EVP_Digest(alg, str)

EVP_Digest for oneshot digest calculation. For example:

when HTTP_REQUEST { alg = "MD5"; data = "your data" re = EVP_Digest(alg, data);

debug("the digest in hex is %s\n", to_HEX(re));

}

HMAC(alg, str, key)

HMAC message authentication code. For example:

when HTTP_REQUEST { alg = "MD5"; --must be "MD5", "SHA1", "SHA256", "SHA384", "SHA512" data = "your data" key = "11234567890ab";

re = HMAC(alg, data, key);

debug("the HMAC in hex is %s\n", to_HEX(re)); }

HMAC_verify(alg, data, key, verify)

Check if the signature is same as the current digest.

when HTTP_REQUEST { alg = "MD5"; data = "your data" verify = "your result to compare" key = "11234567890ab";

re = HMAC_verify(alg, data, key, verify);

if re then debug("verified\n") else debug("not verified\n") end }

G2F(alg, key)

Returns a G2F random value . For example:

when HTTP_REQUEST { alg = "MD5"; key = "11234567890ab";

re = G2F(alg, key);

debug("the G2F value is %d\n", re); }

class_match(str, method, list);

Used to match the string against an element in list:

when HTTP_REQUEST { url = HTTP:uri_get() status, count, t = class_match(url, "starts_with", url_list);

debug("status %s, count %s\n", status, count);

for k,v in pairs(t) do debug("index %s, value %s\n", k,v); end }

class_search(list, method, str);

Used to search the an element in the list against a string:

when HTTP_REQUEST { status, count, t = class_search(url_list, "starts_with", url);

--or "ends_with", "equals", "contains" for k,v in pairs(t) do debug("index %s, value %s\n", k,v); end }

ip2country_name(ip)

Return the GEO information (country name) of an IP address.

when HTTP_REQUEST { cip = IP:client_addr(); cnm = ip2country_name(cip); debug("cname %s\n", cnm); }

ip2countryProv_name(ip)

Return the the GEO information (country name + possible province name) of an IP address.

when HTTP_REQUEST { cip = IP:client_addr(); cnm = ip2countryProv_name(cip); debug("cname %s\n", cnm); }

url_enc(str)

Converted the url into a valid ASCII format.

when HTTP_REQUEST { url = "http://foor bar/@!"; enc = url_enc(url); debug("encoded url is %s\n", enc); }

url_dec(str)

converted the encoding-url into a orignal url.

when HTTP_REQUEST { url = "http://foor.bar/test/"; enc = url_enc(url); debug("encoded url is %s\n", enc); }

url_parser(str)

Extracte the url and host are converted to lower case letters.

when HTTP_REQUEST { url = "http://foo:bar@w1.superman.com/very/long/path.html?p1=v1&p2=v2#more-details" purl = url_parser(url); if purl then debug("parsed url scheme %s, host %s, port %s, path %s, query %s, fragment %s, username %s, passowrd %s\n", purl["scheme"], purl["host"], purl["port"],purl["path"], purl["query"], purl["fragment"], purl["username"], purl["password"]); end }

url_compare(url1, url2)

Compare two url string, return true if it's the same.

when HTTP_REQUEST { url1 = "http://www.example.com/url/path/data" url2 = "httP://WWW.example.com:80/url/path/data" if url_compare(url1, url2) then debug("url match\n"); else debug("url not match\n"); end }

rand_hex(int)

Generate a random number in HEX:

str = rand_hex(16);

rand_alphanum(int)

Generate a random alphabet+number sequence:

str = rand_alphanum(16);

rand_seq(int)

Generate a random in sequence:

str = rand_seq(16)

md5_str(str)

Calculate the MD5 of a string input and stores the results in an intermediate variable, In some cases you need a this version to deal with it. For example:

Md=md5_str(input); --input can be a cert in DER format

md5_hex_str(str)

Calculates the MD5 of a string input of a string input and outputs the results in HEX format, In some cases you need a this version to deal with it. For example:

Md=md5_hex_str(input); --input can be a cert in DER format

sha1_str()

Calculates the SHA1 of a string input of a string input and stores the results in an intermediate variable, In some cases you need a this version to deal with it. For example:

result=sha1_str(input); --input can be a cert in DER format

sha1_hex_str()

Calculates the SHA1 of a string input of a string input and outputs the results in HEX format, In some cases you need a this version to deal with it. For example:

result=sha1_hex_str(input); --input can be a cert in DER format

sha256()

Calculates the SHA256 of a string input of a string input and stores the results in an intermediate variable. The following code will calculate the SHA256 of the string provided and store it in variable "sha256".

Str="abc" sha256=sha256(str)

sha256_hex()

Calculates the SHA256 of a string input of a string input and outputs the results in HEX format. The following code will calculate the SHA256 of the string provided and store it, in HEX format, in variable "sha256".

Str="abc" sha256=sha256_hex(str)

sha256_str()

Calculates the SHA256 of a string input of a string input and stores the results in an intermediate variable. In some cases you need a this version to deal with it. For example:

result=sha256_str(input); --input can be a cert in DER format

sha256_hex_str()

Calculates the SHA256 of a string input of a string input and outputs the results in HEX format. In some cases you need a this version to deal with it. For example:

result=sha256_hex_str(input); --input can be a cert in DER format

sha384()

Calculates the SHA384 of a string input of a string input and stores the results in an intermediate variable. The following code will calculate the SHA384 of the string provided and store it in variable "sha384".

Str="abc" sha384=sha384(str)

sha384_hex()

Calculates the SHA384 of a string input of a string input and outputs the results in HEX format. The following code will calculate the SHA384 of the string provided and store it, in HEX format, in variable "sha384".

Str="abc" sha384=sha384_hex(str)

sha384_str()

Calculates the SHA384 of a string input of a string input and stores the results in an intermediate variable. In some cases you need a this version to deal with it. For example:

result=sha384_str(input); --input can be a cert in DER format

sha384_hex_str()

Calculates the SHA384 of a string input of a string input and outputs the results in HEX format. In some cases you need a this version to deal with it. For example:

result=sha384_hex_str(input); --input can be a cert in DER format

sha512()

Calculates the SHA512 of a string input of a string input and stores the results in an intermediate variable. The following code will calculate the SHA512 of the string provided and store it in variable "sha512".

Str="abc" sha512=sha512(str)

sha512_hex()

Calculates the SHA512 of a string input of a string input and outputs the results in HEX format. The following code will calculate the SHA512 of the string provided and store it, in HEX format, in variable "sha512".

Str="abc" sha512=sha512_hex(str)

sha512_str()

Calculates the SHA512 of a string input of a string input and stores the results in an intermediate variable. In some cases you need a this version to deal with it. For example:

result=sha512_str(input); --input can be a cert in DER format

sha512_hex_str()

Calculates the SHA512 of a string input of a string input and outputs the results in HEX format. In some cases you need a this version to deal with it. For example:

result=sha512_hex_str(input); --input can be a cert in DER format

b32_enc()

Encodes a string input in base32 and outputs the results in string format. The following code will encode the string provided and store it in the variable "en".

Str="abc" en=b32_enc(str)

b32_enc_str(str)

Encodes a string input in base32 and outputs the results in string format. In some cases you need a this version to deal with it. For example:

result=b32_enc_str(input); --input can be a cert in DER format

b32_dec()

Decodes a base32 encoded string input and outputs the results in string format. The following code will encode the string provided and store it in the variable "dec".

Str="abc" dec=b32_dec(str)

b32_dec_str()

Decodes a base32 encoded string input and outputs the results in string format. In some cases you need a this version to deal with it. For example:

result=b32_dec_str(input); --input can be a cert in DER format

get_pid()

Return the PID value of the VS process. For exmaple:

debug("VS PID is : %d\n", get_pid());

HTTP
cookie_list

Returns a list of cookies: their names and values. For example:

ret=HTTP:cookie_list()

for k,v in pairs(ret)

do debug("cookie name %s, value %s\n", k,v);

end

cookie

Allows you to GET/SET its value and its attribute, REMOVE a whole cookie, GET the whole cookie in HTTP RESPONSE, and INSERT a new cookie. For example:

t={};

t["name"]="test" t["parameter"]="value";--value, cookie, path, domain, expires, secure, maxage, max-age, httponly, version, port

t["action"]="get"--get, set, remove, insert ret = HTTP:cookie(t)

if ret then

debug("get cookie value succeed %s\n",ret);

else

debug("get cookie value failed\n");

end

cookie_crypto

The provided function response_encrypt_cookie can be used to perform cookie encryption in HTTP RESPONSE and request_decrypt_cookie can be used to perform cookie decryption in HTTP REQUEST. For example:

--Decrypt cookie "test" in HTTP REQUEST before forwarding to real servers local t={};

t["name"]="cookiename"

t["action"]="encrypt"--encrypt, or decrypt

t["key"]="0123456789ABCDEF";

t["prefix"]="XXXX";

t["size"]=size-- 128, 192, or 256, the corresponding key length is 16, 24, and 32 if HTTP:

cookie_crypto(t) then debug("Encrypt cookie succeed\n");

else

debug("Encrypt cookie failed\n");

end

respond

Allows you to return a customized page, For example:

when HTTP_REQUEST{ tt={} tt["code"] = 200;

tt["content"] = "XXXXX Test Page XXXXXXX\r\n\r\n";

status = HTTP:respond(tt);

debug("HTTP_respond() status: %s\n", status);

}

header_get_names() Returns a list of all the headers present in the request or response. For example:

--use header and value

headers = HTTP:header_get_names()

for k, v in pairs(headers) do

debug("The value of header %s is %s.\n", k, v)

end

--only use the header name

for name in pairs(headers) do

debug("The request/response includes header %s.\n", name)

end

header_get_values(header_name) Returns a list of value(s) of the HTTP header named <header_name>, with a count for each value. Note that the command returns all the values in the headers as a list if there are multiple headers with the same name. For example:

cookies=HTTP:header_get_values("Cookie")

for k, cnt in pairs(cookies) do

debug("initially include cookie %s cnt %d\n", k, v)

end

header_get_value(header_name) Returns the value of the HTTP header named <header_name>.

Returns false if the HTTP header named <header_name> does not exist. Note: The command operates on the value of the last header if there are multiple headers with the same name. For example:

host = HTTP:header_get_value("Host")

header_remove(header_name) Removes all headers names with the name <header_name>. For example:

HTTP:header_remove("Cookie")

header_remove2(header_name,countid) header_get_values() returns a count ID for each item. This count ID can be used in both header_remove2() and header_replace2() to remove and replace a certain header of a given name referenced by the count ID. For example:

cookies=HTTP:header_get_values("Set-Cookie")

for k, v in pairs(cookies) do

debug("include cookie %s cnt %d\n", k, v)

end

if HTTP:header_remove2("Set-Cookie", 1) then

debug("remove 1st cookie\n")

end

header_insert(header_name, value) Inserts the named HTTP header(s) and value(s) into the end of the HTTP request or response. For example:

HTTP:header_insert("Cookie", "cookie=server1")

header_replace(header_name, value) Replaces the value of the last occurrence of the header named <header_name> with the string <value>. Performs a header insertion if the header is not present. For example:

HTTP:header_replace("Host", "www.fortinet.com")

header_replace2(header_name, value,countid) header_get_values() returns a count ID for each item. This count ID can be used in both header_remove2() and header_replace2() to remove and replace a certain header of a given name referenced by the count ID. For example:

cookies=HTTP:header_get_values("Set-Cookie")

for k, v in pairs(cookies) do

debug("include cookie %s cnt %d\n", k, v)

end

if HTTP:header_replace2("Set-Cookie", "new2=value2", 2) then

debug("replace 2nd cookie by new2=value2\n")

end

header_exists(header_name) Returns true if the named header is present and not empty on the request or response. For example:

if HTTP:header_exists("Cookie") then

end

header_count(header_name) Returns the number of HTTP headers present in the request or response. For example:

count = HTTP:header_count("Cookie")

method_get() Return the string of the HTTP request method. For example:

method = HTTP:method_get()

method_set(string) Set the HTTP request method to the string "value". For example:

HTTP:method_set("POST")

path_get() Returns the path part of the HTTP request. For example:

path = HTTP:path_get()

path_set(string) Sets the path part of the HTTP request. The client will not see the update unless the web application uses the requested path to generate response headers and/or content. If you want the client to see the update to the path in the browser's address bar, you can send an HTTP redirect using HTTP:redirect or HTTP:respond. For example:

HTTP:path_set("/other.html")

uri_get() Returns the URI given in the request. For example:

uri = HTTP:uri_get()

uri_set(string) Changes the URI passed to the server. It should always start with a slash. For example:

HTTP:uri_set("/index.html?value=xxxx")

query_get() Returns the query part of the HTTP request. For example:

query = HTTP:query_get()

query_set(string) Sets the query part of the HTTP request. For example:

HTTP:query_set("value=xxx")

redirect(“URL”, …) Redirects an HTTP request or response to the specified URL. For example:

Host = HTTP:header_get_value("host")

Path = HTTP:path_get()

HTTP:redirect("https://%s%s", Host, Path)

redirect_with_cookie(URL, cookie) Redirects an HTTP request or response to the specified URL with Cookie. For example:

HTTP:redirect_with_cookie(“www.example.com”, “server=nginx”)

redirect_t Redirects an HTTP request or response to the URL specified in the table. For example:

a={}

a["url"]="http://192.168.1.7"

a["code"]="303"

a["cookie"]="test=server"

HTTP:redirect_t(a)

version_get() Returns the HTTP version of the request or response. For example:

vers = HTTP:version_get()

version_set(string) Sets the HTTP version of the request or response. For example:

HTTP:version_set("1.0")

status_code_get() Returns the response status code output as string. For example:

responsestatus=HTTP:status_code_get()

status_code_set(string) Sets the response status code. For example:

HTTP:status_code_set("301")

code_get() Returns the response status code,output as integer. For example:

responsestatus=HTTP:code_get()

code_set(integer) Sets the response status code. For example:

HTTP:code_set(301)

reason_get() Returns the response reason. For example:

HTTP:reason_get()

reason_set(string) Sets the response reason. For example:

HTTP:reason_set(string)

rand_id() Returns a random string of 32-long in hex format, which can be inserted directly as an HTTP header. For example:

ID=HTTP:rand_id()

HTTP:header_insert("Message-ID", ID)

client_addr() Returns the client IP address of a connection for an HTTP_REQUEST packet, which is the source address for the HTTP_REQUEST packet. It's a destination address. For example:

CIP=HTTP:client_addr()

local_addr() For HTTP_REQUEST, returns the IP address of the virtual server the client is connected to; for HTTP_RESPONSE, returns the incoming interface IP address of the return packet. For example:

LIP=HTTP:local_addr()

remote_addr() Returns the IP address of the host on the far end of the connection. For example:

RIP=HTTP:remote_addr()

server_addr() Returns the IP address of the server in HTTP_RESPONSE.

SIP=HTTP:server_addr()

close() Closes an HTTP connection using code 503. For example:

HTTP:close()

client_port() Returns the client port number in a string format. For example:

HTTP:client_port()

local_port() Returns the local port number in a string format. For example:

HTTP:local_port()

remote_port() Returns the remote port number in a string format. For example:

HTTP:local_port()

server_port() Returns the server port number in a string format. For example:

HTTP:server_port()

client_ip_ver() Returns the client IP version number. For example:

HTTP:client_ip_ver()

server_ip_ver() Returns the server IP version number. For example:

HTTP:server_ip_ver()

collect

Collects data. You may specify a specific amount using the length argument. Used in HTTP_REQUEST or HTTP_RESPONSE. For example:

t={};

t["size"]=1000; --optional

HTTP:collect(t);

payload (size)

Returns the size of the buffered content. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE. For example:

t={};

t["operation"]="size"

sz=HTTP:payload(t); --return value is an int

payload (content)

Returns the buffered content in a string. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE. For example:

t={};

t[“operation”]=”content”

t[“offset”]=12; --optional

t[“size”]=20; --optional

ct = HTTP:payload(t); --return value is a string

payload (set)

Replaces the buffered data with new data. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE.For example:

t={};

t[“operation”]=”set”

t[“offset”]=12; --optional

t[“size”]=20; --optional

t[“data”]= ”new data to insert”;

ret = HTTP:payload(t); --returns true if operation succeeds

payload (find)

Searches for a particular string in the buffered data. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE.For example:

t={};

t[“operation”]=”find”

t[“data”]=”sth”; -- can also be a regular expression, like (s.h)

t[“offset”]=12; --optional

t[“size”]=20; --optional

t[“scope”]=”first” -- the scope field can be either “first” or “all”

ct = HTTP:payload(t); --returns the number of occurences found

payload (remove)

Removes a particular string from the buffered data. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE.For example:

t={};

t[“operation”]=”remove”

t[“data”]=”sth”; -- can also be a regular expression, like (s.h)

t[“offset”]=12;

t[“size”]=20;

t[“scope”]=”first” -- or “all”

ct = HTTP:payload(t); --returns number of occurrences removed

payload (replace)

Replaces a particular string or regular expression with a new string. Used in HTTP_DATA_REQUEST or HTTP_DATA_RESPONSE. For example:

t={};

t[“operation”]=”replace”

t[“data”]=”sth”; -- can be a regular expression, like (s.h)

t[“new_data”]=”sth new”;

t[“offset”]=12; --optional

t[“size”]=20; --optional

t[“scope”]=”first” -- or “all”

ct = HTTP:payload(t); --returns number of occurrences replaced

set_event

Sets a request or response event. For example:

t={};

t["event"] = "data_res"; --can be req,res,data_req, or data_res

t["operation"] = "disable";

HTTP:set_event(t)

set_auto

Sets an automatic request or response event. For example:

t={};

t["event"] = "data_res"; --can be req, res, data_req, or data_res

t["operation"] = "disable";

HTTP:set_auto(t)

lookup_tbl

Input a hash value to look up the persistence session table and dispatches it in ADC if the hash value matches the one in the persistence table.

t[“hash_value”] = “hash”

persist

HTTP:persist() : (operate in PERSISTENCE and POST_PERSIST)

  1. Operation #1. Save the entry to stick table:
  2. Input:

    t[“operation”] = “save_tbl”

    t[“hash_value”] = “hash”

    t[“srv_name”]= “srv name”

    Output:

    true: success, false: failed

  3. Operation #2. Read the tbl entry:
  4. Input:

    t[“operation”] = “read_tbl”

    t[“hash_value”] = “hash”

    Output:

    server name of the entry, or false if no entry found

  5. Operation #3. Dump the tbl entry:
  6. Input

    t[“operation”] = “dump_tbl”

    t[“index”] = 50

    t[“count”] = 1000

    Output:

    A table include hash and server name

  7. Operation #4. Get the list o freal server and status:
  8. Input

    t[“operation”] = “get_valid_server”

    Output

    Return the table of usable real server and server state(enable, disable, maintain, backup)

  9. Operation #5 Calculate the real server from hash:
  10. Input

    t[“operation”] = “cal_server_from_hash”

    t[“hash_value”] = “hash”

    Output

    Return the real server name according to the hash value using our algorithm or False if failed.

  11. Operation #6. Get the real server currently assigned to this session:
  12. Input

    t[“operation”] = “get_current_assigned_server”

    Output

    Return the real server name which is assigned to current session or False if no server is assigned right now.

Load Balance
routing(content_route) Selects a content route. For example:

LB:routing("content2")

TCP
reject()

Allow you to reject a TCP connection from a client. Can be used in TCP_ACCEPTED event. For example:

when TCP_ACCEPTED {

--Check if the st is true or false

if st then

TCP:reject();

end }

set_snat_ip(str)

Allows user to set the backend TCP connection's source address and port. For example:

when TCP_ACCEPTED {

addr_group = "172.24.172.60/32"

client_ip = IP:client_addr()

matched = cmp_addr(client_ip, addr_group)

if matched then

if TCP:set_snat_ip("10.106.3.124") then

debug("set SNAT ip to 10.106.3.124\n");

end

end }

clear_snat_ip()

Allows you to clear whatever customized ip you ever set using set_snat_ip(). For example:

when TCP_ACCEPTED {

if TCP:clear_snat_ip() then

debug("Clear SNAT IP !\n");

end }

sockopt(t)

Allows user to customize the send buffer and receive buffer size. For example:

when VS_LISTENER_BIND {

local t = {};

t["op"] = "get";

t["message"] = "snd_buf" --"snd_buf" or "rcv_buf"

if TCP:sockopt(t) then

debug("tcp send buffer is %d\n", tcp_snd_buf);

else

debug("get tcp send buffer failed\n");

end }

SSL
version()

Allows you to GET the SSL version, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

ver=SSL:version();

cipher()

Allows you to GET the SSL cipher, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

ci=SSL:cipher();

alg_keysize()

Allows you to GET the SSL key size, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

alg_keysize=SSL:alg_keysize()

npn()

Allows you to GET the SSL NPN extension, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

npn=SSL:npn();

alpn

Allows you to GET the SSL ALPN extension, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

alpn=SSL:alpn();

sni()

Allows you to GET the SSL SNI, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

sni=SSL:sni();

client_cert()

Returns the client certificate status, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

client_cert=SSL:client_cert()

session(t)

Allows you to GET SSL session id / Reused / Remove from cache, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

t={}

t["operation"]="get_id"--or "remove" "reused"

sess_id=SSL:session(t);

if sess_id then

sess_id=to_HEX(sess_id)

debug("client sess id %s\n", sess_id);

else

sess_id="FALSE"

end

cert(t)

Allows you to GET the cert info between local or remote, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example:

t={} t["direction"]="remote";--or "local"

t["operation"]="count";-- or "index", or "issuer"

cert=SSL:cert(t)

if cert then

debug("has %s certs\n", cert)

else

debug("no cert\n")

end

peer_cert(str)

Returns the peer certificate, can be used in CLIENTSSL_HANDSHAKE / SERVERSSL_HANDSHAKE / CLIENTSSL_RENEGOTIATE / SERVERSSL_RENEGOTIATE event. For example

cder=SSL:peer_cert("der");--for remote leaf certificate, the input parameter can be "info" or "der" or "pem".

if cder then

hash=sha1_hex_str(cder);

debug("whole cert sha1 hash is %s\n", hash);

end

IP
client_addr()

Returns the client IP address, can be used in all events except VS_LISTENER_BIND. For example:

cip=IP:client_addr()

local_addr()

Returns the local IP address, can be used in all events except VS_LISTENER_BIND / SERVER_BEFORE_CONNECT. For example:

lip=IP:local_addr()

remote_addr()

Returns the remote IP address, can be used in all events except VS_LISTENER_BIND / SERVER_BEFORE_CONNECT. For example:

rip=IP:remote_addr()

client_port()

Returns the client IP port number, can be used in all events except VS_LISTENER_BIND. For example:

cp=IP:client_port()

local_port()

Returns the local port number, can be used in all events except VS_LISTENER_BIND / SERVER_BEFORE_CONNECT. For example:

lp=IP:local_port()

remote_port()

Returns the remote port number can be used in all events except VS_LISTENER_BIND / SERVER_BEFORE_CONNECT. For example:

rp=IP:remote_port()

client_ip_ver()

Returns the client IP version, can be used in all events except VS_LISTENER_BIND. For example:

cipv=IP:client_ip_ver();

server_addr()

Returns the server IP address, can be used in server-side events. For example:

sip=IP:server_addr()

server_port()

Returns the server port number, can be used in server-side events. For example:

sp=IP:server_port()

server_ip_ver()

Returns the server IP version, can be used in server-side events. For example:

sipv=IP:server_ip_ver();

Management
get_session_id()

Returns the session id, can be used in all events except VS_LISTENER_BIND. For example:

sid=MGM:get_session_id()

debug("sess id %s\n", sid);

rand_id()

Returns the rand id, can be used in all events except VS_LISTENER_BIND. For example:

sid=MGM:get_session_id()

debug("rand id %s\n", rid);

set_event(t)

Allow user to disable/enable rest of theevents from executing by disabling this event. For example:

t={};

t["event"]="req"; -- can be "req", "res", "data_req", "data_res", "ssl_client", "ssl_server", "tcp_accept", "tcp_close", "ssl_renego_client", "ssl_renego_server", "server_connected", "server_close", "server_before_connect", "vs_listener_bind", "auth_result", "cookie_bake"

t["operation"]="disable"; -- can be "enable", and "disable"

MGM:set_event(t);

debug("disable rest of the HTTP_REQUEST events\n");

set_auto(t)

Allow user to enable/disable automatic re-enabling. For example:

t={};

t["event"]="req"; -- can be "req", "res", "data_req", "data_res", "ssl_server", "ssl_renego_server", "server_connected", "server_close", "server_before_connect" t["operation"]="disable"; -- can be "enable", and "disable"

MGM:set_auto(t);

debug("disable automatic re-enabling of the HTTP_REQUEST events\n");

Auth
get_baked_cookie()

Allows you to retrieve the baked cookie, For example:

when COOKIE_BAKE { cookie = AUTH:get_baked_cookie() debug("baked cookie %s\n", cookie); }

set_baked_cookie(cookie)

Allows you to customize cookie attributes the baked cookie, For example:

when COOKIE_BAKE { cookie = AUTH:get_baked_cookie() --add new attribute HttpOnly new_cookie = cookie.."; HttpOnly"; AUTH:set_baked_cookie(new_cookie); }

on_off()

Returns the authentication is required or not, For example:

on_off = AUTH:on_off();

success()

Returns the authentication is successful or not, For example:

succ = AUTH:success();

form_based()

Returns the authentication is HTTP form based or not , For example:

fm = AUTH:form_based()

user()

Returns the authentication of the user name , For

example:user = AUTH:user()

pass()

Returns the authentication of the password , For

example:pass = AUTH:pass()

usergroup()

Returns the authentication of the user group , For

example:userg = AUTH:usergroup()

realm()

Returns the authentication of the realm , For

example:userg = AUTH:usergroup()

host()

Returns the authentication of the host , For

example:host = AUTH:host()

Proxy
set_auth_key(str)

Allows user to customize the crypto key FADC used for encrypt/decrypt authentication cookie, For example:

when VS_LISTENER_BIND {

AUTH_KEY = ""0123456789ABCDEF0123456789ABCDEF""

if PROXY:set_auth_key(AUTH_KEY) then

debug(""set auth key succeed\n"");

end

}

Init_stick_tbl_timeout()

Allow user to set the timeout of stick table for persistence.

when RULE_INIT{

env={}

PROXY:init_stick_tbl_timeout(500)

}