Syed Jahanzaib Personal Blog to Share Knowledge !

August 10, 2022

CallMeBot: Sending Alerts to Various Messaging Apps using APi

Filed under: Linux Related, Mikrotik Related — Tags: , , , , , — Syed Jahanzaib / Pinochio~:) @ 11:00 AM

At multiple ISP’s or networks, I use either GSM Modems or 3rd party SMS API to send various information / alerts messages to admin or users , & it involves minor cost on a per sms basis or as bundle. Another method to send messages on WHATSAPP & its FREE , very simple to use CALLMEBOT APi’s. Its a online FREE service via which you can send basic messages to multiple messaging services like WhatsApp / messenger / Signal / Telegram apps.  The only caveat is that you cannot send messages to EVERY contact. The receiver contact must have the callmebot API KEY , which he can easily get via adding callmebot number in there contact list & send particular message & he will get it instantly. so EACH API EKY is tagged with that particular mobile number only. Once you know the key & its tagged mobile number, you can send message to that contact using the API_KEY & his mobile number using various methods.

In this guide we will be using callmebot API to send various test message to admin WhatsAPP number. Follow the below steps …

  • First, You need to get the API key form the CallMeBot. Add the phone number +34 644 91 96 80 into your Phone Contacts. (Name it it as you wish like CallMeBoT / My_Alerts etc )
  • Using WhatsApp, Send this message to this contact

I allow callmebot to send me messages

  • once it is sent, Wait until you receive the message like “API Activated for your phone number. Your APIKEY is XXXXXX” from the bot. Note down the APIKEY
    Note: If you don’t receive the ApiKey in 2 minutes, please try again after 24hs.
  • The WhatsApp message from the CallMeBot will contain the API key needed to send messages using various API.
  • Now You can send text messages using the API after receiving the confirmation.

Following are few methods, which I am using to send various informational/warning/critical messages to Admin whatsapp

Send message using Browser HTTP APi:

Using browser, you can send message by using below

(As always, change the Phone/APiKey)

Example Message:

Linux Examples:

CMD: on Terminal/shell

(As always, change the Phone/APiKey)

curl --insecure ''

Example Message:

Linux Bash Script Example using separate Text file as attachment

(As always, change the Phone/APiKey)

# DAILY SMS SCRIPT FOR whatsapp MSG Testing
# Script by Syed Jahanzaib /
# Version 2.0 -
# Created in year 2013
# Last modified 20-NOV-2017
set -x
logger DAILY 8 am sms executed for whatsapp testing
#ntpdate -u
> $TMP
# Jahanzaib Cell # CHANGE CELL AS PER YOUR's
UPTIME=`uptime | awk -F'( |,|:)+' '{if ($7=="min") m=$6; else {if ($7~/^day/) {d=$6;h=$8;m=$9} else {h=$6;m=$7}}} {print d+0,"days,",h+0,"hours,",m+0,"minutes"}'`
FOOTER="Powered By Jz"
# Print total and each vlan users
MSG="$COMPANY - Msg Test !
Daily Msg Test @
echo "$MSG" > $TMP
cat $TMP

# Finally SEND MSG to whatsapp using CALLMEBOT
curl --insecure "$CELL1&apikey=$API_KEY" -G --data-urlencode text@$TMP

rm $TMP

Example Message:

Mikrotik RouterOS Example:


(As always, change the Phone/APiKey)

/tool fetch http-method=get mode=https url="\?&apikey=123123&phone=+923333021909&text=Mikrotik+Router+Whatsapp+Msg+Example+SJZ"

Example Message:

Mikrotik DUDE (for Windows) Example:

First download the windows base WGET utility, copy it in any local folder of dude server. & now add notification like this

On DUDE App, Goto Notifications, Click on + ICON to add new notification, a new popup will appear, fill it as per below

Name: Whatsapp2Zaib
Enabled: Ticked
Type: Execute on Server
& in Command Window section, use below cmd

(As always, change the Phone/APiKey)

C:\wget\wget.exe --no-check-certificate " [Probe.Name] on [Device.Name] is now [Service.Status] ([Service.ProblemDescription])"

Example Message:

Hope it Helps !

Syed Jahanzaib

August 27, 2021

NAT types for console | a horror tale for gamers behind NAT

Filed under: Mikrotik Related — Tags: , , , — Syed Jahanzaib / Pinochio~:) @ 4:55 PM

First of all, **What is NAT?**

Network Address Translation (NAT) is designed for IP address conservation. It enables private IP networks that use unregistered IP addresses to connect to the Internet. NAT operates on a router, usually connecting two networks together, and translates the private (not globally unique) addresses in the internal network into legal addresses, before packets are forwarded to another network.

As part of this capability, NAT can be configured to advertise only one address for the entire network to the outside world. This provides additional security by effectively hiding the entire internal network behind that address. NAT offers the dual functions of security and address conservation and is typically implemented in remote-access environments.

Basically, NAT allows a single device, such as a router, to act as an agent between the Internet (or public network) and a local network (or private network), which means that only a single unique IP address is required to represent an entire group of computers to anything outside their network.

Moving on, the 3 NAT types, when concerning gaming consoles/PCs, PS3/PS4, or the Xbox 360/Xbox One, are

  1. Open (Type 1)
  2. Moderate (Type 2) &
  3. Strict NAT (Type 3)

NAT1 is a direct connection to the internet; all ports are accessible, with no port forwarding rules required. Ultimately, an Open/Type 1 NAT will provide the best connection quality whereas Moderate and Strict NAT restrict the connections between a gaming console or PC. If your internet connection has a public IP address (non-RFC1918, non-RFC6598) on the exterior interface of your home router, you should be able to have your PS4 run in NAT2 mode. If you control the port forwarding on your home router, you should be able to get the PS4 to run in NAT1 mode, even on an internal RFC1918 address.

NAT2 is a single layer of public-to-private conversion, and requires assisted port forwarding to achieve inbound connections to the PS4. The Moderate, Type 2 NAT, as well as Strict, Type 3 NAT, limits the connections that can be created between your gaming console or PC and someone else’s gaming consoles or PCs. Users with Moderate NAT, or type 2 NAT, are only able to connect with other users also having a Moderate NAT type, type 2, or an Open NAT Type, type 1.

NAT3 is two layers of conversion, and usually involves a carrier-grade-NAT device at the ISP, as well as a NAT device at the home, making it nearly impossible to achieve direct inbound connections to the PS4; in NAT3 mode, only server-assisted connections are possible, with each PS4 establishing an outbound connection through the two layers of NAT devices, with centralized servers mediating the PS4-to-PS4 communication. Users with Strict/Type 3 NATs can only connect with other users using an Open/Type 1 NAT.Furthermore, at a smarter NAT 3 setup, If you see an address in on the outside interface of your home router, you’re out of luck; you’re in NAT3 territory, may GOD have mercy on your gameplay 🙂


More to come from the Mikrotik Side …

July 2, 2021

Radius | Disconnect users after service change / user disable

Filed under: Mikrotik Related, Radius Manager — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 8:50 AM

Note for self

In older version of radius manager, when OP disables any user account or change user service package , those changes doesnt take effect until the user disconnect/reconnect. Sometimes user remains connected for days. Back in those days , we made a workaround by creating a mysql trigger and script combination. 

Assuming you have fully functional radius working, along with root access to DB. Save this trigger.sql and import it in mysql radius DB.

Example: mysql -uroot -pMYPASS radius < trigger.sql

Following trigger will check for rm_users table changes, and if it found any changes in the users disable/enable or srvid changes, it will add entry in the rm_kickuserstable & our schedule script will pick the data from there and will act accordingly …

MYSQL > kickuser_trigger

