MikroTik SMS to Telegram – A SMS Gateway Forwarder Script

I needed a way to forward SMS messages from my Mikrotik router with modem. The easiest way was to forward the SMS to a Telegram chat.

The script retrieves incoming SMS messages, extracts essential information such as the sender, message content, and timestamp, and forwards them to the Telegram Bot API. It also includes basic error handling and provides feedback on the success or failure of the forwarding process. Multiple chat IDs are also possible.

Basic setup

  1. Setup modem and test sending and reciving without the script
  2. Register Telegram Bot and get API Token. I don't want to explain this here, there are enough tutorials on the internet.
  3. Get Chat ID. Send a message for example to @chatIDrobot and get the Chat ID.

Script setup

  1. Create a new script forward-incoming-sms in the Mikrotik router and paste the script code:

# ------------------------------------------------- #
# SMS to Telegram - A SMS Gateway Forwarder Script  #
# ------------------------------------------------- #

# Description
# This script will forward all SMS messages to a Telegram chat.

# Author
# 2024-01-11 foorschtbar
# https://blog.spaps.de/

# Credits
# http://blog.redax.hu/2021/02/mikrotik-sms-to-sms-forwarding.html
# https://medium.com/@dedanirungu/forwarding-sms-messages-with-mikrotik-to-website-url-via-modem-12d926615834
# https://github.com/eworm-de/routeros-scripts/blob/main/sms-forward.rsc

# Configuration
:local token "12345678:AAABBCCC...XXXYYYZZZZ"
:local chatids {"12345678";"12345678"}

:put "== Starting SMS forwarder script =="

# Check if receiving is enabled
:if ([ /tool/sms/get receive-enabled ] = false) do={
  :log warning ("Receiving of SMS is not enabled.")
  :error ("exit script");
}

# Check if the modem is in running state
:local Settings [ /tool/sms/get ];
:if ([ /interface/lte/get ($Settings->"port") running ] != true) do={
  :log warning ("The LTE interface is not in running state, skipping.")
  :error ("exit script");
}

# forward SMS in a loop
:local smsCount [ :len [ /tool/sms/inbox/find ] ]
:put ("Found ".$smsCount." SMS to process")
:local index 0
:foreach sms in=[ /tool/sms/inbox/find ] do={
    :set index ($index + 1)
    :put ("> Processing ".$index." of ".$smsCount)

    :local smsVal [ /tool/sms/inbox/get $sms ];
    :local smsPhone ($smsVal->"phone")
    :local smsType ($smsVal->"type")
    :local smsMessage ($smsVal->"message")
    :local smsTime ($smsVal->"timestamp")

    :local logmsg ("SMS from ".$smsPhone." on ".$smsTime." (".$smsType."):\n".$smsMessage)
    :put ($logmsg);
    :log info ("Forwarding ". $logmsg);

    # URL safe message
  :local urlMessage ""
    :for i from=0 to=([:len $logmsg] - 1) do={ 
      :local char [:pick $logmsg $i]

      :if ($char = "\n") do={
        :set $char "%0A";
      }

      :if ($char = " ") do={
        :set $char "%20";
      }

      :if ($char = "-") do={
        :set $char "%2D";
      }

      :if ($char = "\?") do={
        :set $char "%3F";
      }

      :if ($char = "!") do={
        :set $char "%21";
      }

      :if ($char = "+") do={
        :set $char "%2B";
      }

      :if ($char = "%") do={
        :set $char "%22";
      }

      :if ($char = "'") do={
        :set $char "%27";
      }

      :if ($char = "(") do={
        :set $char "%28";
      }

      :if ($char = ")") do={
        :set $char "%29";
      }

      :if ($char = ",") do={
        :set $char "%2C";
      }

      :if ($char = ".") do={
        :set $char "%2E";
      }

      :if ($char = ":") do={
        :set $char "%3A";
      }

      :if ($char = ";") do={
        :set $char "%3B";
      }

      :if ($char = "=") do={
        :set $char "%3D";
      }

      :if ($char = "&") do={
        :set $char "%26";
      }

      :if ($char = "*") do={
        :set $char "%2A";
      }

      :if ($char = "/") do={
        :set $char "%2F";
      } 

        :set urlMessage ($urlMessage . $char);

    }

    # send POST
    :local noerror true
    :local chatIdx 1
    :local chatsTotal [ :len $chatids ]
    :foreach chatid in=$chatids do={
        :put ("> Sending HTTP request ". $chatIdx . " of " . $chatsTotal."...")
        :local url ("https://api.telegram.org/bot" .$token . "/sendMessage")
        :local parameters ("?chat_id=" . $chatid . "&text=" . $urlMessage)
        :local fullurl ($url . $parameters)
        :local responseStr [/tool fetch url=$fullurl http-method=get as-value output=user]
        :put ("Status: ".$responseStr->"status")
        :put ("Data: ".$responseStr->"data")
        :if ($responseStr->"status" = "finished") do={
            :put ("Successfully forwarded message ID: " . $index. " to chat ID: " . $chatid)
            :log info ("Successfully forwarded message ID: " . $index. " to chat ID: " . $chatid)
        } else={
            :put ("Failed to forward message ID: " . $index. " to chat ID: " . $chatid)
            :log error ("Failed to forward message ID: " . $index. " to chat ID: " . $chatid)
            :set noerror false
        }
        :set chatIdx ($chatIdx + 1)
    }

    :if ($noerror) do={
        /tool sms inbox remove $sms
        :put ("Deleted message ID: " . $index)
    }
}

