54 lines
2.4 KiB
Python
54 lines
2.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
|
|
|
|
INBOX=Path('/srv/plotdirector/incoming')
|
|
LIMIT=4*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)
|
|
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):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)
|