-- Host: localhost Database: radius
-- Server version 5.5.54-0ubuntu0.12.04.1
/*!40103 SET TIME_ZONE='+00:00' */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = '' */ ;
/!50003 CREATE/ /!50017 DEFINER=root@localhost/ /*!50003 TRIGGER kickuser_trigger BEFORE UPDATE ON rm_users
IF NEW.enableuser <> OLD.enableuser THEN
INSERT INTO rm_kickuser (datetime, username, msg) VALUES (NOW(), new.username, new.enableuser);
IF NEW.srvid <> OLD.srvid THEN
INSERT INTO rm_kickuser (datetime, username, msg) VALUES (NOW(), new.username, new.srvid);
END */;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
---- Dumping routines for database 'radius'
-- Dump completed on 2021-07-02 8:24:05

rm_kickuser TABLE

Save following & import it in radius db 

Example: mysql -uroot -pMYPASS radius < rm_kickuser_SQL_DB_Creation.sql

root@radius-zaib:/temp# cat rm_kickuser_SQL_DB_Creation.sql

-- phpMyAdmin SQL Dump
-- version
-- Host: localhost
-- Generation Time: Jun 13, 2016 at 10:32 AM
-- Server version: 5.5.46
-- PHP Version: 5.3.10-1ubuntu3.21
SET time_zone = "+00:00";
/*!40101 SET NAMES utf8 */;
-- Database: `radius`
-- --------------------------------------------------------
-- Table structure for table `rm_kickuser`
`datetime` datetime NOT NULL,
`username` varchar(64) NOT NULL,
`msg` varchar(32) NOT NULL,
-- Dumping data for table `rm_kickuser`


the Script !

Now create the script & schedule it to run every 1 minutes

#set -x
# Following script is made specifically for Dmasoftlab radius manager 4.1.x
# When OP disables any user or change service, it will kick the user so that either disconnects, or his package changes on reconnect
# it requires custom trigger on rm_users table, this script will be schedule to run every minute
# Created: 25-MARCH-2019
# Tested on Ubuntu OS Only
# CHANGE these
currenttime=$(date +%H:%M:%S)
# Add Script start execution entry in the /var/log/syslog to see if the script got executed or not
logger "Kick Disabled/Enabled & Service Change - User poller script Started @ $currenttime by the CRON scheduler ... Powered by SYED.JAHANZAIB"
echo "- Script Start Time - $currenttime"
echo "- Checking Disabled/Enabled Users in $USR_TABLE table ..."
CMD="mysql -u$SQLID --skip-column-names -s -e"
#Table which contain main users information

# Checking if /temp folder is previously present or not . . .
if [ ! -d "$TEMP" ]; then
echo "- INFO: $TEMP folder not found, Creating it now to store logs ..."
mkdir $TEMP
echo -e "- INFO: $TEMP folder is already present to store logs."

# Check if table exists
if [ $($CMD \
"select count(*) from information_schema.tables where \
table_schema='$DB' and table_name='$USR_TABLE';") -eq 1 ]; then
echo "- INFO: $USR_TABLE Table exists ..."
echo "- WARNING: $USR_TABLE Table does not exists ..."
# pull user record
$CMD "use $DB; select username from $USR_TABLE WHERE datetime >= NOW() - INTERVAL $MNT MINUTE;" >> $TMPUSRINFO
if [ ! -s $TMPUSRINFO ]
endtime=$(date +%H:%M:%S)

echo "
- INFO: No User to KICK found in DMA RADIUS MANAGER TABLE '$USR_TABLE' , Sending EXIT signals ...

- Script Ends Here...
- EXITING peacefully...
- Script End Time - $endtime
exit 1
# Apply Count Loop Formula while deleting first line which have junk text
cat $TMPUSRINFO | while read users
username=`echo $users | awk '{print $1}'`
USER_IP=`echo $users | awk '{print $2}'`
ACCTSESID=`$CMD "use $DB; select acctsessionid from radacct where username ='$username' AND acctstoptime is NULL;"`
NAS_IP=`$CMD "use $DB; select nasipaddress from radacct where username ='$username' AND acctstoptime is NULL;"`
NAS_SECRET=`$CMD "use $DB; select secret from nas where nasname = '$NAS_IP' ;"`
if [ -z "$ACCTSESID" ]; then
echo "User Found to KICK: USER: $username , BUT USER IS NOT ONLINE, no action is requiroed ..."
# Print Info on screen
echo " User Found to KICK: USER: $username , IP: $USER_IP, ID: $ACCTSESID, NAS: $NAS_IP @ $currenttime ... KICKING him now ..."
logger " User Found to KICK: USER: $username , IP: $USER_IP, ID: $ACCTSESID, NAS: $NAS_IP @ $currenttime ... KICKING him now ..."
echo " User Found to KICK: USER: $username , IP: $USER_IP, ID: $ACCTSESID, NAS: $NAS_IP @ $currenttime ... KICKING him now ..." >> $KICKUSER_LIST_FILE
#in below cmd, I am using SSH base method to kick the user because there were some issues in routing & NAS was not accepting radclient packets, you may use the radclient method which is better approach
ssh -p 22 admin@ /ppp active remove [find name=$username]
#for pppoe , use below
#echo user-name=$username | radclient -x $NAS_IP:$NAS_COA_PORT disconnect $NAS_SECRET
#for hotspot, enable following line
#echo Framed-IP-Address=$USER_IP | radclient -x -c 1 $NAS_IP:$NAS_COA_PORT disconnect $NAS_SECRET
# once done, we should delete the tmp files to clear the garbage


*** Schedule the script to run every minute

crontab -e

*/1 * * * * /temp/ > /dev/null 2>&1


root@radius-zaib:/temp# ./

- Script Start Time - 08:43:58
- Checking Disabled/Enabled Users in rm_kickuser table ...
- INFO: /temp folder is already present to store logs.
- INFO: rm_kickuser Table exists ...
- INFO: No User to KICK found in DMA RADIUS MANAGER TABLE 'rm_kickuser' , Sending EXIT signals ...

- Script Ends Here...
- EXITING peacefully...
- Script End Time - 08:43:58


Syed Jahanzaib

March 22, 2021

Modifying Expiration Time in Dmasoftlab Radius Manager

Filed under: Mikrotik Related — Tags: , — Syed Jahanzaib / Pinochio~:) @ 8:38 AM

This post is published as a personal reference, It describes a method via which you can modify the user account expiration default time of 00:00:00 to some other time, so that middle night disconnection can be avoided & user can get some time in official hours to recharge there account. with traditional FREERADIUS we can modify the disconnection in RADCHECK table, but since DMA doesn’t defines the expiration there & uses its own authentication module which checks for the user expiration date in RM_USERS table, therefore we have to make little modification to facilitate this option.

Another option is to create TRIGGERS, so that whenever a new user is created, it should modify the time instantly, or add the user name in separate table, and using predefined bash script which can monitor the table and perform action accordingly. lots of options can be opted.

As asked by few network OP’s who are using dmasoftlab radius manager as there billing system & performs manual recharge after getting payment from the users by door to door collection, One of the most annoying issue is the expiration time at which users get disconnected dueto expiration limit expires. By default when a user is created his time is entered in following format

2021-03-20 00:00:00

As a result, as soon as date changes at 00:00:00 hours, the user will be disconnected from the system. which means in the middle of night. Users starts calling OP help desk & most of the time, its difficult to recharge accounts in mid night.

Therefore its better to change the expiration time to happen in official working hours so that both user & OP can have some time to recharge the accounts within office hours.

To automate this process, create a bash script & schedule it to run at 11:50 pm daily. This script will change all users expiration HOURS to your modified time.