:put "== Finished SMS forwarder script =="
  1. Change the configuration variables in the script: tokenand chatids
  2. Test the script by running it manually /system script run forward-incoming-sms
  3. Create a new scheduler forward-incoming-sms. You can use the following command or create it in the Webfig
    /system scheduler add name=forward-incoming-sms interval=10s on-event="/system script run forward-incoming-sms" start-time=startup

Temporarily access NixOS with encrypted LUKS from Ubuntu Live

Setup

  • Boot Ubuntu Live as usual
  • Change keyboard layout with setxkbmap <lang>
  • Install useful packages with sudo apt install vim nix-bin

Open crypt device

  • Idenitify LUKS device with lsblk --fs. Look for crypto_LUKS:
    nvme0n1
    ├─nvme0n1p1   vfat        FAT32
    └─nvme0n1p2   crypto_LUKS 2
  • Open encrypted device with cryptsetup luksOpen /dev/<root partition (sda2 or similar)> secure
  • Check sucessfull open with lslbk. You should now see the crypt partition(s):
    nvme0n1       259:0    0 476.9G  0 disk
    ├─nvme0n1p1   259:1    0   549M  0 part
    └─nvme0n1p2   259:2    0 476.4G  0 part
    └─enc-pv    253:0    0 476.4G  0 crypt
      ├─vg-swap 253:1    0    16G  0 lvm
      └─vg-root 253:2    0 460.4G  0 lvm

Mount partitions

  • lvchange -a y /dev/vg/swap
  • lvchange -a y /dev/vg/root
  • mount /dev/vg/root /mnt
  • mount /dev/<boot partition (sda1 or similar)> /mnt/boot
  • swapon /dev/vg/swap

Temporarily access NixOS

  • Access with nixos-enter
  • Optional:
    • Add additional channel if needed
      nix-channel --add https://github.com/NixOS/mobile-nixos/archive/refs/heads/master.tar.gz mobile-nixos
    • Update channels nix-channel --update
  • Change config
  • Rebuild system nixos-rebuild boot

Enable sshd for root on Ubuntu Live

  • Set keyboard layout with setxkbmap <lang>
  • Update package repo with sudo apt update
  • Install sshd and vim with sudo apt install openssh-server vim
  • Update sshd config with sudo vim /etc/ssh/sshd_config
    • Set PermitRootLogin yes
    • Set PasswordAuthentication yes
  • Set password for root with sudo passwd root
  • Restart SSHD service sudo systemctl restart ssh.service
  • Login via ssh to machine

