Compare commits
6 Commits
auth-daemo
...
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
b2d9400f0e
|
|||
|
2838c584d3
|
|||
|
ce75aa509d
|
|||
|
87ef63b680
|
|||
|
6686b3bbe7
|
|||
|
f75b34f40c
|
@@ -1,12 +1,11 @@
|
||||
[package]
|
||||
name = "muscl"
|
||||
version = "0.1.0"
|
||||
version = "1.0.0"
|
||||
edition = "2024"
|
||||
resolver = "2"
|
||||
license = "BSD-3-Clause"
|
||||
authors = [
|
||||
"oysteikt@pvv.ntnu.no",
|
||||
"felixalb@pvv.ntnu.no",
|
||||
"Programvareverkstedet <projects@pvv.ntnu.no>",
|
||||
]
|
||||
homepage = "https://git.pvv.ntnu.no/Projects/muscl"
|
||||
repository = "https://git.pvv.ntnu.no/Projects/muscl"
|
||||
|
||||
@@ -3,6 +3,7 @@ Description=Muscl MySQL admin tool
|
||||
|
||||
[Socket]
|
||||
ListenStream=/run/muscl/muscl.sock
|
||||
RemoveOnStop=true
|
||||
Accept=no
|
||||
PassCredentials=true
|
||||
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
[Unit]
|
||||
Description=Authorization daemon for Muscl
|
||||
|
||||
[Service]
|
||||
Type=notify
|
||||
ExecStart=/usr/local/bin/muscl_auth_daemon.py
|
||||
|
||||
# WatchdogSec=15
|
||||
|
||||
User=muscl
|
||||
Group=muscl
|
||||
DynamicUser=yes
|
||||
|
||||
; ConfigurationDirectory=muscl
|
||||
; RuntimeDirectory=muscl
|
||||
|
||||
; # This is required to read unix user/group details.
|
||||
; PrivateUsers=false
|
||||
|
||||
; # Needed to communicate with MySQL.
|
||||
; PrivateNetwork=false
|
||||
; PrivateIPC=false
|
||||
|
||||
; AmbientCapabilities=
|
||||
; CapabilityBoundingSet=
|
||||
; DeviceAllow=
|
||||
; DevicePolicy=closed
|
||||
; LockPersonality=true
|
||||
; MemoryDenyWriteExecute=true
|
||||
; NoNewPrivileges=true
|
||||
; PrivateDevices=true
|
||||
; PrivateMounts=true
|
||||
; PrivateTmp=yes
|
||||
; ProcSubset=pid
|
||||
; ProtectClock=true
|
||||
; ProtectControlGroups=strict
|
||||
; ProtectHome=true
|
||||
; ProtectHostname=true
|
||||
; ProtectKernelLogs=true
|
||||
; ProtectKernelModules=true
|
||||
; ProtectKernelTunables=true
|
||||
; ProtectProc=invisible
|
||||
; ProtectSystem=strict
|
||||
; RemoveIPC=true
|
||||
; RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
||||
; RestrictNamespaces=true
|
||||
; RestrictRealtime=true
|
||||
; RestrictSUIDSGID=true
|
||||
; SocketBindDeny=any
|
||||
; SystemCallArchitectures=native
|
||||
; SystemCallFilter=@system-service
|
||||
; SystemCallFilter=~@privileged @resources
|
||||
; UMask=0777
|
||||
@@ -1,8 +0,0 @@
|
||||
[Unit]
|
||||
Description=Authorization daemon for Muscl
|
||||
WantedBy=sockets.target
|
||||
|
||||
[Socket]
|
||||
ListenStream=/run/muscl/muscl-auth-daemon.socket
|
||||
Accept=no
|
||||
SocketMode=0660
|
||||
@@ -1,84 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# TODO: create pool of workers to handle requests concurrently
|
||||
# the socket should be a listener socket and each worker should accept connections from it
|
||||
# the socket should accept requests as newline-separated JSON objects
|
||||
# there should be a watchdog to monitor worker health and restart them if they die
|
||||
# graceful shutdown should be implemented for the workers
|
||||
# optional logging of requests and responses
|
||||
# use systemd notify to signal readiness and amount of connections handled
|
||||
|
||||
import json
|
||||
import os
|
||||
from socket import AF_UNIX, SOCK_DGRAM, SOCK_STREAM, fromfd, socket
|
||||
from multiprocessing import Pool
|
||||
|
||||
|
||||
def get_listener_from_systemd() -> socket:
|
||||
listen_fds = int(os.getenv("LISTEN_FDS", "0"))
|
||||
listen_pid = int(os.getenv("LISTEN_PID", "0"))
|
||||
if listen_fds != 1 or listen_pid != os.getpid():
|
||||
raise RuntimeError("No socket passed from systemd")
|
||||
assert listen_fds == 1
|
||||
sock = fromfd(3, AF_UNIX, SOCK_STREAM)
|
||||
sock.setblocking(False)
|
||||
return sock
|
||||
|
||||
|
||||
def get_notify_socket_from_systemd() -> socket:
|
||||
notify_socket_path = os.getenv("NOTIFY_SOCKET")
|
||||
if not notify_socket_path:
|
||||
raise RuntimeError("No notify socket path found in environment")
|
||||
sock = socket(AF_UNIX, SOCK_DGRAM)
|
||||
sock.connect(notify_socket_path)
|
||||
return sock
|
||||
|
||||
|
||||
def run_auth_daemon(sock: socket):
|
||||
sock.listen()
|
||||
print("Auth daemon is running and listening for connections...")
|
||||
with Pool() as worker_pool:
|
||||
with get_notify_socket_from_systemd() as notify_socket:
|
||||
notify_socket.sendall(b"READY=1\n")
|
||||
while True:
|
||||
conn, _ = sock.accept()
|
||||
worker_pool.apply_async(session_handler, args=(conn,))
|
||||
|
||||
|
||||
def session_handler(sock: socket):
|
||||
buffer = ""
|
||||
while True:
|
||||
data = sock.recv(4096).decode("utf-8")
|
||||
if not data:
|
||||
print("Connection closed by client")
|
||||
break
|
||||
buffer += data
|
||||
if buffer.endswith("\n"):
|
||||
requests = buffer.strip().split("\n")
|
||||
buffer = ""
|
||||
for request in requests:
|
||||
try:
|
||||
req_json = json.loads(request)
|
||||
username = req_json.get("username", "")
|
||||
groups = req_json.get("groups", [])
|
||||
resource_type = req_json.get("resource_type", "")
|
||||
resource = req_json.get("resource", "")
|
||||
allowed = process_request(username, groups, resource_type, resource)
|
||||
response = {"allowed": allowed}
|
||||
except json.JSONDecodeError:
|
||||
response = {"error": "Invalid JSON"}
|
||||
sock.sendall((json.dumps(response) + "\n").encode("utf-8"))
|
||||
|
||||
|
||||
def process_request(
|
||||
username: str,
|
||||
groups: list[str],
|
||||
resource_type: str,
|
||||
resource: str,
|
||||
) -> bool:
|
||||
...
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
listener_socket = get_listener_from_systemd()
|
||||
run_auth_daemon(listener_socket)
|
||||
@@ -105,7 +105,6 @@
|
||||
fileset = lib.fileset.unions [
|
||||
(craneLib.fileset.commonCargoSources ./.)
|
||||
./assets
|
||||
./examples
|
||||
];
|
||||
};
|
||||
in {
|
||||
|
||||
@@ -85,9 +85,6 @@ buildFunction ({
|
||||
install -Dm644 assets/systemd/muscl.service -t "$out/lib/systemd/system"
|
||||
substituteInPlace "$out/lib/systemd/system/muscl.service" \
|
||||
--replace-fail '/usr/bin/muscl-server' "$out/bin/muscl-server"
|
||||
|
||||
mkdir -p "$out/share/muscl"
|
||||
cp -r examples "$out/share/muscl"
|
||||
'';
|
||||
|
||||
meta = with lib; {
|
||||
|
||||
@@ -27,31 +27,6 @@ in
|
||||
}.${level};
|
||||
};
|
||||
|
||||
authHandler = lib.mkOption {
|
||||
type = with lib.types; nullOr lines;
|
||||
default = null;
|
||||
description = "Custom authentication handler, written in python";
|
||||
example = ''
|
||||
def process_request(
|
||||
username: str,
|
||||
groups: list[str],
|
||||
resource_type: str,
|
||||
resource: str,
|
||||
) -> bool:
|
||||
if resource_type == "database":
|
||||
if resource.startswith(username) or any(
|
||||
resource.startswith(group) for group in groups
|
||||
):
|
||||
return True
|
||||
elif resource_type == "user":
|
||||
if resource.startswith(username) or any(
|
||||
resource.startswith(group) for group in groups
|
||||
):
|
||||
return True
|
||||
return False
|
||||
'';
|
||||
};
|
||||
|
||||
settings = lib.mkOption {
|
||||
default = { };
|
||||
type = lib.types.submodule {
|
||||
@@ -216,72 +191,5 @@ in
|
||||
++ (lib.optionals (cfg.settings.mysql.host != null) [ "AF_INET" "AF_INET6" ]);
|
||||
};
|
||||
};
|
||||
|
||||
systemd.sockets."muscl-auth-daemon" = lib.mkIf (cfg.authHandler != null) {
|
||||
description = "Authorization daemon for Muscl";
|
||||
wantedBy = [ "sockets.target" ];
|
||||
socketConfig = {
|
||||
ListenStream = "/run/muscl/muscl-auth-daemon.sock";
|
||||
Accept = "no";
|
||||
};
|
||||
};
|
||||
|
||||
systemd.services."muscl-auth-daemon" = lib.mkIf (cfg.authHandler != null) {
|
||||
description = "Authorization daemon for Muscl";
|
||||
requires = [ "muscl-auth-daemon.socket" ];
|
||||
serviceConfig = {
|
||||
Type = "notify";
|
||||
ExecStart = let
|
||||
authScript = lib.pipe ../examples/auth_daemon_python/muscl_auth_daemon.py [
|
||||
lib.fileContents
|
||||
(lib.replaceString ''
|
||||
def process_request(
|
||||
username: str,
|
||||
groups: list[str],
|
||||
resource_type: str,
|
||||
resource: str,
|
||||
) -> bool:
|
||||
...
|
||||
'' cfg.authHandler)
|
||||
(pkgs.writers.writePyPy3Bin "muscl-auth-handler.py" { })
|
||||
];
|
||||
in lib.getExe authScript;
|
||||
|
||||
User = "muscl-auth-daemon";
|
||||
Group = "muscl-auth-daemon";
|
||||
DynamicUser = true;
|
||||
|
||||
AmbientCapabilities = [ "" ];
|
||||
CapabilityBoundingSet = [ "" ];
|
||||
DeviceAllow = [ "" ];
|
||||
LockPersonality = true;
|
||||
NoNewPrivileges = true;
|
||||
PrivateDevices = true;
|
||||
PrivateMounts = true;
|
||||
PrivateTmp = "yes";
|
||||
ProcSubset = "pid";
|
||||
ProtectClock = true;
|
||||
ProtectControlGroups = "strict";
|
||||
ProtectHome = true;
|
||||
ProtectHostname = true;
|
||||
ProtectKernelLogs = true;
|
||||
ProtectKernelModules = true;
|
||||
ProtectKernelTunables = true;
|
||||
ProtectProc = "invisible";
|
||||
ProtectSystem = "strict";
|
||||
RemoveIPC = true;
|
||||
UMask = "0777";
|
||||
RestrictNamespaces = true;
|
||||
RestrictRealtime = true;
|
||||
RestrictSUIDSGID = true;
|
||||
SystemCallArchitectures = "native";
|
||||
SocketBindDeny = [ "any" ];
|
||||
SystemCallFilter = [
|
||||
"@system-service"
|
||||
"~@privileged"
|
||||
"~@resources"
|
||||
];
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -56,25 +56,6 @@ nixpkgs.lib.nixosSystem {
|
||||
enable = true;
|
||||
logLevel = "trace";
|
||||
createLocalDatabaseUser = true;
|
||||
authHandler = ''
|
||||
def process_request(
|
||||
username: str,
|
||||
groups: list[str],
|
||||
resource_type: str,
|
||||
resource: str,
|
||||
) -> bool:
|
||||
if resource_type == "database":
|
||||
if resource.startswith(username) or any(
|
||||
resource.startswith(group) for group in groups
|
||||
):
|
||||
return True
|
||||
elif resource_type == "user":
|
||||
if resource.startswith(username) or any(
|
||||
resource.startswith(group) for group in groups
|
||||
):
|
||||
return True
|
||||
return False
|
||||
'';
|
||||
};
|
||||
|
||||
programs.vim = {
|
||||
|
||||
@@ -54,11 +54,13 @@ for variant in debian-bookworm debian-trixie ubuntu-jammy ubuntu-noble; do
|
||||
DEB_VERSION=$(find "$TMPDIR/muscl-deb-$variant-$GIT_SHA"/*.deb -print0 | xargs -0 -n1 basename | cut -d'_' -f2 | head -n1)
|
||||
DEB_ARCH=$(find "$TMPDIR/muscl-deb-$variant-$GIT_SHA"/*.deb -print0 | xargs -0 -n1 basename | cut -d'_' -f3 | cut -d'.' -f1 | head -n1)
|
||||
|
||||
echo "[DELETE] https://git.pvv.ntnu.no/api/packages/Projects/debian/pool/$DISTRO_VERSION_NAME/main/$DEB_NAME/$DEB_VERSION/$DEB_ARCH"
|
||||
curl \
|
||||
-X DELETE \
|
||||
--user "$GITEA_USER:$GITEA_TOKEN" \
|
||||
"https://git.pvv.ntnu.no/api/packages/Projects/debian/pool/$DISTRO_VERSION_NAME/main/$DEB_NAME/$DEB_VERSION/$DEB_ARCH"
|
||||
|
||||
echo "[PUT] https://git.pvv.ntnu.no/api/packages/Projects/debian/pool/$DISTRO_VERSION_NAME/main/upload"
|
||||
curl \
|
||||
-X PUT \
|
||||
--user "$GITEA_USER:$GITEA_TOKEN" \
|
||||
|
||||
@@ -319,7 +319,8 @@ fn main() -> anyhow::Result<()> {
|
||||
#[cfg(not(feature = "suid-sgid-mode"))]
|
||||
None,
|
||||
args.verbose,
|
||||
)?;
|
||||
)
|
||||
.context("Failed to connect to the server")?;
|
||||
|
||||
tokio_run_command(args.command, connection)?;
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::FileTypeExt,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
@@ -7,7 +8,10 @@ use std::{
|
||||
|
||||
use anyhow::{Context, anyhow};
|
||||
use clap_verbosity_flag::{InfoLevel, Verbosity};
|
||||
use nix::libc::{EXIT_SUCCESS, exit};
|
||||
use nix::{
|
||||
libc::{EXIT_SUCCESS, exit},
|
||||
unistd::{AccessFlags, access},
|
||||
};
|
||||
use sqlx::mysql::MySqlPoolOptions;
|
||||
use std::os::unix::net::UnixStream as StdUnixStream;
|
||||
use tokio::{net::UnixStream as TokioUnixStream, sync::RwLock};
|
||||
@@ -130,11 +134,28 @@ pub fn bootstrap_server_connection_and_drop_privileges(
|
||||
}
|
||||
}
|
||||
|
||||
fn socket_path_is_ok(path: &Path) -> anyhow::Result<()> {
|
||||
fs::metadata(path)
|
||||
.context(format!("Failed to get metadata for {:?}", path))
|
||||
.and_then(|meta| {
|
||||
if !meta.file_type().is_socket() {
|
||||
anyhow::bail!("{:?} is not a unix socket", path);
|
||||
}
|
||||
|
||||
access(path, AccessFlags::R_OK | AccessFlags::W_OK)
|
||||
.with_context(|| format!("Socket at {:?} is not readable/writable", path))?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn connect_to_external_server(
|
||||
server_socket_path: Option<PathBuf>,
|
||||
) -> anyhow::Result<StdUnixStream> {
|
||||
// TODO: ensure this is both readable and writable
|
||||
if let Some(socket_path) = server_socket_path {
|
||||
tracing::trace!("Checking socket at {:?}", socket_path);
|
||||
socket_path_is_ok(&socket_path)?;
|
||||
|
||||
tracing::debug!("Connecting to socket at {:?}", socket_path);
|
||||
return match StdUnixStream::connect(socket_path) {
|
||||
Ok(socket) => Ok(socket),
|
||||
@@ -147,6 +168,9 @@ fn connect_to_external_server(
|
||||
}
|
||||
|
||||
if fs::metadata(DEFAULT_SOCKET_PATH).is_ok() {
|
||||
tracing::trace!("Checking socket at {:?}", DEFAULT_SOCKET_PATH);
|
||||
socket_path_is_ok(Path::new(DEFAULT_SOCKET_PATH))?;
|
||||
|
||||
tracing::debug!("Connecting to default socket at {:?}", DEFAULT_SOCKET_PATH);
|
||||
return match StdUnixStream::connect(DEFAULT_SOCKET_PATH) {
|
||||
Ok(socket) => Ok(socket),
|
||||
@@ -158,7 +182,9 @@ fn connect_to_external_server(
|
||||
};
|
||||
}
|
||||
|
||||
anyhow::bail!("No socket path provided, and no default socket found");
|
||||
anyhow::bail!(
|
||||
"No socket path provided, and no socket found found at default location {DEFAULT_SOCKET_PATH}"
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: this function is security critical, it should be integration tested
|
||||
|
||||
@@ -59,6 +59,10 @@ fn parse_group_denylist(denylist_path: &Path, lines: Lines) -> GroupDenylist {
|
||||
}
|
||||
.trim();
|
||||
|
||||
if trimmed_line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let parts: Vec<&str> = trimmed_line.splitn(2, ':').collect();
|
||||
if parts.len() != 2 {
|
||||
tracing::warn!(
|
||||
|
||||
Reference in New Issue
Block a user