Create TEMP folder / script file along with executable permission

mkdir /temp
touch /temp/
chmod +x /temp/
nano /temp/

& paste following contents, make sure to change MYSQL user/password & required expiration hours

# set -x
# BASH base script to change EXPIRATION hours in DMA RADIUS Manager RM_USERS table
# to modify users expiration disconnection time so that middle night disconnection can be avoided
# You can schedule this script to run every XX minutes/hours
# example : in cron use below line , means run at 11:50pm
# 50 23 * * * * /temp/
# By Syed Jahanzaib / aacable at hotmail dot com
# CREATED on : 20th-March-2021

CMD="mysql -u$SQLUSER --skip-column-names -s -e"
# DMA related, below is 8pm. change timings as per your requirements
# R.M Table which contain users expiration information (in freeradius, we use Expiration attribute in radcheck,
# But DMA uses its own authentication module to validate users details from the rm_users table
# Date Related
TODAY=$(date +"%Y-%m-%d")

# Start execution
# Modify the 00:00:00 hours to suite yours local time, I have used 8pm timings as an example

# or you can use single line code here in mysql directly or by $CMD
#UPDATE rm_users SET expiration = DATE_FORMAT(expiration, '%Y-%m-%d $NEW_EXP_TIME');"

# ECHO on screen and also LOG in /var/log/syslog (for ubuntu)
echo "DMASOFTLAB RADIUS MANAGER - User expiration HOURS now changed from $COLUMN_NAME to $NEW_EXP_TIME - Script executed successfully @ $DATE"
logger "DMASOFTLAB RADIUS MANAGER - User expiration HOURS now changed from $COLUMN_NAME to $NEW_EXP_TIME - Script executed successfully @ $DATE"
#Script Ends here

CRON Scheduler:

You can schedule it to run at 23:50 hours daily (this is the default time when dma expires account program runs, so we will modify the cron schedule to modify expiration time just before DMA program runs …

to edit CRON (Task Manager for linux), edit it by using below CMD

crontab -e

Now add below (you can modify it to to run at single time or multiple times as per your need, every 50 minutes of every hour, or likewise)

50 23 * * * /temp/

Syed Jahanzaib

January 21, 2021

Possibilities: Mikrotik PPP Disconnection/Yellow Sign Problems

Filed under: Mikrotik Related — Tags: , , , — Syed Jahanzaib / Pinochio~:) @ 9:58 AM

Disclaimer! This is important!

Every Network is different , so one solution cannot fit/applied to all. Therefore try to understand logics & create/modify the solution as per your network scenario. Do Not follow copy paste blindly.

My humble request is that kindly donot consider me as an expert on this stuff, I am NOT certified in anything Mikrotik/Cisco/Linux or Windows. However I have worked with some core networks and I read , research & try stuff all of the time. So I am not speaking/posting about stuff I am formerly trained in, I pretty much go with experience and what I have learned on my own. And , If I don’t know something then I read & learn all about it.

So , please don’t hold me/my-postings to be always 100 percent correct. I make mistakes just like everybody else. However – I do my best, learn from my mistakes and try to share tips that worked for me.

Tips posted here are based on personal experiences which I faced/sorted at various networks locally/internationally. It is requested to kindly contribute your valuable experience & any tips to help others.
Sharing is Caring …

Syed Jahanzaib~

PPP Common Problems

From some time we were getting following complains from few ISP’s regarding

  • Few websites (like banking) not opening if user is connected via pppoe only
  • User pppoe dial stuck , not able to reach to mikrotik pppoe server
  • User pppoe connectivity frequent/intermittent disconnection/termination
  • User pppoe dialer is connected but yellow mark at user device/workstation , No internet


Try to diagnose the issue one by one by below tips

  1. For few websites not working on pppoe clients only issue , try to add following rule & test
    /ip firewall mangle
    add action=change-mss chain=forward new-mss=clamp-to-pmtu passthrough=yes protocol=tcp tcp-flags=syn
  2. Mikrotik RouterOS Firmwares plays very important roles in the stability in various segments, Try LONG-TERM release. Sometimes upgrading/downgrading rectifies issues without modifying any configuration. Read Mikrotik Forums to see if other users are having similar issues on particular version.
  3. Cheap wifi routers at client end example TPLINK/TENDA are headache to manage. Most of the older models have BUGS from security & stability issues. Always make sure that you dont use buggy routers brands, Always upgrade the Firmwares to latest. This mostly rectifies many issues.
  4. On busy network, always use your local dns (must be reachable with/without pppoe dialer as well via intervlan routing level). Uncheck allow remote request from mikrotik. In PPPoE profile, use the local dns as primary and google dns as secondary. In few network this sorted the YELLOW ICON sign.
  5. Pay attention to mikrotik CPU, if you have high number of users on single Tik, OR if you have CONNTRACK/NATTING enabled, then disconnection of pppoe users can cause CPU spikes resulting in Tik freezing for a minute or it can cause other users disconnection dueto cpu not responding timely, resulting in looping as well. Use separate router for natting. If you have high number of PPP users along with some NATTING rules, Stop using Masquarade on same router that have a lot of dynamic interfaces. DO NOT use NAT on any router that have high number of connecting/disconnecting interfaces , like pppoe/vpn. Place an additional router connected with your PPPoE NAS, and route NAT traffic there. Make sure to disable CONNECTION TRACKING on PPPoE NAS router. As a rule of thumb, to divide load (& as a failover) , if you are using ccr1036 , add another ccr1036 after every 1200-1500 users.
  6. Adding your local DNS & assign it to user profile as a primary DNS sorted the yellow sign problems in some users WiFi Routers.
  7. PPP is sensitive to high delays and network timeouts, Make sure you dont have layer 2 level broadcast/delays
  8. If you Cisco switch with VLANs , set STP/RSTP to none on switch TRUNK  [*** This sorted the ppp disconnection at few networks]
  9. If you have Cisco switches with VLANs, Do Not allow all VLANS on TRUNK ports, Allow only limited/designated vlans on TRUNK port [*** This sorted dialup stuck issues at few networks]
  10. Changing the MTU [sometimes it sorts websites & few apps related issues , examples whatsAPP , Telegram, etc]
  11. Try to disable Encryption/Compression on the profile of the pppoe. Choosing only (pap) for pppoe server [This sorts some old freeradius related issues]
  12. Disable RSTP on all ports/VLANS [Test with caution, for temporary basis only just to confirm if its related issue]
  13. Disable LOOP protection in mikrotik ports settings [Test with caution, for temporary basis only]
  14. Do Not disable ICMP Some user end routers checks for icmp reachability to detect internet access. It’s quite worse when there are operators that think that ICMP is dangerous and it has to be blocked. Make sure you are not blocking all ICMP traffic, just fine tune it to allow at least certain type of icmp packets, however, when someone further upstream does that, you will have problems
  15. Do Not disable NTP protocol, [it is being used by many devices like android devices like android TV’s, Gaming devices etc]

Part 3/4 Annexure Example: [Test it with caution or preferably in LAB tests]

no spanning-tree vlan 1-1014
interface GigabitEthernet2/0/1
description Trunk-LAN-2-Mikrotik
switchport trunk encapsulation dot1q
switchport trunk allowed vlan 2-16,99
switchport mode trunk

Personnel Opinion!

Well TBH, Mikrotik is a cheap/affordable solution & overall Mikrotik is excellent for core routing too BUT its not made for large scale ppp NATTING. Mikrotik is not an enterprise grade solution with reference to pppoe concentrator. It have it’s architecture’s limitations. As a rule of thumb/In general , We suggest that after crossing 1200-1400 ppp users (& max 2Gb of traffic), just add another mikrotik (ccr1036 or likewise) & so on. I knows few ISp’s locally who are using mikrotik who have used Mikrotik routers just start up their journey in the SP business but later they moves to more mature products like cisco/juniper/vBNG. One ISP in particular using 10-12 Mikrotiks to cater 15k users load (in routing mode only, no natting). With natting situation gets worse when ppp users disconnects in large quantity resulting in CPU hiking/freezing creating nightmares for admins)