Resize a LUKS encrypted root partition

  1. Resizing the partition used by the encrypted volume
parted /dev/sda

(parted) print
[...]
Number  Start   End    Size   File system  Name                  Flags
 1      1049kB  525MB  524MB  fat16        EFI system partition  boot, esp
 2      525MB   256GB  256GB               Linux filesystem

(parted) resizepart
Partition number? 2
End?  [512GB]? '100%'

(parted) print
[...]
Number  Start   End    Size   File system  Name                  Flags
 1      1049kB  525MB  524MB  fat16        EFI system partition  boot, esp
 2      525MB   512GB  512GB               Linux filesystem

(parted) q
  1. Boot machine from a bootable USB linux system (Arch Linux-, Ubuntu or similar USB installer)
  2. Open and resizing the encrypted LUKS volume
cryptsetup open /dev/sdb1 sdb1_crypt
cryptsetup resize sdb1_crypt
  1. Resize the physical device
pvresize /dev/mapper/sdb1_crypt
  1. Resize the logical device
lvextend -l +100%FREE /dev/mapper/vg-root
  1. Resizing the file-system of the volume
resize2fs /dev/mapper/vg-root
  1. Reboot. You are done.

Compile and use Proxmark3 on NixOS (nix-shell)

To compile and use proxmark3 on NixOS you need some packages. I created a nix-shell file with all needed dependencies.

Copy this file as shell.nix to the cloned proxmark3 folder and run sudo nix-shell. Continue then the normal compile guide.

with (import <nixpkgs> {});
mkShell {
  buildInputs = [
    lz4
    readline
    bzip2
    ocamlPackages.ssl
    gcc-arm-embedded
  ];
}

Examples

Proxmark Version/HW Info/Test connection

hw ver

Clone EM4100 to T5577 (Iceman Repo)

lf search
lf em 410x clone --id 0011223344
lf em 410x reader

Clone MIFARE Classic (Iceman Repo)

hf search
hf mf info
hf mf csetuid -u 00AA11BB

Clone EM4100 to T5577 (Offical Repo)

lf search
lf em 410xwrite 0011223344 1
lf em 410xread

