HSL code examples

From Halon, SMTP software for hosting providers
Revision as of 09:11, 19 June 2017 by Erik (talk | contribs) (Distribution list)
Jump to: navigation, search

Below is a smorgasbord with some script examples you may find useful. For more information about HSL, please see the reference manual.


These scripts may be used in all flows.

Notification limit

On certain events it may be useful to eg. send a mail notification, however if these messages aren't rate-limited you may end up with huge amounts of notifications. Here are two ways of limiting notifications by time, non of which is better but serves different purposes.

if (true) {
// this example sends one mail per hour for every unique function arguments.
cache "ttl" => 3600 ]
mail("""[email protected]""Event occurred""An event occurred"); 
if (true) {
// this example sends one mail per hour (based on the event1 rate).
if (rate("notification""event1"13600))
mail("""[email protected]""Event occurred""An event occurred"); 

Clustered lookup cache

It's possible to query the rate function for the number of entries (implementing a lookup cache), which could be used to implement eg. a SASL authentication cache shared in a cluster.

$ttl 3600;
if (
rate("sasl-cache"$saslusername ":" sha1($saslpassword), 0$ttl))
if (
$saslusername == "username" and $saslpassword == "secret") {
rate("sasl-cache"$saslusername ":" sha1($saslpassword), 1$ttl);

IP flow

These scripts may be used in IP flows.

Black and white list

// White list: check if $senderip is in any of the networks..
$network = [""""];
foreach (
$network as $net) {
    if (
in_network($senderip$net)) {

// Black list: check if $senderip is in any of the networks..
$network = [""];
foreach (
$network as $net) {
    if (
in_network($senderip$net)) {


if (count(dnsbl($senderip,"zen.spamhaus.org")))
Block("$senderip blocked by Spamhaus");
if (
Block("$senderip blocked by SpamCop"); 

RCPT TO flow

These examples can be used in the flows executing MAIL FROM/RCPT TO combinations.

External black/whitelist using API

This example shows how to implement a black and whitelist as a web service in PHP and use that data in the SP as a black/whitelist passing the data using JSON.


= [];
$whitelist = ["[email protected]""example.org"];
json_encode(["blacklist" => $blacklist"whitelist" => $whitelist]); 

json data:

{"blacklist":[], "whitelist":["[email protected]", "example.org"]}


$list json_decode(http("http://api.example.com/bwlist.php", ["timeout" => 10])); // TODO: use cache

if (is_array($list) and is_array($list["whitelist"])) {
    foreach (
$list["whitelist"] as $item) {
        if (
$senderip == $itemAccept();
        if (
$senderdomain == $itemAccept();
        if (
$sender == $itemAccept();

if (
is_array($list) and is_array($list["blacklist"])) {
    foreach (
$list["blacklist"] as $item) {
        if (
$senderip == $itemReject("Blacklisted");
        if (
$senderdomain == $itemReject("Blacklisted");
        if (
$sender == $itemReject("Blacklisted");


Greylisting is a technique to prevent custom/non-compliant spam software/bots to send messages on the first try, thus requiring a server implementations with proper queuing.

function greylist($triplet$time) {

// $sendernet (network/24) can be replaced with $senderip
$sendernet implode("."explode("."$senderip)[0:3]);
$triplet "$sendernet:$sender:$recipient";

// time recommendations from http://en.wikipedia.org/wiki/Greylisting
$windowopen 24;                   // Greylist time (24 minutes)
$windowclose 60 4;              // Greylist time end (4 hours)
$windowtime 60 24 14;         // Skip greylist time (14 days)
$slot cache ["size" => 1000000,
"ttl" => ($windowclose 60),
"argv_filter" => [1] ]
greylist(md5($triplet), uptime() + ($windowopen 60));
if (
$slot == 0)
"Greylist, ok";
else if (
$slot <= uptime()) {
"Greylist, pass";
cache ["size" => 1000000,
"ttl" => ($windowtime 60),
"argv_filter" => [1],
"force" => true]
greylist(md5($triplet), 0);
} else
Defer("Greylisted, please try again in ".round($slot-uptime(), 0)." seconds"); 

Outbound rate control based on failed deliveries

One indication of outbound messages being spam, is that other server reject them. Put the following code in the post-delivery (transport) flow

if ($transportid == "mailtransport:2"// whichever is the outbound (lookup-mx) transport
if ($errorcode >= 500)

and the following in the outbound RCPT TO flow:

if (rate("delivery-fail"$sender03600) > 100)
Defer("You have more than 100 failed deliveries the last hour, try again later"); 

Concurrency control for smtp_lookup_rcpt

function smtp_lookup_rcpt(...$argv) {
barrier "smtp_lookup_rcpt" => $var {
        if (!isset(
$var)) {
$var = [];
        if (
$unique $argv[0];
$unique $argv[0]["host"];
        if (!isset(
$var[$unique])) {
$var[$unique] = 0;
        if (
$var[$unique] >= 3) {
            if (
$argv[3]["error_code"] == true) {
                return [
"error_code" => 400,
"error_message" => "Too many concurrent lookups"
            return -
$var[$unique] += 1;
$result builtin smtp_lookup_rcpt(...$argv);
barrier "smtp_lookup_rcpt" => $var {
$var[$unique] -= 1;

DATA flow

These scripts may be used in DATA flows; processing the actual mail message.

Distribution list

This example shows how to create a simple mail distribution list with JSON API integration. Add a custom/fictional domain (eg. notify). Add a custom flow

if ($_GET['key'] === 'secretkey') {
$mail = [];
$mail[] = '[email protected]'// fetch from database
$mail[] = '[email protected]'// fetch from database
if ($senderip == "" and $sender == "[email protected]") {
$mail json_decode(http("https://api.example.com/notifications/?key=secretkey"));
SetSender("[email protected]");
SetDelayedDeliver(300); // "whops"-protection
foreach ($mail as $e) {
SetHeader("From""Example company <[email protected]>");
Reject("Message sent to ".count($mail)." users!");
Reject("Not allowed"); 

Prevent getting blacklisted by using a dedicated "spam" source IP

  1. Add an extra IP address (for each cluster node)
  2. Add an outbound (lookup-mx) transport with that source address
  3. Add the script below to the outbound DATA flow
if (ScanRPD() > or ScanSA() > 2)
SetMailTransport(“mailtransport:X”); // with X being the transport added above 

DSN bypass (rate)

Deliver (possible without scanning) DSN messages (in this example, if receiving more than 10 DSN / 5 minutes, only do a Deliver). Good if you do regularly large send out and are expecting bounces.

if ($sender == "" and rate("dsn-bypass"$recipient10300) == false) {
"DSN bypass";

Manually review high-volume email

Place this script in the very end of the DATA flow, to delay the 20th+ delivery (during one hour) of messages with identical subject lines. These can be listed on the Activity > Rate limit page, and reviewed by searching for them using the filter


on the Activity > Tracking page. In some occasions, this can be spam, and thus deleted.

function is_news($senderdomain) {
$news = [
    foreach (
$news as $domain)
        if (

$subject GetHeader("subject"false);
if (
$subject and
cache ["ttl" => 3600"size" => 20000is_news($senderdomain) and 
rate("delayed-review"$subject[0:40], 20003600) and
rate("delayed-review"$subject[0:40], 03600) > 20) {
    if (
mail("""[email protected]""Review delayed messages""Please do it");

Check total process time of a message

executiontime() only tells the current recipients process time, to check total process time of a message (for all recipients). The following script may be used.

$beginprocess cache ["per_message" => trueuptime();
// do processing...
echo (uptime() - $beginprocess) . " total process time"

Check if sender domain exists

Check if Sender Domain exists; if not delete the mail.

if ($senderdomain != "" and !dns($senderdomain) and !dnsmx($senderdomain))
Reject("$senderdomain doesn't exist"); 

White list sender domain

This is how a white list could be written. Below follows two examples, the first using string compare and second using regular expressions.

$whitelist = ["halonsecurity.com""halon.se""example.org"];
if (

Example using regular expressions against $sender.

$whitelist = ["@halonsecurity\\.com$""@halon\\.se$""@example\\.org$"];
foreach (
$whitelist as $host)
   if (
$sender =~ $host)

Be aware of that you have to escape the dots in the host with \\., or else the dot will match any character.


Put the following code in your outbound data flow to enable bi-directional whitelist.

// auto-whitelist
if ($sender != "" and $sender != $recipient)

and the following in the inbound data flow to check if recipient sent an mail to sender within the last 24 hours.

// check if sender and recipient is in the auto-whitelist
if (rate("auto-whitelist"$sender."->".$recipient086400) > 0) {
"Sender is whitelisted";

Add headers


Limit number of recipient addresses allowed per domain

We generally recommend using the http() function to query external data sources when implementing business logic such as this, but in case you want to design a pure HSL script which limits the number of users to scan on a domain basis, the following script should work.

$maxusers in_file($recipientdomain"file:1");
if (
$maxusers $maxusers[1];
$maxusers 5;

barrier "user-count" => $var {
    if (!isset(
$var = [];
    if (!isset(
$var[$recipientdomain] = [];
$mbox explode("@"$recipient)[0];
    if (!
$var[$recipientdomain][] = $mbox;
    if (
count($var[$recipientdomain]) > number($maxusers))
"Exceeding user count";

Support/collaboration script

This script makes sure support or sales addresses always reaches everyone in the distribution group.

// Inbound
function DoInCC($address) {
    if (
$recipient == $address and GetHeader("References") == "")
DoInCC("[email protected]");
DoInCC("[email protected]");

// Outbound
function DoOutCC($address$name$transport) {
    if (
GetHeader("References") =~ "-cc-$address>") {
SetHeader("from""$name  <$address>");
DoOutCC("[email protected]""Example Sales""mailtransport:X");
DoOutCC("[email protected]""Example Sales""mailtransport:X"); 

Verify sender "HELO" hostname

This example will check if the senders HELO message does resolve back to his IP.

if (!in_array($senderipdns($senderhelo)))
"Provided HELO message does not resolve to sender IP, this is suspicious"

Log all mail messages sent out not during office hours

Since you don't expect anyone to send out mail during the night, you may want to explicit log all sent mail. This of course only makes sense when using the flow for outgoing traffic.

// Code executed between 17:00 and 6:59
$time number(strftime("%H"));
if (
$time 16 or $time 7)
"$senderip tried to send a mail to $recipient (from $sender)"

DSN Spam Protection

Delete the message if it is a DSN (delivery status notification) but not sent directly from your outgoing mail server (*.example.com).

$dsn GetDSN();
if (
$dsn["route"][1] =~ "\\.example\\.com") {
"DSN Spam; Deleted Message from $sender to $recipient";