176 lines
6.6 KiB
Python
176 lines
6.6 KiB
Python
#!/usr/bin/python3
|
|
"""PAM helper: one challenge, one answer, fail closed."""
|
|
import base64
|
|
import fcntl
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import os
|
|
import secrets
|
|
import socket
|
|
import subprocess
|
|
import stat
|
|
import struct
|
|
import sys
|
|
import time
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
CONFIG = '/etc/duo-ssh/config.json'
|
|
STATE = '/var/lib/duo-ssh'
|
|
|
|
|
|
def secure_directory(path):
|
|
"""Open every component without symlinks or writable ancestors."""
|
|
if not os.path.isabs(path):
|
|
raise ValueError('absolute path required')
|
|
fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC)
|
|
try:
|
|
for part in path.split('/'):
|
|
if not part:
|
|
continue
|
|
if part in ('.', '..'):
|
|
raise ValueError('invalid path')
|
|
next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=fd)
|
|
os.close(fd)
|
|
fd = next_fd
|
|
info = os.fstat(fd)
|
|
if info.st_uid != 0 or info.st_mode & 0o022:
|
|
raise ValueError('unsafe directory')
|
|
return fd
|
|
except BaseException:
|
|
os.close(fd)
|
|
raise
|
|
|
|
|
|
def secure_file(path):
|
|
directory = secure_directory(os.path.dirname(path))
|
|
try:
|
|
fd = os.open(os.path.basename(path), os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=directory)
|
|
finally:
|
|
os.close(directory)
|
|
with os.fdopen(fd, 'r', encoding='utf-8') as file:
|
|
info = os.fstat(file.fileno())
|
|
if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o077:
|
|
raise ValueError('unsafe file')
|
|
return json.load(file)
|
|
|
|
|
|
def totp(secret, counter):
|
|
key = base64.b32decode(secret.upper() + '=' * (-len(secret) % 8), casefold=True)
|
|
digest = hmac.new(key, struct.pack('>Q', counter), hashlib.sha1).digest()
|
|
pos = digest[-1] & 15
|
|
return f'{(struct.unpack(">I", digest[pos:pos+4])[0] & 0x7fffffff) % 1000000:06d}'
|
|
|
|
|
|
def use_totp(user, secret, code, now):
|
|
current = int(now // 30)
|
|
matches = [step for step in range(current - 1, current + 2)
|
|
if step >= 0 and hmac.compare_digest(totp(secret, step), code)]
|
|
if not matches:
|
|
return False
|
|
# Scope replay protection to the key, including when multiple users share it.
|
|
key = base64.b32decode(secret.upper() + '=' * (-len(secret) % 8), casefold=True)
|
|
name = hashlib.sha256(key).hexdigest()
|
|
directory = secure_directory(STATE)
|
|
try:
|
|
info = os.fstat(directory)
|
|
if info.st_mode & 0o077:
|
|
raise ValueError('unsafe state directory')
|
|
fd = os.open(name + '.lock', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600, dir_fd=directory)
|
|
with os.fdopen(fd, 'r+') as lock:
|
|
info = os.fstat(lock.fileno())
|
|
if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o077:
|
|
raise ValueError('unsafe lock')
|
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
try:
|
|
statefd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=directory)
|
|
except FileNotFoundError:
|
|
last = -1
|
|
else:
|
|
with os.fdopen(statefd, 'r', encoding='ascii') as file:
|
|
info = os.fstat(file.fileno())
|
|
if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o077:
|
|
raise ValueError('unsafe state')
|
|
data = file.read(64)
|
|
if not data.isascii() or not data.isdigit():
|
|
raise ValueError('invalid state')
|
|
last = int(data)
|
|
step = max(matches)
|
|
if step <= last:
|
|
return False
|
|
temp = name + '.' + secrets.token_hex(16)
|
|
tempfd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600, dir_fd=directory)
|
|
try:
|
|
with os.fdopen(tempfd, 'w', encoding='ascii') as file:
|
|
file.write(str(step))
|
|
file.flush()
|
|
os.fsync(file.fileno())
|
|
os.replace(temp, name, src_dir_fd=directory, dst_dir_fd=directory)
|
|
os.fsync(directory)
|
|
finally:
|
|
try:
|
|
os.unlink(temp, dir_fd=directory)
|
|
except FileNotFoundError:
|
|
pass
|
|
return True
|
|
finally:
|
|
os.close(directory)
|
|
|
|
|
|
def server_identity():
|
|
hostname = socket.gethostname()
|
|
try:
|
|
result = subprocess.run(['/usr/sbin/ip', '-j', 'address', 'show', 'scope', 'global'],
|
|
capture_output=True, text=True, timeout=2, check=True)
|
|
addresses = sorted({entry['local'] for interface in json.loads(result.stdout)
|
|
for entry in interface.get('addr_info', []) if entry.get('local')})
|
|
except (OSError, ValueError, KeyError, subprocess.SubprocessError):
|
|
addresses = []
|
|
return hostname, ', '.join(addresses) or 'unavailable'
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) != 2:
|
|
return False
|
|
user = sys.argv[1]
|
|
config = secure_file(CONFIG)
|
|
item = config['users'][user]
|
|
token, chat, secret = item.get('telegram_token', ''), item.get('telegram_chat_id', ''), item.get('totp_secret', '')
|
|
if not secret and not (token and chat):
|
|
return False
|
|
directory = secure_directory(STATE)
|
|
try:
|
|
if os.fstat(directory).st_mode & 0o077:
|
|
return False
|
|
finally:
|
|
os.close(directory)
|
|
code = f'{secrets.randbelow(1000000):06d}'
|
|
sent = False
|
|
if token and chat:
|
|
try:
|
|
hostname, addresses = server_identity()
|
|
body = urllib.parse.urlencode({'chat_id': str(chat), 'text': f'SSH code: {code}\nUser: {user}\nServer: {hostname}\nServer local IPs: {addresses}\nValid for 300 seconds.'}).encode()
|
|
request = urllib.request.Request(f'https://api.telegram.org/bot{token}/sendMessage', data=body)
|
|
with urllib.request.urlopen(request, timeout=5) as response:
|
|
sent = response.status == 200 and json.load(response).get('ok') is True
|
|
except Exception:
|
|
pass
|
|
if not sent and not secret:
|
|
return False
|
|
expiry = time.monotonic() + 300
|
|
print('READY', flush=True)
|
|
answer = sys.stdin.readline(32).strip()
|
|
if len(answer) != 6 or not answer.isascii() or not answer.isdigit() or time.monotonic() >= expiry:
|
|
return False
|
|
if sent and hmac.compare_digest(code, answer):
|
|
return True
|
|
return bool(secret and use_totp(user, secret, answer, time.time()))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
sys.exit(0 if main() else 1)
|
|
except Exception:
|
|
sys.exit(1)
|