What is the lease-script?

It’s a field of the DHCP server (/ip dhcp-server) where you write a small RouterOS script. The router runs it at two moments:

  • when it assigns an address to a client (a “bound” lease);
  • when the lease is freed, because the client released it or because it expired.

And when the client renews? Nothing: I tested it in the lab with a 2-minute lease, the client renewed every minute, and the script stayed quiet. Good news: you don’t get an alert on every renewal, only when a device actually comes or goes.

Inside the script you already have these variables ready to use:

  • $leaseBound: it’s 1 when the address is assigned, 0 when it’s freed or expires;
  • $leaseServerName: the name of the DHCP server;
  • $leaseActMAC: the client’s MAC address;
  • $leaseActIP: the IP address of the lease;
  • $"lease-hostname": the name the client declared, if it declared one (the hyphen forces you to write it in quotes);
  • $"lease-options": the DHCP options sent to the client, indexed by option number;
  • $"lease-agent-circuit-id" and $"lease-agent-remote-id": the switch and port the client comes from, when the request goes through a relay or a switch with Option 82.

The full list of server properties, lease-script included, is in the MikroTik manual: DHCP Server Properties.

Diagram: a device asking the MikroTik's DHCP server for an address, the lease-script sending an alert and updating an address list
On every new assignment the DHCP server runs the script: it can warn you, or give the client timed access.

Step 1: which DHCP server am I working on?

The script attaches to a specific DHCP server. Look at what yours are called:

/ip dhcp-server print

In the examples the server is called dhcp-lan: swap the name for yours. If you have several servers (LAN, guests, cameras), each one has its own lease-script.

Step 2: how do I test it without breaking anything?

With a script that does nothing but write to the log. It’s the “mic check” of the lease-script:

/ip dhcp-server set [find name=dhcp-lan] lease-script={
    :if ($leaseBound = 1) do={
        :log info ("DHCP " . $leaseServerName . ": assigned " . $leaseActIP . " to " . $leaseActMAC . " (" . $"lease-hostname" . ")")
    } else={
        :log info ("DHCP " . $leaseServerName . ": released " . $leaseActIP . " from " . $leaseActMAC)
    }
}

Disconnect and reconnect a device, then look at the log:

/log print where topics~"script"

In the lab, unplugging and plugging a Linux PC back in, this came out:

script,info DHCP dhcp-lan: released 192.168.88.199 from 50:00:00:1E:00:00
script,info DHCP dhcp-lan: assigned 192.168.88.199 to 50:00:00:1E:00:00 (pc7a)

Step 3: how do I get an alert when a new device joins?

The idea: the devices you know about have a static lease, the ones you don’t know don’t. The script alerts you only for the latter. First, though, the router needs to know how to send mail: there’s a dedicated howto on sending email from MikroTik with Gmail.

/ip dhcp-server set [find name=dhcp-lan] lease-script={
    :if ($leaseBound = 1) do={
        :local noto [/ip dhcp-server lease find where mac-address=$leaseActMAC and dynamic=no]
        :if ([:len $noto] = 0) do={
            :log warning ("Unknown device: " . $leaseActMAC . " " . $leaseActIP)
            /tool e-mail send to="admin@example.com" subject=("New device on the LAN: " . $leaseActMAC) \
                body=("IP " . $leaseActIP . ", name " . $"lease-hostname" . ", server " . $leaseServerName)
        }
    }
}

Change admin@example.com to your own address. The log line stays even if the mail doesn’t go out: it’s your reminder.

Step 4: how do I make a device “known”?

By turning its lease into a static one. From that point on the script recognizes it and stops flagging it:

/ip dhcp-server lease make-static [find where mac-address="AA:BB:CC:DD:EE:FF"]
/ip dhcp-server lease print where dynamic=no

From WinBox it’s even quicker: IP → DHCP Server → Leases, right-click the lease and Make Static.

⚠️ Heads up: many smartphones use a random MAC address for each Wi-Fi network. It usually stays the same as long as the phone connects to the same network, but if the user regenerates it from the settings, to the router it’s a new device and the script flags it again.

Step 5: how do I give a client temporary access?

This was the idea in the original article: open a service for a few minutes to each new client, for example a social login on the hotspot. In RouterOS 7 the right tool is the address list with a timeout: the address disappears on its own when the time runs out, with no second script to remove it.

/ip dhcp-server set [find name=dhcp-ospiti] lease-script={
    :if ($leaseBound = 1) do={
        /ip firewall address-list add list=accesso-temporaneo address=$leaseActIP \
            timeout=10m comment=$leaseActMAC
    } else={
        /ip firewall address-list remove [find list=accesso-temporaneo address=$leaseActIP]
    }
}

Check that the client lands in the list:

/ip firewall address-list print where list=accesso-temporaneo

The client shows up as a dynamic entry, with the timeout counting down and its MAC in the comment. At that point a firewall or walled-garden rule can use src-address-list=accesso-temporaneo: on the hotspot, for example, you can open a site only to the clients that are in the list.

Step 6: how do I find out if the script has an error?

Lease-script errors don’t show on screen: they end up in the log. For example, the script from Step 3 on a router with no mail configured leaves these lines:

script,warning Unknown device: 50:00:00:1E:00:00 192.168.88.199
e-mail,error Error sending e-mail <New device on the LAN: 50:00:00:1E:00:00>: error connecting to server
script,error executing script from dhcp failed, please check it manually

The command to find them:

/log print where topics~"script" or topics~"e-mail"

Three rules to keep from hurting yourself:

  • no slow operations: the script runs while the server is handling the client;
  • always test first with :log, as in Step 2, and only then add mail or firewall;
  • the $lease… variables exist only inside the lease-script: in any other script they’re empty.

Step 7: what do I check before putting it into production?

A lease-script that sends mail or touches the firewall lives on a router that must already be protected. If you haven’t done it yet, follow the Basic hardening of a MikroTik router: a user other than admin, limited services, a firewall facing the internet.

Tested in the lab on PNETLab with a CHR running RouterOS 7.24.5 (stable) and a Linux client: the script in the log, an alert for unknown MACs, make-static, an address list with a timeout, and no execution on lease renewals.

Frequently asked questions

When does the MikroTik DHCP server’s lease-script run?

When the DHCP server assigns an address to a client and when a lease is freed or expires. The $leaseBound variable is 1 in the first case and 0 in the second.

Does the lease-script also run when the client renews the lease?

No. In the lab, on RouterOS 7.24.5, with a 2-minute lease the client renewed every minute and the script never ran: it runs only on assignment and on release or expiry.

How do I read the device name in the lease-script?

The name the client declares is in the $"lease-hostname" variable, which you write in quotes because of the hyphen. It can be empty: not every device sends it.

Can I send an email from a lease-script?

Yes, with /tool e-mail send, after configuring the router’s SMTP server. It’s best to filter the cases where you send it, for example only for unknown MACs; if the mail doesn’t go out, the error ends up in the log.

How do I automatically remove a client from the address list?

By adding it with a timeout, for example timeout=10m: when the time runs out RouterOS removes the entry on its own, with no need for other scripts.

This howto updates to RouterOS 7 a 2015 article from my old blog wirelessguru.it, now offline.