If you have thousands of users , then you are in serious business, go with *Huawei/Juniper/Cisco* (which are much mature but comparatively costly products ) & as an alternate, you may look for *VBNG* which have pay as per you go modules.

Syed Jahanzaib

June 19, 2020

Mikrotik Queue Tree with Traffic Priority

Filed under: Mikrotik Related — Syed Jahanzaib / Pinochio~:) @ 3:17 PM

Mikrotik Queue tree with Traffic Priority

Example if you have assigned user with 1 mb profile, & if user is doing full download, his stream will get degrade, buffered because IDM will fetch using full available bandwidth using multiple connection.

Using Priority feature in TREE, we can configure mikrotik to assign user 1mb bandwidth limit, but it should always give 1mb priority to CDN traffic first, then to others. This way even if user is downloading at full speed liek using IDM, and if he plays video from CDN , then bandwidth priority will be given to CDN first (IDM download will degrade so that priority can be given to CDN.

This was done to avoid streaming buffer issue even if user is downloading at full speed .

– Youtube Link:

Queue Code: [dynamic queue for user is auto created upon user pppoe connection, on top of that we r using queue tree to prioritize]

/ip firewall address-list
add address= list=1mb
add address= list=cdn_list

/ip firewall mangle
add action=mark-connection chain=forward new-connection-mark=ICMP_Conn protocol=icmp
add action=mark-packet chain=forward connection-mark=ICMP_Conn new-packet-mark=ICMP_Pkts passthrough=no
add action=mark-packet chain=forward comment="MARK CDN UP" dst-address-list=1mb new-packet-mark=cdn_up passthrough=no \
add action=mark-packet chain=forward comment="MARK CDN DOWN" dst-address-list=cdn_list new-packet-mark=cdn_down \
passthrough=no src-address-list=1mb
add action=mark-packet chain=forward comment=MARK_1MB_UP_USER new-packet-mark=1mb_up passthrough=no src-address-list=1mb
add action=mark-packet chain=forward comment=MARK_1MB_DOWN_USER dst-address-list=1mb new-packet-mark=1mb_down \

/queue simple
add max-limit=1M/1M name=ICMP packet-marks=ICMP_Pkts target=""

/queue tree
add max-limit=1G name=10G-ZAIB-WAN-Link parent=global
add name="icmp pkts Top Priority from Main Feed - Zaib" packet-mark=ICMP_Pkts parent=10G-ZAIB-WAN-Link priority=1
add name=1mb-overall-internet-up packet-mark=1mb_up parent=10G-ZAIB-WAN-Link queue=1mb-upload
add name=1mb-overall-internet-down packet-mark=1mb_down parent=10G-ZAIB-WAN-Link queue=1mb-download
add name=cdn-down-hi-priority packet-mark=cdn_down parent=1mb-overall-internet-down priority=2 queue=1mb-download
add name=cdn-up-hi-priority packet-mark=cdn_up parent=1mb-overall-internet-up priority=2 queue=1mb-upload

/queue simple
add max-limit=1M/1M name=ICMP packet-marks=ICMP_Pkts target=""

Syed Jahanzaib

May 15, 2020

Mikrotik to Mikrotik/Cisco Bonding – Reference Notes

Filed under: Cisco Related, Mikrotik Related — Tags: , , , , — Syed Jahanzaib / Pinochio~:) @ 2:40 PM


cisco bonding mikrotik to cisco

2 ports bonding


2020-05-13 13.19.04

This post was made for self reference purposes, so that I can find the configs easily from this page when needed again.

This post describes possible methods of creating ethernet interfaces bonding between Mikrotik to Cisco (etherchannel) or Mikrotik to Mikrotik to achieve load balancing & failover to achieve higher speed from multiple ethernet interfaces. Bonding is a technology that allows aggregation of multiple Ethernet-like interfaces into a single virtual link, thus getting Maximum Throughput and providing failover. You can use this technique to create bonding between WAN Cisco switch/R to User Mikrotik, then from User mikrotik to User distribution vlan switch. lots of combinations you can create in this regard.

Possible Scenarios:

OP have Mikrotik CCR1036 routerboard with SFP+. ISP have given OP with 10G of SFP+ connectivity on OP WAN Mikrotik router. but on user side router OP have simple CCR1036 with 1G ports only. So the wan link from 1036-wan to 1036-LAN is choking at  1G. Proper solution is to have back to back 10G connectivity between all routers, but since it requires cash investment, therefore the OP sometimes chooses workaround to fulfill the requirements for the time being. BONDING is one of that workaround that can be chosen. although I try to avoid using it as much as possible & always look for 10/25G solutions.

Hardware Used in this post

  • Mikrotik: RB2011
  • Cisco 36450 24 Ports Switch
  • In general you can use upto 8 ports Bonding, should be of same type/speed.
  • All ports should be enabled before adding them to bond.

Option-1# Mikrotik to Cisco Bonding (using 1Gx2 interfaces to achieve failover / load balancing / higher speed)

Using any two interfaces, we are creating 2 port Bonding interface. Example from Mikrotik Port 9 & 10 we will connect two cables connected to Cisco Switch port 23 & 24.

#Mikrotik Example Code , using port 9 & 10

/interface bonding
add link-monitoring=none mode=802.3ad name=bonding1-lan slaves=ether9,ether10 transmit-hash-policy=layer-2-and-3

# Cisco Switch Example Code, suing port 23 & 24

configure terminal
inter range gigabitEthernet 1/0/23-24
channel-group 1 mode active
channel-protocol lacp
#on newer IOS you dont need following CMD
#switchport trunk encapsulation dot1q
switchport mode trunk

Note: If you are doing Cisco to Cisco Port Bonding , then you need to repeat above code on 2nd switch too

Option-2# Mikrotik to Mikrotik Bonding

Its very simple. Just issue below command on both mikrotik and connect the cables from designated interfaces, assign IP, and you are good to go …

/interface bonding
add name=bonding1-to-ppp slaves=ether1,ether2

Some Helpful CMD’s related to etherchannel on Cisco switch …

show etherchannel summary
show etherchannel 1 port-channel
show interfaces etherchannel

Note: Before you connect both cable, make sure to add the config on Mikrotik & Cisco side, Else cisco port will get shut dueto STP protection to avoid loop.

*May 13 04:58:33.710: %ETC-5-L3DONTBNDL2: Gi1/0/23 suspended: LACP currently not enabled on the remote port.

Configuring EtherChannel Load Balancing


To view etherchannel load balancing setting, use the show command …

show etherchannel load-balance

To configure load balancing, use the following commands:

configure terminal
port-channel load-balance dst-mac
do wr

Syed Jahanzaib

January 8, 2020

Syslog-ng – Part 3: Minimized logging to mysql with dynamic tables & trimming

Filed under: Linux Related, Mikrotik Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 1:27 PM

syslog cgnat

Revision: 7th-JAN-2020

In continuation to existing posts related to syslog-ng, Following post illustrates on how you can log only particular messages with pattern matching and let syslog-ng creates dynamic table based on the dates so that searching/querying becomes easy.

This task was required in relation to CGNAT logging. you may want to read it here

Hardware Software used in this post:

  • Mikrotik Routerboard – firmware 6.46.x
  • Ubuntu 16.4 Server x64 along with syslog-ng version 3.25.1 on some decent hardware


