===============
== bacardi55 ==
===============
ἕν οἶδα ὅτι οὐδὲν οἶδα

Receive a notification on ssh connection via ntfy

- Permalink

One thing I have set up on all my servers for the past year and a half is an automated alert when an ssh connection is made to one of my servers. I do this on all my “cloud” servers (DigitalOcean and now also with Hetzner) but also for my home servers, which include Proxmox hosts and attached VM and containers.

The notification is sent to a selfhosted ntfy instance. This post will not go through the installation and configuration of ntfy, I’m assuming for this post that you already have one ready and configured. I’m using a ntfy token that can be generated with ntfy CLI tool and not login / password, as it is easier and better. Look at ntfy documentation to create a new token for this usage.

Assumptions:

  • <YourSuperNtfyToken> is the generated token via ntfy cli
  • <your.ntfy.domain.tld> is the fqdn where ntfy is installed with https
  • <ntfyChannel> is the dedicated ntfy channel where the alert are sent

First, let’s create a simple bash script that will send the notification. I put it in /usr/bin/ntfy-ssh-login.sh:

#!/bin/bash
machine_name=$(uname -n)

if [ "${PAM_TYPE}" = "open_session" ]; then
  curl \
    -H "X-Tags: warning,ssh" \
    -H "Authorization: Bearer <YourSuperNtfyToken>" \
    -d "[${machine_name}] SSH login: ${PAM_USER} from ${PAM_RHOST}" \
    https://<your.ntfy.domain.tld>/<ntfyChannel>
fi

Don’t forget to make it executable:

chmod +x /usr/bin/ntfy-ssh-login.sh

You can test it by using the curl command in your shell directly. In this case, the PAM related variable will be empty, but the point is to test that the curl command works with the given token.

Then, to tell PAM (Pluggable Authentication Modules) to use the script on login, edit /etc/pam.d/sshd and add at the bottom:

session optional pam_exec.so /usr/bin/ntfy-ssh-login.sh

You will now recieve a notification each time you connect to your server via ssh.

While this could be annoying for some people to receive too many notifications, I’ve learned to ignore them when actively connecting to any of my machine and quickly remove them to avoid future surprise. The good news is that so far, I’ve never received an unwanted notification from that script :).


Contact

If you find any issue or have any question about this article, feel free to reach out to me via webmentions, email, mastodon, matrix or even IRC, see the About page for details.