PlotDirector/Tools/Deployment/ssh_dispatch.py

75 lines
3.4 KiB
Python

#!/usr/bin/python3 -I
"""Forced SSH command for plotdirector-deploy; no shell, SFTP or arbitrary paths."""
import os
from pathlib import Path
import re
import subprocess
import sys
import tarfile
import fcntl
import resource
import signal
import shutil
import stat
INBOX=Path('/srv/plotdirector/incoming')
LIMIT=4*1024**3
UPLOAD_LOCK=Path('/srv/plotdirector/incoming-upload.lock')
FREE_FLOOR=10*1024**3
def main():
os.umask(0o077)
# sshd ForceCommand passes the requested text as data, never to a shell here.
original=os.environ.get('SSH_ORIGINAL_COMMAND','')
match=re.fullmatch(r'(upload|validate|activate|rollback) ([A-Za-z0-9][A-Za-z0-9_.-]{0,99})',original)
if not match or match[2] in ('.','..'):
raise ValueError('Unsupported deployment operation')
operation,release=match.groups()
if operation!='upload':
args=['/usr/bin/sudo','-n','/usr/local/sbin/deploy-plotdirector']
if operation=='validate':args.append('--validate')
if operation=='rollback':args.append('--rollback')
args.append(release)
raise SystemExit(subprocess.run(args,env={'PATH':'/usr/sbin:/usr/bin:/sbin:/bin','LANG':'C.UTF-8'},cwd='/').returncode)
# These limits apply only to unprivileged transfer, never to the activation
# worker/.NET subprocess. Serialize uploads and retain space for other sites.
resource.setrlimit(resource.RLIMIT_AS,(256*1024**2,256*1024**2))
resource.setrlimit(resource.RLIMIT_CPU,(120,120))
signal.alarm(1800)
os.nice(10)
lock=os.open(UPLOAD_LOCK,os.O_RDWR|os.O_NOFOLLOW)
info=os.fstat(lock)
if not stat.S_ISREG(info.st_mode) or info.st_uid!=0 or info.st_nlink!=1 or info.st_mode&0o007:
raise ValueError('Invalid protected upload lock')
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if shutil.disk_usage(INBOX).free<FREE_FLOOR+LIMIT:raise ValueError('Insufficient staging space')
destination=INBOX/release
destination.mkdir(mode=0o700) # Refuses replacement, including symlinks.
received=set()
total=0
with tarfile.open(fileobj=sys.stdin.buffer,mode='r|') as tar:
for member in tar:
if member.name not in ('package.tar','authorization.json','authorization.sig') or member.name in received or not member.isfile() or member.linkname or member.pax_headers:
raise ValueError('Invalid transfer member')
received.add(member.name)
limit=LIMIT if member.name=='package.tar' else 16384
if not 0<=member.size<=limit:raise ValueError('Transfer size exceeded')
total+=member.size
if total>LIMIT+32768:raise ValueError('Transfer size exceeded')
with tar.extractfile(member) as source,(destination/member.name).open('xb') as target:
while block:=source.read(1024**2):
if shutil.disk_usage(INBOX).free<FREE_FLOOR+len(block):raise ValueError('Staging space floor reached')
target.write(block)
target.flush();os.fsync(target.fileno())
if received!={'package.tar','authorization.json','authorization.sig'}:
raise ValueError('Incomplete transfer; administrator must remove the incomplete incoming directory before retry')
print('UPLOADED '+release+'; activation has not been performed')
if __name__=='__main__':
try:main()
except Exception:
print('DEPLOYMENT REQUEST REFUSED; no command was shell-evaluated',file=sys.stderr)
sys.exit(1)