How to downgrade Unifi Controller Software

  1. You need a backup file from the version you want to downgrade. If you haven`t, you can stop here.
  2. SSH into your controller
ssh {user}@{controller-ip}
  1. Removed existing downloads
rm -f unifi_sysvinit_all.deb*
  1. Uninstall current controller package
apt purge unifi -y
  1. Download old controller package (replace version in url with your needs)
wget https://dl.ui.com/unifi/6.5.54/unifi_sysvinit_all.deb
  1. Install package
dpkg -i unifi_sysvinit_all.deb
  1. Remove download
rm unifi_sysvinit_all.deb
  1. Access UniFi Controller WebUI and restore backup

Useful information about NixOS

Since a few years i use NixOS as my favorite Linux distribution. NixOS is a Linux distribution based on the Nix package manager and build system. It supports reproducible and declarative system-wide configuration management as well as atomic upgrades and rollbacks, although it can additionally support imperative package and user management. See NixOS Wiki.

Upgrade to new version

  1. Review the NixOS release notes to ensure you account for any changes that need to be done manually. In particular, sometimes options change in backward-incompatible ways.

  2. sudo nix-channel --add https://nixos.org/channels/nixos-22.05 nixos (Change version tag if necessary)

  3. sudo nix-channel --update

  4. nixos-rebuild --upgrade boot

  5. Reboot to enter your newly-built NixOS.

It‘s perfectly fine and recommended to leave system.stateVersion value in the configuration at the release version of the first install of this system. You should only bump this option, if you are sure that you can or have migrated all state on your system which is affected by this option. Before changing this value read the documentation for this option (e.g. man configuration.nix or on NixOS Options).

[via]https://unix.stackexchange.com/a/491772[/via]

Clean up system

  1. sudo nix-collect-garbage --delete-older-than 30d

[via]https://matthewrhone.dev/nixos-package-guide#cleanup-old-packages-user-wide[/via]

Upgrade Kernel to latest version

  1. Add boot.kernelPackages = pkgs.linuxPackages_latest; to your configuration.nix

Use pipewire for Audio (with Bluetooth)

sound.enable = false;
hardware.pulseaudio = {
  enable = false;
  package = pkgs.pulseaudioFull;
};
security.rtkit.enable = true;
services.pipewire = {
  enable = true;
  alsa.enable = true;
  alsa.support32Bit = true;
  pulse.enable = true;
  # If you want to use JACK applications, uncomment this
  #jack.enable = true;

  # use the example session manager (no others are packaged yet so this is enabled by default,
  # no need to redefine it in your config for now)
  #media-session.enable = true;
  config.pipewire = {
    "context.properties" = {
      #"link.max-buffers" = 64;
      "link.max-buffers" = 16; # version < 3 clients can't handle more than this
      "log.level" = 2; # https://docs.pipewire.org/#Logging
      #"default.clock.rate" = 48000;
      #"default.clock.quantum" = 1024;
      #"default.clock.min-quantum" = 32;
      #"default.clock.max-quantum" = 8192;
  };
  media-session.config.bluez-monitor.rules = [
    {
      # Matches all cards
      matches = [ { "device.name" = "~bluez_card.*"; } ];
      actions = {
        "update-props" = {
          "bluez5.reconnect-profiles" = [ "hfp_hf" "hsp_hs" "a2dp_sink" ];
          # mSBC is not expected to work on all headset + adapter combinations.
          "bluez5.msbc-support" = true;
          # SBC-XQ is not expected to work on all headset + adapter combinations.
          "bluez5.sbc-xq-support" = true;
        };
      };
    }
    {
      matches = [
        # Matches all sources
        { "node.name" = "~bluez_input.*"; }
        # Matches all outputs
        { "node.name" = "~bluez_output.*"; }
      ];
      actions = {
        "node.pause-on-idle" = false;
      };
    }
  ];
};
};

Add a power LED to a Weller WE1010 soldering station

Some time ago I bought a Weller WE1010 soldering station. On all product photos it looks as if the display has a backlight - unfortunately this is not the case. Not even the on/off switch is illuminated, like on the old models. Shame on you Weller, that really goes better - especially for the price!

A backlight for the display would improve the readability enormously, but a retrofit is not so easy. I have instead installed a light under the on/off switch to see at least better whether the soldering station is switched on. I get the power directly from transformer, which supplies around 24V/AC. As LED i used this great Red 6mm 12-24V AC/DC LED.

Disclaimer

I assume no warranty or responsibility for any damage or injury. The conversion is at your own risk! When opening devices that are operated with mains voltage there is danger to life!

Parts

Assembly

  1. Open soldering station by removing the two screws on the back
  2. At this point, the housing can be carefully lifted with a flat screwdriver
  3. Then I removed the on/off switch and drilled a 6mm hole 12mm below the opening for the LED. Since there is so much space, one could think that Weller wanted to install an LED here - who knows?
  4. Insert the LED
  5. Protect LED cables with some tube
  6. Solder LED wires to the 24V output from the transformer
  7. Test and reassemble

Images

Video

Links

The links to AliExpress are advertising links. I would be happy if you use this link, but of course you don't have to. I have linked exactly the offers from which I have also bought and was satisfied with the supplier and the goods. The products can of course be bought anywhere.

Microsoft Outlook – Cannot delete this folder

After restoring an Exchange mailbox and sorting the mails, I wanted to delete the restore folder, but Outlook won't let me:

Cannot delete this folder. Right-click the folder, and then click Properties to check your petmissions for the folder, See the folder owner or your administrator to change your permissions, Shared folders cannot be deleted during synchronization with the server. Delete the folder after synchronization is finished

Solution: Move the folder to trash and then delete the folder.