132 lines
7.4 KiB
Python
132 lines
7.4 KiB
Python
#!/usr/bin/python3
|
|
"""Run only inside a private mount namespace; no host config changes."""
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import socket
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
|
|
import pexpect
|
|
|
|
root = pathlib.Path(__file__).resolve().parent.parent
|
|
if os.environ.get('DUO_NS') != '1':
|
|
if os.geteuid() != 0:
|
|
sys.exit('requires root and mount namespace privileges')
|
|
with tempfile.TemporaryDirectory(prefix='duo-e2e-', dir='/root') as td:
|
|
os.chmod(td, 0o755)
|
|
for name in ('etc-upper', 'etc-work', 'var-upper', 'var-work'):
|
|
os.mkdir(os.path.join(td, name), 0o755)
|
|
os.chmod(os.path.join(td, name), 0o755)
|
|
env = dict(os.environ, DUO_NS='1', DUO_TMP=td)
|
|
subprocess.run(['unshare', '-m', sys.executable, __file__], env=env, check=True)
|
|
sys.exit()
|
|
|
|
td = pathlib.Path(os.environ['DUO_TMP'])
|
|
subprocess.run(['mount', '--make-rprivate', '/'], check=True)
|
|
for target, prefix in [('/etc', 'etc'), ('/var/lib', 'var')]:
|
|
subprocess.run(['mount', '-t', 'overlay', 'overlay', '-o', f'lowerdir={target},upperdir={td}/{prefix}-upper,workdir={td}/{prefix}-work', target], check=True)
|
|
user = 'duo_e2e_test'
|
|
password = 'TEST-password-582934!'
|
|
secret = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'
|
|
passwd_hash = subprocess.run(['openssl', 'passwd', '-6', '-stdin'], input=password + '\n', text=True, capture_output=True, check=True).stdout.strip()
|
|
with open('/etc/passwd', 'a') as f: f.write(f'\n{user}:x:19389:19389::/tmp:/bin/sh\n')
|
|
with open('/etc/shadow', 'a') as f: f.write(f'\n{user}:{passwd_hash}:20000:0:99999:7:::\n')
|
|
with open('/etc/group', 'a') as f: f.write(f'\n{user}:x:19389:\n')
|
|
os.mkdir('/etc/duo-ssh', 0o700)
|
|
os.mkdir('/var/lib/duo-ssh', 0o700)
|
|
with open('/etc/duo-ssh/config.json', 'w') as f: json.dump({'users': {user: {'totp_secret': secret}}}, f)
|
|
os.chmod('/etc/duo-ssh/config.json', 0o600)
|
|
helper = td / 'helper.py'
|
|
helper.write_bytes((root / 'duo_ssh.py').read_bytes())
|
|
os.chmod(helper, 0o755)
|
|
module = td / 'pam_duo_ssh.so'
|
|
subprocess.run(['cc', '-O2', '-Wall', '-Wextra', '-Werror', '-fPIC', '-shared', '-DDUO_HELPER="' + str(helper) + '"', '-o', str(module), str(root / 'pam_duo_ssh.c')], check=True)
|
|
with open('/etc/pam.d/sshd', 'w') as f:
|
|
f.write(f'auth requisite pam_unix.so\nauth requisite {module}\naccount required pam_unix.so\nsession required pam_permit.so\n')
|
|
# Exercise the real pam_unix -> duo helper stack independently of sshd.
|
|
harness = td / 'pam_real'
|
|
subprocess.run(['cc', '-Wall', '-Wextra', '-Werror', '-o', str(harness), str(root / 'tests/pam_real.c'), '-Wl,-l:libpam.so.0'], check=True)
|
|
(td / 'duotest').write_text(f'auth requisite pam_unix.so\nauth requisite {module}\n')
|
|
def totp_at(step):
|
|
digest = hmac.new(base64.b32decode(secret), struct.pack('>Q', step), hashlib.sha1).digest()
|
|
offset = digest[-1] & 15
|
|
return f'{(int.from_bytes(digest[offset:offset+4], "big") & 0x7fffffff) % 1000000:06d}'
|
|
def pam_check(pwd, otp, expected_rc, prompts):
|
|
result = subprocess.run([str(harness), str(td), user, pwd, otp], text=True, capture_output=True)
|
|
assert result.returncode == expected_rc and f'prompts={prompts}' in result.stdout, (result.returncode, result.stdout, result.stderr)
|
|
valid = totp_at(int(time.time()) // 30)
|
|
pam_check('bad-password', valid, 1, 1)
|
|
pam_check(password, 'invalid', 1, 2)
|
|
pam_check(password, valid, 0, 2)
|
|
pam_check(password, valid, 1, 2)
|
|
print('Real PAM stack passed: bad password stops before OTP; correct password + OTP accepted; bad OTP and replay rejected', flush=True)
|
|
# Reset test-only state for the independent SSH scenario.
|
|
for state in pathlib.Path('/var/lib/duo-ssh').iterdir(): state.unlink()
|
|
key = td / 'key'
|
|
hostkey = td / 'hostkey'
|
|
for path in (key, hostkey):
|
|
subprocess.run(['ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-f', str(path)], check=True)
|
|
authorized = td / 'authorized_keys'
|
|
authorized.write_bytes(pathlib.Path(str(key) + '.pub').read_bytes())
|
|
with socket.socket() as sock:
|
|
sock.bind(('127.0.0.1', 0))
|
|
port = sock.getsockname()[1]
|
|
config = td / 'sshd_config'
|
|
config.write_text(f'''Port {port}
|
|
ListenAddress 127.0.0.1
|
|
HostKey {hostkey}
|
|
PidFile {td}/sshd.pid
|
|
AuthorizedKeysFile {authorized}
|
|
StrictModes no
|
|
UsePAM yes
|
|
KbdInteractiveAuthentication yes
|
|
PasswordAuthentication no
|
|
PubkeyAuthentication yes
|
|
AuthenticationMethods keyboard-interactive:pam
|
|
MaxAuthTries 1
|
|
PermitRootLogin no
|
|
AllowUsers {user}
|
|
PrintMotd no
|
|
LogLevel VERBOSE
|
|
''')
|
|
subprocess.run(['/usr/sbin/sshd', '-t', '-f', str(config)], check=True)
|
|
effective = subprocess.run(['/usr/sbin/sshd', '-T', '-f', str(config)], check=True, text=True, capture_output=True).stdout.splitlines()
|
|
for option in ('usepam yes', 'kbdinteractiveauthentication yes', 'passwordauthentication no', 'authenticationmethods keyboard-interactive:pam', 'maxauthtries 1'):
|
|
assert option in effective, option
|
|
print('sshd effective test configuration checked; key-only is not an allowed authentication method', flush=True)
|
|
server = subprocess.Popen(['/usr/sbin/sshd', '-D', '-e', '-f', str(config)], stdout=subprocess.DEVNULL, stderr=sys.stderr)
|
|
try:
|
|
for _ in range(100):
|
|
if server.poll() is not None: raise RuntimeError('sshd failed')
|
|
try:
|
|
with socket.create_connection(('127.0.0.1', port), timeout=0.1): break
|
|
except OSError: time.sleep(.05)
|
|
else: raise RuntimeError('sshd did not start')
|
|
args = ['-F', '/dev/null', '-p', str(port), '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'LogLevel=ERROR', '-o', 'ConnectTimeout=3', '-o', 'PreferredAuthentications=keyboard-interactive', f'{user}@127.0.0.1', 'echo E2E_OK']
|
|
def start(): return pexpect.spawn('/usr/bin/ssh', args, encoding='utf-8', timeout=10)
|
|
def code():
|
|
digest = hmac.new(base64.b32decode(secret), struct.pack('>Q', int(time.time()) // 30), hashlib.sha1).digest()
|
|
offset = digest[-1] & 15
|
|
return f'{(int.from_bytes(digest[offset:offset+4], "big") & 0x7fffffff) % 1000000:06d}'
|
|
child = start(); child.expect('[Pp]assword:'); child.sendline('bad-password'); child.expect(pexpect.EOF)
|
|
assert 'Telegram or Google code:' not in child.before
|
|
child.close(); assert child.exitstatus != 0
|
|
child = start(); child.expect('[Pp]assword:'); child.sendline(password); child.expect('Telegram or Google code:'); child.sendline('invalid'); child.expect(pexpect.EOF)
|
|
assert 'Telegram or Google code:' not in child.before
|
|
child.close(); assert child.exitstatus != 0
|
|
child = start(); child.expect('[Pp]assword:'); child.sendline(password); child.expect('Telegram or Google code:'); value = code(); child.sendline(value); child.expect('E2E_OK'); child.expect(pexpect.EOF); child.close(); assert child.exitstatus == 0
|
|
child = start(); child.expect('[Pp]assword:'); child.sendline(password); child.expect('Telegram or Google code:'); child.sendline(value); child.expect(pexpect.EOF); child.close(); assert child.exitstatus != 0
|
|
result = subprocess.run(['/usr/bin/ssh', '-F', '/dev/null', '-p', str(port), '-i', str(key), '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'LogLevel=ERROR', '-o', 'PreferredAuthentications=publickey', '-o', 'BatchMode=yes', f'{user}@127.0.0.1', 'true'], capture_output=True, timeout=10)
|
|
assert result.returncode != 0
|
|
print('SSH E2E passed: password order, wrong password, invalid OTP disconnect, TOTP success, replay rejection, public-key-only rejected')
|
|
finally:
|
|
server.terminate()
|
|
server.wait(timeout=5)
|