Ubuntu OS

Ref: Installing latest version of syslog-ng

#Make sure to change the version, I have used this CMD on Ubuntu 16.04 , for version 18, you may change this to 18.04

wget -qO - | sudo apt-key add -
touch /etc/apt/sources.list.d/syslog-ng-obs.list
echo "deb ./" &gt; /etc/apt/sources.list.d/syslog-ng-obs.list
apt-get update
apt-get -y install apache2 mc wget make gcc mysql-server mysql-client curl phpmyadmin libdbd-pgsql aptitude libboost-system-dev libboost-thread-dev libboost-regex-dev libmongo-client0 libesmtp6 syslog-ng-mod-sql libdbd-mysql libdbd-mysql syslog-ng

Note: during above packages installation, it will ask you to enter mysql/phpmyadmin password, you can use your root password to continue the installations. It may download around  after installation finishes, you can check syslog-ng version.

At the time I did installation I got this

syslog-ng -V

root@nab-syslog:~# syslog-ng -V
syslog-ng 3 (3.30.1)
Config version: 3.29
Installer-Version: 3.30.1
Revision: 3.30.1-2
Compile-Date: Nov 19 2020 16:33:22
Module-Directory: /usr/lib/syslog-ng/3.30
Module-Path: /usr/lib/syslog-ng/3.30
Include-Path: /usr/share/syslog-ng/include
Error opening plugin module; module='mod-java', error=' cannot open shared object file: No such file or directory'
Available-Modules: syslogformat,azure-auth-header,hook-commands,linux-kmsg-format,kafka,afmongodb,json-plugin,cef,secure-logging,afsocket,pseudofile,kvformat,add-contextual-data,afamqp,riemann,http,appmodel,stardate,tfgetent,redis,cryptofuncs,sdjournal,afuser,pacctformat,graphite,confgen,geoip2-plugin,affile,basicfuncs,xml,mod-python,examples,afsmtp,timestamp,map-value-pairs,disk-buffer,afsnmp,system-source,afsql,afstomp,csvparser,tags-parser,afprog,dbparser
Enable-Debug: off
Enable-GProf: off
Enable-Memtrace: off
Enable-IPv6: on
Enable-Spoof-Source: on
Enable-TCP-Wrapper: on
Enable-Linux-Caps: on
Enable-Systemd: on


