Server/ssh: send a message to discord on login

This commit is contained in:
Toast 2024-11-10 18:58:25 +01:00
parent aa17ed51c8
commit 3c72a10ec0
2 changed files with 41 additions and 4 deletions

8
flake.lock generated
View file

@ -593,11 +593,11 @@
"secrets": {
"flake": false,
"locked": {
"lastModified": 1726137390,
"narHash": "sha256-RaTOgscAl0pnAT/1DwyitTfFNwFDPZaqN/vTaqAoCTM=",
"lastModified": 1731258517,
"narHash": "sha256-zqYyWyZYK2FsRhqDRaZPmP6IqJ6QRXK37jthHcMAe+8=",
"ref": "refs/heads/main",
"rev": "994526ba9affd6e6d617b1743126a36846530c93",
"revCount": 24,
"rev": "4d6184cf5e78978e26839690af7e1a3ff9af92ae",
"revCount": 25,
"type": "git",
"url": "ssh://forgejo@git.everest.tailscale:4222/Toast/nix-secrets"
},

View file

@ -1,10 +1,40 @@
{
flakeSelf,
config,
pkgs,
lib,
...
}: let
hostSecrets = "${flakeSelf.inputs.secrets}/" + config.networking.hostName + "/";
hostKeyPath = "/etc/ssh/everest_host_key";
notify =
pkgs.writers.writePython3 "send-discord-login-notification" {
libraries = [pkgs.python3Packages.requests];
} ''
import requests
import os
if os.environ["PAM_TYPE"] != "open_session":
raise SystemExit
print("User logging in")
secretPath = "${config.age.secrets.discord-webhook.path}"
webhookUrl: str
with open(secretPath) as file:
webhookUrl = file.read().strip()
user = os.environ["PAM_USER"]
rhost = os.environ["PAM_RHOST"]
data = {
"username": "SSH Login",
"content": user + " logged in from " + rhost
}
result = requests.post(webhookUrl, json=data)
'';
in {
age.secrets = {
everest-host-key = {
@ -16,6 +46,9 @@ in {
file = hostSecrets + "host-public-key.age";
path = hostKeyPath + ".pub";
};
discord-webhook = {
file = hostSecrets + "discord-webhook.age";
};
};
users.users.toast.openssh.authorizedKeys.keys = [
@ -43,4 +76,8 @@ in {
];
startWhenNeeded = true;
};
security.pam.services.sshd.text = lib.mkDefault (lib.mkAfter ''
session optional pam_exec.so debug stdout ${builtins.trace notify.outPath notify}
'');
}