81 lines
4.1 KiB
Python
81 lines
4.1 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
|
|
import time
|
|
import json
|
|
from datetime import datetime, timezone
|
|
|
|
INBOX=Path('/srv/plotdirector-website/incoming')
|
|
LIMIT=4*1024**3
|
|
UPLOAD_LOCK=Path('/srv/plotdirector-website/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|receipt) ([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-website-production',operation,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.
|
|
started=time.monotonic()
|
|
started_utc=datetime.now(timezone.utc).isoformat()
|
|
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','package.tar.zst','authorization.json','authorization.sig','transport.json','transport.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)
|
|
if member.name in ('package.tar','package.tar.zst') and received & ({'package.tar','package.tar.zst'}-{member.name}):
|
|
raise ValueError('Ambiguous transport')
|
|
limit=LIMIT if member.name in ('package.tar','package.tar.zst') else 16384
|
|
if not 0<=member.size<=limit:raise ValueError('Transfer size exceeded')
|
|
total+=member.size
|
|
if total>LIMIT+65536: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 not in ({'package.tar','authorization.json','authorization.sig'},{'package.tar.zst','authorization.json','authorization.sig','transport.json','transport.sig'}):
|
|
raise ValueError('Incomplete transfer; administrator must remove the incomplete incoming directory before retry')
|
|
elapsed=time.monotonic()-started
|
|
(destination/'transfer-metrics.json').write_text(json.dumps({'source':'ssh-receiver-unprivileged','started_utc':started_utc,'completed_utc':datetime.now(timezone.utc).isoformat(),'bytes':total,'seconds':elapsed,'mib_per_second':total/elapsed/1024**2}))
|
|
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)
|