root@nab-syslog:~# service syslog-ng status
syslog-ng.service - System Logger Daemon
Loaded: loaded (/lib/systemd/system/syslog-ng.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2021-01-25 00:20:55 EST; 1min 26s ago
Docs: man:syslog-ng(8)
Main PID: 21596 (syslog-ng)
CGroup: /system.slice/syslog-ng.service
21596 /usr/sbin/syslog-ng -F

Jan 25 00:20:55 nab-syslog systemd[1]: Starting System Logger Daemon...
Jan 25 00:20:55 nab-syslog systemd[1]: Started System Logger Daemon.

Create Database in mySQL to store dynamic tables

Create Base Database for storing dynamically created date wise tables

mysql -uroot -pXXX -e "create database syslog;"

Now edit the syslog-ng file

nano /etc/syslog-ng/syslog-ng.conf

& use following as sample. I would recommend that you should add only relevant part, just dont do blind copy paste. This is just sample for demonstration purposes only …

Syslog-ng Sample File

@version: 3.30
@include "scl.conf"
# First, set some global options.
options { chain_hostnames(off); flush_lines(0); use_dns(no); use_fqdn(no);
dns_cache(no); owner("root"); group("adm"); perm(0640);
stats_freq(0); bad_hostname("^gconfd$");
# Sources
# This is the default behavior of sysklogd package
# Logs may come from unix stream, but not from another machine.
source s_src {
# Destinations
# First some standard logfile
destination d_auth { file("/var/log/auth.log"); };
destination d_cron { file("/var/log/cron.log"); };
destination d_daemon { file("/var/log/daemon.log"); };
destination d_kern { file("/var/log/kern.log"); };
destination d_lpr { file("/var/log/lpr.log"); };
destination d_mail { file("/var/log/mail.log"); };
destination d_syslog { file("/var/log/syslog"); };
destination d_user { file("/var/log/user.log"); };
destination d_uucp { file("/var/log/uucp.log"); };
destination d_mailinfo { file("/var/log/"); };
destination d_mailwarn { file("/var/log/mail.warn"); };
destination d_mailerr { file("/var/log/mail.err"); };
destination d_newscrit { file("/var/log/news/news.crit"); };
destination d_newserr { file("/var/log/news/news.err"); };
destination d_newsnotice { file("/var/log/news/news.notice"); };
destination d_debug { file("/var/log/debug"); };
destination d_error { file("/var/log/error"); };
destination d_messages { file("/var/log/messages"); };
destination d_console { usertty("root"); };
destination d_console_all { file(`tty10`); };
destination d_xconsole { pipe("/dev/xconsole"); };
destination d_ppp { file("/var/log/ppp.log"); };
# Filters
# Here's come the filter options. With this rules, we can set which
# message go where.

filter f_dbg { level(debug); };
filter f_info { level(info); };
filter f_notice { level(notice); };
filter f_warn { level(warn); };
filter f_err { level(err); };
filter f_crit { level(crit .. emerg); };
filter f_debug { level(debug) and not facility(auth, authpriv, news, mail); };
filter f_error { level(err .. emerg) ; };
filter f_messages { level(info,notice,warn) and
not facility(auth,authpriv,cron,daemon,mail,news); };
filter f_auth { facility(auth, authpriv) and not filter(f_debug); };
filter f_cron { facility(cron) and not filter(f_debug); };
filter f_daemon { facility(daemon) and not filter(f_debug); };
filter f_kern { facility(kern) and not filter(f_debug); };
filter f_lpr { facility(lpr) and not filter(f_debug); };
filter f_local { facility(local0, local1, local3, local4, local5,
local6, local7) and not filter(f_debug); };
filter f_mail { facility(mail) and not filter(f_debug); };
filter f_news { facility(news) and not filter(f_debug); };
filter f_syslog3 { not facility(auth, authpriv, mail) and not filter(f_debug); };
filter f_user { facility(user) and not filter(f_debug); };
filter f_uucp { facility(uucp) and not filter(f_debug); };

filter f_cnews { level(notice, err, crit) and facility(news); };
filter f_cother { level(debug, info, notice, warn) or facility(daemon, mail); };
filter f_ppp { facility(local2) and not filter(f_debug); };
filter f_console { level(warn .. emerg); };
# Log paths
log { source(s_src); filter(f_auth); destination(d_auth); };
log { source(s_src); filter(f_cron); destination(d_cron); };
log { source(s_src); filter(f_daemon); destination(d_daemon); };
log { source(s_src); filter(f_kern); destination(d_kern); };
log { source(s_src); filter(f_lpr); destination(d_lpr); };
log { source(s_src); filter(f_syslog3); destination(d_syslog); };
log { source(s_src); filter(f_user); destination(d_user); };
log { source(s_src); filter(f_uucp); destination(d_uucp); };
log { source(s_src); filter(f_mail); destination(d_mail); };
log { source(s_src); filter(f_news); filter(f_crit); destination(d_newscrit); };
log { source(s_src); filter(f_news); filter(f_err); destination(d_newserr); };
log { source(s_src); filter(f_news); filter(f_notice); destination(d_newsnotice); };
log { source(s_src); filter(f_debug); destination(d_debug); };
log { source(s_src); filter(f_error); destination(d_error); };
log { source(s_src); filter(f_messages); destination(d_messages); };
log { source(s_src); filter(f_console); destination(d_console_all);
destination(d_xconsole); };
log { source(s_src); filter(f_crit); destination(d_console); };
@include "/etc/syslog-ng/conf.d/*.conf"

######## Zaib Section Starts here
# Accept connection on UDP
source s_net { udp (); };

# Adding filter for our Mikrotik Routerboard, store logs in FILE as primary
# MIKROTIK ###########

# This entry will LOG all information coming from this IP, change this to match your mikrotik NAS
filter f_mikrotik_192.168.0.1 { host(""); };
# add info in LOG (Part1)
destination df_mikrotik_192.168.0.1 {
source s_mysql {

# Store Logs in MYSQL DB as secondary # add info in MYSQL (Part2)
destination d_mysql {
columns( "id int(11) unsigned not null auto_increment primary key", "host varchar(40) not null", "date datetime", "message text not null")
values("0", "$FULLHOST", "$R_YEAR-$R_MONTH-$R_DAY $R_HOUR:$R_MIN:$R_SEC", "$MSG")
log {


Create ‘zlogs‘ folder in /var/log , so that mikrotik logs will be saved in separate file if required by you

mkdir /var/log/zlogs

Mikrotik rule to LOG Forward chain

Now we need to create a rule in mikrotik FILTER section so that it can log all packets being forward to/from pppoe users. Make sure you in source address list you select your local pppoe users pool there to avoid un-related excessive logging. In below example we are doing only TCP base connection for NEW tcp connections only.

LOG SIZE Example: at one ISP who had around 1200+ online users , its log size for TCP connection was around 25 GB. to lower the size, I configured it log only new TCP connections which reduced the DB Size by 50%.

/ip firewall filter
add action=log chain=forward connection-state=new protocol=tcp src-address-list=pppoe_allowed_users

Mikrotik rule to send LOG to SYSLOG-NG Server

/system logging action
add name=syslogng remote= target=remote
# Change IP address pointed towards syslog server

/system logging
set 0 topics=info,!firewall
add action=syslogng topics=firewall

Restart Syslog-ng server

Now restart syslog-ng service

service syslog-ng restart

and you will see the dynamic tables created as follows

mysql -uroot -pXXXXX
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 411
Server version: 5.7.28-0ubuntu0.18.04.4-log (Ubuntu)
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql&gt; use syslog;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql&gt; show tables;
| Tables_in_syslog |
| 2020_01_08 |
1 row in set (0.00 sec)

mysql&gt; describe 2020_01_08;
| Field | Type | Null | Key | Default | Extra |
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| host | varchar(40) | NO | | NULL | |
| date | datetime | YES | | NULL | |
| message | text | NO | | NULL | |
4 rows in set (0.00 sec)

& you can then see data insertion into the table as soon LOG is received from remote devices

2020-01-08T07:49:43.020811Z 430 Query INSERT INTO 2020_01_08 (id, host, date, message) VALUES ('0', '', '2020-01-08 12:49:28', 'forward: in: out:ether1-agp-wan, src-mac d0:bf:9c:f7:88:76, proto TCP (ACK,PSH),;, NAT (;;, len 79')
2020-01-08T07:49:43.031281Z 430 Query INSERT INTO 2020_01_08 (id, host, date, message) VALUES ('0', '', '2020-01-08 12:49:28', 'forward: in: out:ether1-agp-wan, src-mac d0:bf:9c:f7:88:76, proto TCP (ACK,FIN),;, NAT (;;, len 40')
2020-01-08T07:49:43.041420Z 430 Query INSERT INTO 2020_01_08 (id, host, date, message) VALUES ('0', '', '2020-01-08 12:49:38', 'forward: in: out:ether1-agp-wan, src-mac d0:bf:9c:f7:88:76, proto UDP,;, NAT (;;, len 1378')
2020-01-08T07:49:43.051112Z 430 Query INSERT INTO 2020_01_08 (id, host, date, message) VALUES ('0', '', '2020-01-08 12:49:38', 'forward: in: out:ether1-agp-wan, src-mac d0:bf:9c:f7:88:76, proto UDP,;, NAT (;;, len 1378')
2020-01-08T07:49:43.061280Z 430 Query INSERT INTO 2020_01_08 (id, host, date, message) VALUES ('0', '', '2020-01-08 12:49:39', 'forward: in: out:ether1-agp-wan, src-mac d0:bf:9c:f7:88:76, proto UDP,;, NAT (;;, len 1378')
2020-01-08T07:49:43.071449Z 430 Query INSERT INTO 2020_01_08 (id, host, date, message) VALUES ('0', '', '2020-01-08 12:49:39', 'forward: in: out:ether1-agp-wan, src-mac d0:bf:9c:f7:88:76, proto UDP,;, NAT (;;, len 1378')
2020-01-08T07:49:44.828993Z 430 Query INSERT INTO 2020_01_08 (id, host, date, message) VALUES ('0', '', '2020-01-08 12:49:44', 'forward: in: out:ether1-agp-wan, src-mac d0:bf:9c:f7:88:76, proto UDP,;, NAT (;;, len 827')
2020-01-08T07:49:44.851034Z 430 Query INSERT INTO 2020_01_08 (id, host, date, message) VALUES ('0', '', '2020-01-08 12:49:44', 'forward: in: out:ether1-agp-wan, src-mac d0:bf:9c:f7:88:76, proto UDP,;, NAT (;;, len 827')
2020-01-08T07:51:37.518276Z 430 Query INSERT INTO 2020_01_08 (id, host, date, message) VALUES ('0', '', '2020-01-08 12:51:37', 'forward: in: out:ether1-agp-wan, src-mac d0:bf:9c:f7:88:76, proto TCP (ACK),;, NAT (;;, len 41')
2020-01-08T07:51:37.522015Z 430 Query INSERT INTO 2020_01_08 (id, host, date, message) VALUES ('0', '', '2020-01-08 12:51:37', 'forward: in: out:ether1-agp-wan, src-mac d0:bf:9c:f7:88:76, proto TCP (ACK),;, NAT (;;, len 41')

syslog-ng dynamic table data from phpmyadmin.PNG


Deleting all tables inside particular DB

# drop tables matching filter
for t in $(mysql -u $u -p$p -D $db -Bse 'show tables' | grep $filter); do
echo Dropping $t;
[[ $force -eq 1 ]] && mysql -u root -p$p -D $db -Bse "drop table \`$t\`"

Syed Jahanzaib

January 1, 2020

CGNAT Deployment using Mikrotik RouterOS

Filed under: Mikrotik Related — Tags: , , , , , , , — Syed Jahanzaib / Pinochio~:) @ 5:34 PM

mdnet cgnat conept.PNG

Note: This is In-complete Post. It contains src-nat method part only. Second method of NETMAP will be added later (if time will allow)  which is I feel far more simple & efficient as compared to the src-nat method. But this method is ok too to comply with the Law using little resources.

My humble request, Kindly donot consider me as an expert on this stuff, I am NOT certified in anything Mikrotik/Cisco/Linux or Windows. However I have worked with some networks and I read , research & try stuff all of the time. When you are enslaved by private job & working as one man army, you have to perform many task in which you are not formally trained for. So I am not speaking/posting about stuff I am formerly trained in, I pretty much go with experience and what I have learned on my own. And , If I don’t know something then I read & learn all about it.

So , please don’t hold me/my-postings to be always 100 percent correct. I make mistakes just like everybody else. However – I do my best, learn from my mistakes and try to help others

Some references used in this post

*CG-NAT* as Workaround:

CGNAT concept is used to share one or preferably more public IP addresses with large number of private ip addresses on ratio basis.CGNAT/NAT444 is a conception, not a function. In terms of RouterOS functionality it’s simple SRC NAT rule.

To combat with this IPV4 exhausting issue, we can use CGNAT as a workaround. This is by no means a solution, & the OP should get public IP space (either ipv4 or ipv6) to comply with the LAW.

Note: Please note that CGNAT concept is mostly for UDP/TCP and its generally not meant for other protocols.

Some possible disadvantages of using CGNAT concept:

  • CGNAT is not sustainable in the long term, hectic to manage the private/public pools especially if you have multiple NASes doing same job
  • ISP deploying IP address sharing techniques should also deploy a corresponding logging architecture to maintain records of the relation between a customer’s identity and IP/port resources utilized
  • You should deploy additional SYSLOG server (either windows or linux base) to store logs. I would prefer linux base SYSLOG-NG). Tracking of users for legal reasons means searching hundreds GB’s of logging would be required, as multiple end users go behind one (or more) public IP address(es). Tracking Logs is not an easy task particularly when you have tongs of Logging (in a DB).Logging every NAT translation is resource consuming. Some super fast computing resources (including preferably RAID10 or SSD based storage) and fine tune DB would be required
  • A CG-NAT device must use the same external IP address mapping for all sessions associated with the same internal IP address
  • Most Applications do not behave well with TCP resets
  • Many operators are still not familiar with CG-NAT complexities. There is a lot of trial and error on the part of ISP’s


in my personal experience , Deployment is somewhat hectic, & tracking any request is daunting task ! z@ib

Hardware/Software Used in this post:

CGNAT logging to remote syslog server with some customization


OP is running mini ISP with around 200 active subscribers. Mikrotik Router is being used as PPPoE Server along with Freeradius as AAA. On Mikrotik, one public IP is configured for WAN and additional /24 routed pool (256 public IP addresses) is provided to the OP via ISP so that he can provide public IP to each user. After the network upgrades , OP have reached 700 users in total, and since he have only 256 public ip’s , he is now using natting for half of his users.

We all know that IPV4 shortage is on peak , getting ipv4 is expensive for 3rd world countries & small ISP’s as well.

This NATTING workaround is creating hurdles in tracking illegal activity performed by any NATTED users because hundreds of NATTED user will have same public ip (Mikrotik WAN IP). nowadays law sometimes provide only the public ip along with source port and ask for the user credentials details for investigation purposes.

with single public IP and hundreds of natted hosts behind it. tracking is nearly impossible.

IP scheme example used in this Scenario#1:

Public IP range: (/24 public IP’s routed pool)

  • 1.1.1-
  • Total Public IP useable: 255

Private IP range for PPPoE users:

  • Total Private IP useable: 765

For 765 Users, we will be using 1:5 Ratio, thus 153 public ips will be used for 765 users. (on a ratio of 1:5).

  • per private IP, we will reserve 10,000 ports, which should be more than enough for each user.
  • per private IP, we will be creating 3 rules, one for TCP, second for UDP, 3rd for non ports range [Use 3rd this rule with caution, it will nat every non tcp/udp traffic, some firewalling may be put, ALSO YOU MAY NOT BE NEEDING 3rd rule which can eliminate 1/3 rules]

in my personal expeirence, CGNAT configuration on RouterOS is very much similar to regular source NAT configuration.

To add multiple Public IP addresses on WAN interface in bulk using single CMD on Terminal

You may need to add all of your public IP addresses (which will be used for CGNAT) on WAN interface(required for troubleshooting purposes as well).

To add ips in bulk using single CMD, you can use Mikrotik FOR X script function for ease / ZAIB

:for x from 1 to 153 do={ /ip address add address="1.1.1.$x/32" comment="1.1.1.$x - Routed IP for ppp CGNAT - zaib" interface="ether1-wan"}


Adding FUNCTION in Mikrotik for later Automation

Paste this in Mikrotik RouterOS terminal:

# CGNAT Customized minimalistic Script to add function.
# Disclaimer: This particular function is not made by ME, I only trimmed/modified it to suite my local requirements
# Syed Jahanzaib / aacable at hotmail dot com
:global sqrt
:global sqrt do={
:for i from=0 to=$1 do={
:if (i * i > $1) do={ :return ($i - 1) }
:global addNatRules do={
:local x [$sqrt $count]
:local y $x
:if ($x * $x = $count) do={ :set y ($x + 1) }
:for i from=0 to=($count - 1) do={
:local prange "$($portStart + ($i * $portsPerAddr))-$($portStart + (($i + 1) * $portsPerAddr) - 1)"
# src-nat TCP traffic
/ip firewall nat add chain=srcnat action=src-nat protocol=tcp src-address=($srcStart + $i) to-address=$toAddr to-ports=$prange
# src-nat UDP traffic
/ip firewall nat add chain=srcnat action=src-nat protocol=udp src-address=($srcStart + $i) to-address=$toAddr to-ports=$prange
# This below 3rd rule is created to allow protocols other then tcp/udp, example ICMP ? , use it with caution , zaib
/ip firewall nat add chain=srcnat action=src-nat src-address=($srcStart + $i) to-address=$toAddr

Now we have function inserted with the help of above code, and using this function, we can create rules in bulk using following CMD to add rules in NAT section

# per private IP, we will reserve 10000 ports, which should be more than enough for each user.
# per private IP, we will be creating 3 rules, one for TCP, second for UDP, 3rd for non ports range

$addNatRules count=5 srcStart= toAddr= portStart=10000 portsPerAddr=9999
$addNatRules count=5 srcStart= toAddr= portStart=10000 portsPerAddr=9999
$addNatRules count=5 srcStart= toAddr= portStart=10000 portsPerAddr=9999
$addNatRules count=5 srcStart= toAddr= portStart=10000 portsPerAddr=9999
$addNatRules count=5 srcStart= toAddr= portStart=10000 portsPerAddr=9999
$addNatRules count=5 srcStart= toAddr= portStart=10000 portsPerAddr=9999
$addNatRules count=5 srcStart= toAddr= portStart=10000 portsPerAddr=9999
$addNatRules count=5 srcStart= toAddr= portStart=10000 portsPerAddr=9999
$addNatRules count=5 srcStart= toAddr= portStart=10000 portsPerAddr=9999
$addNatRules count=5 srcStart= toAddr= portStart=10000 portsPerAddr=9999

# & so on for rest of the pool, you can further automate this by using additional functions & scripting

Enable Logging of CG-NAT Output:

# To log user IP/NAT information on LOG window / you can configure remote log to syslog-server too
/ip firewall filter
add action=accept chain=forward log=yes log-prefix="NAT_INFO_FW> " src-address=

Log Result (from different servers , so ip scheme may be changed in these logs, For example purposes)

In this log you can clearly see the src-dst address, and on which public ip request was natted along with ports. This is useful

Rules from LAB Router:

Mikrotik WAN IP’s (2 for test purposes):


PPPoE Users (2 for test)


REMOTE WEB SERVER (considering it’s a web server on internet which our user is accessing or doing illegal stuff)



/ip firewall nat
add action=src-nat chain=srcnat protocol=tcp src-address= to-addresses= to-ports=10000-19999
add action=src-nat chain=srcnat protocol=udp src-address= to-addresses= to-ports=10000-19999
add action=src-nat chain=srcnat src-address= to-addresses=
add action=src-nat chain=srcnat protocol=tcp src-address= to-addresses= to-ports=20000-29999
add action=src-nat chain=srcnat protocol=udp src-address= to-addresses= to-ports=20000-29999
add action=src-nat chain=srcnat src-address= to-addresses=



On internet web server, we see following

[]:10133 - - [02/Jan/2020:15:44:37 +0500] "GET /? HTTP/1.1" 200 3138 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"

so the law enforcement agency come to us, and tell us that this is your public IP+Port, now give us his details. And as we know that we are doing CGNAT, so we have to do little tracking.

On Mikrotik LOG we see following [after enabling LOGS,


You can now see that our public IP having port 10133 was natted for our local user IP with PPPoE it will show you the user name as well, so you can catch it right from here, or else if RADIUS is being used, you can track the IP via freeradius DB in radacct.


OP have single public IP (e.g: configured on Mikrotik WAN interface. End user subscriber is connected to mikrotik pppoe server using pppoe dialer. In this example we will be using (256 users) and each user IP will be allowed to use 200 ports (200 ports per private IP).

This way when LAW will ask to provide details for , we can look into our LOGS (usually SYSLOG server either in linux, or using windows based SYSLOG like solarwinds syslog serveR) we can look into the & we can see the pppoe username or its private ip and search the ip in radius radacct table if radius is being used)

$addNatRules count=255 srcStart= toAddr= portStart=2000 portsPerAddr=200

Above CMD will create 765 rules (for 256 users) in IP / Firewall / NAT section. (make sure you have pasted the addNatRules function in the terminal before using above command.

– Enable mikrotik logs in Mikrotik LOG window

To enable LOGS in mikrotik LOG window , use

/ip firewall filter
add action=accept chain=forward log=yes log-prefix="NAT_INFO_FW> " src-address=

– Enable mikrotik built in DISK base logging

To enable DISK base LOGGING in Mikrotik itself, (avoid this, it will OVERLOAD your routerboard which is not designed to handle such massive load of LOGS)

/system logging action
set 1 disk-file-count=25 disk-lines-per-file=5000
/system logging
add action=disk prefix=NAT_INFO_FW topics=info

– Enable remote SYSLOG logging in mikrotik

To ENABLE remote SYSLOG (I used Solarwind SYSLOG server on Windows in this example.

/system logging action
set 3 bsd-syslog=yes remote=
/system logging
add action=remote prefix=NAT_INFO_FW topics=info

Now we can see in the LOG window (just an example, in actual you have to use some SYSLOG server) to search for

Jan/03/2020 10:48:43 firewall,info NAT_INFO_FW> forward: in: out:ether1-wan, src-mac d0:bf:9c:f7:88:76, proto TCP (ACK),>, NAT (>>, len 40
Jan/03/2020 10:48:43 firewall,info NAT_INFO_FW> forward: in: out:ether1-wan, src-mac d0:bf:9c:f7:88:76, proto TCP (ACK),>, NAT (>>, len 52

& as you can see that was used private IP & it will also show the <pppoe-zaib> . This way you can pull the user details & provide it to law enforcement agencies.

on windows base REMOTE syslog we can see the results, and can search easily as well.

solarwind syslog.png

To Delete older logs from syslog mysql DB

 mysql -uroot -pSQLPASSWORD -s -e "use syslog; DELETE FROM logs WHERE date(datetime) < (CURDATE() - INTERVAL 3 MONTH);"

TIPS for Linux base SYSLOG-NG trimming

I am using SYSLOG-NG to store all logs , to log only the NAT related queries (which actually shows the entries of public:port vs private ip:port use following in syslog ng configuration (before SOURCE section

######## Zaib Section Starts here
# Accept connection on UDP
source s_net { udp (); };
# MIKROTIK ########### add logs into files & in mysql dB as well.zaib
# Add Filter to add our mikrotik
filter f_mikrotik_1 { host("") and match("NAT" value("MESSAGE")) };
#filter f_mikrotik_1 { host( "" ); };
log { source ( s_net ); filter( f_mikrotik_1 ); destination ( df_mikrotik_1 ); };
destination df_mikrotik_1 {

source s_mysql {
# Play with below, some confusion here
destination d_mysql { pipe("/var/log/mysql.pipe" template("INSERT INTO
logs (host,facility,priority,level,tag,datetime,program,msg) VALUES
$HOUR:$MIN:$SEC','','$MSG');\n") template-escape(yes)); };

log {
####### #Zaib Section ends here

Note: For 500 active subscribers , the average log size on the syslog DB was 500 MB per day. This was after the controlled syslog entries (logging of requests that contains word NAT only).

~ Syed Jahanzaib ~



December 13, 2019

Mikrotik – Packet Chain Topology

Filed under: Mikrotik Related — Syed Jahanzaib / Pinochio~:) @ 9:36 AM


Firewall Mangle

Firewall mangle is used to mark IP packet. These marks are used by other router facilities like routing, firewall filter and bandwidth management to identified the packets. Moreover it also used to modify some fields in the IP header, like TOS (DSCP) and TTL fields. There are 5 default chain in firewall mangle.


Packet that come into router will check with input chain. It is used to process packets entering the router. For example If we want to filter packet that telnet or ssh to router we need to use input chain in firewall filter.– Used to process packets entering the router through one of the interfaces with the destination IP address which is one of the router addresses. Chain input is useful for limiting the configuration access to Mikrotik Router.
– The connection that occurs from local to router and ends in router
example: use of the internal proxy (internal proxy right in the router)


Prerouting is looked at before the router makes a routing decision. It’s happen before input chain. The packet that forward passthrough the router will match prerouting first.Pre-routing means that the connection will enter the router (no matter from where / depends on the settings mangle in interface later) . this connection will be in the process inside the router, can the process of bending to the external proxy, can filtering port, can anything, anyway there is a process, prerouting it marks the connection before the process occurs.


After prerouting, packet that passthrough router will process by forward chain. Used to process packets passing through the router. Example we want to block users to open facebook. We will use firewall forward chain to do it.– Used to process data packets through routers, connections that occur from the public to local
– The connection that occurs from local to public
with the provision that there is no process inside the router, it means that the connection is direct and only passing in the router does not happen a process inside the router.


Postrouting is a connection that will exit the router after a process occurs inside the router. It’s happen after forward. Postrouting is looked at after the router makes a routing decision.


OUTPUT is used to process packets that originated from the router. Normally we rarely use this chain. Example we ping from router to Internet that’s output traffic.

or to process data packets originating from the router and left through one of the interfaces, connections that occur from the router to the public. It is used to process packets that originated from the router


Firewall Filter

Most of the time we use it for filter traffic simply say to protect our network from unauthorized user or bad guy. There are three default chain in firewall filter. It’s input, output and forward.


Does it matter where you mark?

Yes, because sometimes you might overmark and sometimes you might undermark. Choose the right place for the right classification/marking


Conn/PKT markign TIPS from fewi Mikrotik Expert:

Connection marks are based on the connection tracking facility. That is mandatory for doing any NAT, so if you do NAT you get connection marks for free.

If you have a complicated way of assigning connection marks (you check a lot of parameters, such as protocol, source address, destination port, TTL and time of day) then it’s best to do that once, and above that rule mark packets based on connection mark (based on just one comparison – the connection mark – and hence much cheaper than checking lots of parameters) and setting passthrough to ‘no’. Alternatively, you could add additional parameters on the rule that sets the connection mark and either check for ‘connection-mark=no-mark’ (this connection hasn’t been marked before) or ‘connection-state=new’ (this is a new connection and couldn’t have a mark) so that not each packet is checked against the expensive rule as well – after all you might just as well just mark the packet directly in that case.

Overall, though, unless you’re hitting over 50% CPU utilization at all times and are worried about router performance it is probably best not to optimize your mangle/filter rulesets for performance. You should rather write them in a way that makes sense to you and is easy to understand and troubleshoot so that you can take care of issues quickly when they arise. Who cares if your router is running at 20% utilization but could be running at 10%? But people do care when it takes 2 hours to figure out what’s wrong rather than the 10 minutes it might if you immediately could see what was going on.



Older Posts »

%d bloggers like this: