| new file mode 100644 |
| index 000000000..8954cb595 |
| --- /dev/null |
| +++ b/scripts/region-group-boot-witness.py |
| @@ -0,0 +1,537 @@ |
| +#!/usr/bin/env python3 |
| +"""Controller-only P3b-1 witness. Default is a local dry run; never applies tofu.""" |
| +import argparse |
| +import base64 |
| +import difflib |
| +import email.policy |
| +from email.parser import BytesParser |
| +import gzip |
| +import hashlib |
| +import io |
| +import json |
| +import os |
| +from pathlib import Path |
| +import re |
| +import secrets |
| +import shlex |
| +import shutil |
| +import signal |
| +import subprocess |
| +import sys |
| +import tarfile |
| +import time |
| + |
| +ROOT = Path(__file__).resolve().parents[1] |
| +SCRATCH = Path('/home/paulca/.cache/p3b1-f4-work') |
| +ACCOUNT = '640012953448' |
| +REGION = 'eu-west-1' |
| +BUCKET = 'carlos-dev-640012953448' |
| +SG = 'sg-0c328faf839a02986' |
| +AMI = 'ami-020434b3e0470d552' |
| +BOOT_KEY = 'bootstrap/dev/ie/carlos-v0.34.2-linux-arm64' |
| +BOOT_VERSION = 'J_BSF6jwEX6Fj3HhbyKvvqpp0lidbDIT' |
| +BOOT_SHA = 'f837b3763457825d469c89cde80fb85fd45f50fd1872a8d53147d53fdebfdc01' |
| +FIXED = {'i-046c7fe43620944bc', 'i-05498eada6f0afd23'} |
| +TGS = [f'arn:aws:elasticloadbalancing:{REGION}:{ACCOUNT}:targetgroup/{x}' for x in |
| + ('carlos-dev-ie-nlb-80/2f5186277337ce74', 'carlos-dev-ie-nlb-443/c33262405df2e5df')] |
| +SUBNET = 'subnet-0975dda9ac0e65347' |
| +MOUNTS = ['/run', '/tmp', '/dev/shm', '/var/tmp', '/var/lib', '/var/lib/cloud', |
| + '/var/lib/carlos-group-boot', '/opt', '/etc', '/data'] |
| +UNITS = ['carlos-edge', 'carlos-hairpin-reset', 'carlos-instance-control', 'nftables', 'chrony'] |
| +# These are incompatible requirements in the implementer brief, not AMI failures. |
| +# No switch bypasses this gate. Resolve the read contract before spending a run. |
| +LIVE_BLOCKERS = ( |
| + 'FetchGroup requires ssm:GetParametersByPath on shared and regional scratch paths; GetParameter(s) is insufficient.', |
| + 'install-channel requires signed channel, floor, manifest and artifact reads; bootstrap-key-only S3 cannot install.', |
| + 'A fresh random release public key cannot verify the dev signed channel/floor. A scratch signed release fixture is required.', |
| +) |
| + |
| + |
| +def require(ok, message): |
| + if not ok: |
| + raise ValueError(message) |
| + |
| + |
| +def scope(run): |
| + require(bool(re.fullmatch(r'[a-z0-9][a-z0-9-]{0,31}', run)), 'invalid run id') |
| + deployment = 'f4-' + run |
| + return dict(run=run, deployment=deployment, prefix=f'/carlos/{deployment}/ie', |
| + shared=f'/carlos/{deployment}/shared', key=f'bootstrap/{deployment}/ie/carlos-v0.34.2-linux-arm64', |
| + evidence=f'root-runner/p3b1-f4-witness/{run}', role=f'p3b1-f4-witness-{run}') |
| + |
| + |
| +def plain_render(config): |
| + template = (ROOT / 'infra/modules/region-host/group-init.sh.tftpl').read_text() |
| + loop = '%{ for key, value in config ~}\n${key}=${value}\nexport ${key}\n%{ endfor ~}\n' |
| + require(template.count(loop) == 1, 'template config loop changed') |
| + # Tofu quotes even shell-safe values. |
| + assignments = ''.join(k + "='" + v.replace("'", "'\"'\"'") + "'\nexport " + k + '\n' for k, v in sorted(config.items())) |
| + return template.replace(loop, assignments).replace('$${', '${').replace('%%{', '%{').encode() |
| + |
| + |
| +def witness_config(dev, s): |
| + result = dict(dev, CARLOS_DEPLOYMENT=s['deployment'], CARLOS_POOLS='witness') |
| + for name in ('CARLOS_BOOTSTRAP_HASH_KEY', 'CARLOS_BOOTSTRAP_OBJECT_KEY', 'CARLOS_INGRESS_KEY'): |
| + result[name] = dev[name].replace('/carlos/dev/ie/', s['prefix'] + '/') |
| + # hapair is dev-only in GroupConfig.Validate. Two module input substitutions |
| + # (deployment and pools) therefore change exactly five script assignments. |
| + return result |
| + |
| + |
| +def check_diff(dev, witness, s): |
| + config = json.loads((ROOT / 'scripts/testdata/region-group-plan/dev-boot-config.json').read_text()) |
| + require(dev == plain_render(config), 'module real-dev render differs from the real-dev fixture') |
| + expected = plain_render(witness_config(config, s)) |
| + require(witness == expected, 'witness differs beyond deployment/pool substitutions') |
| + require(b'/carlos/dev/ie' not in witness and b'bootstrap/dev/ie' not in witness, 'real dev namespace in witness') |
| + diff = ''.join(difflib.unified_diff(dev.decode().splitlines(True), witness.decode().splitlines(True), |
| + fromfile='real-dev', tofile='witness')) |
| + require(len([x for x in diff.splitlines() if x.startswith('+') and not x.startswith('+++')]) == 5, |
| + 'expected exactly five changed assignment lines') |
| + return diff |
| + |
| + |
| +def configured_values(values, expressions): |
| + # Mock providers invent values for optional+computed fields. Only attributes |
| + # actually configured by the module may become EC2 launch arguments. |
| + result = {} |
| + for key, expression in expressions.items(): |
| + require(key in values, 'missing configured value: ' + key) |
| + value = values[key] |
| + if isinstance(expression, list): |
| + require(len(value) == len(expression), 'configured block cardinality: ' + key) |
| + result[key] = [configured_values(v, e) for v, e in zip(value, expression)] |
| + else: |
| + if isinstance(expression.get('constant_value'), bool): |
| + require(value in (True, False, 'true', 'false'), 'boolean provider value') |
| + value = value in (True, 'true') |
| + result[key] = value |
| + return result |
| + |
| + |
| +def render(tofu, directory, s): |
| + require(json.loads(subprocess.check_output([str(tofu), 'version', '-json']))['terraform_version'] == '1.13.1', |
| + 'OpenTofu 1.13.1 required') |
| + module = directory / 'module' |
| + shutil.copytree(ROOT / 'infra/modules/region-host', module, dirs_exist_ok=True, |
| + ignore=shutil.ignore_patterns('.terraform', '.terraform.lock.hcl')) |
| + env = dict(os.environ, AWS_EC2_METADATA_DISABLED='true', AWS_CONFIG_FILE='/dev/null', |
| + AWS_SHARED_CREDENTIALS_FILE='/dev/null', AWS_ACCESS_KEY_ID='mock', AWS_SECRET_ACCESS_KEY='mock', |
| + TMPDIR=str(directory), TF_IN_AUTOMATION='1') |
| + env.pop('AWS_PROFILE', None) |
| + env.pop('AWS_SESSION_TOKEN', None) |
| + def run(*args): |
| + result = subprocess.run(['nice', '-n', '10', str(tofu), f'-chdir={module}', *args], |
| + env=env, capture_output=True, text=True, timeout=600) |
| + require(result.returncode == 0, result.stdout[-4000:] + result.stderr[-2000:]) |
| + return result.stdout |
| + if not (module / '.terraform').exists(): |
| + (directory / 'init.log').write_text(run('init', '-backend=false', '-input=false', '-no-color')) |
| + test = module / 'tests/group_user_data.tftest.hcl' |
| + original = test.read_text().split('run "oversize_user_data"')[0] |
| + result = [] |
| + try: |
| + for label, content in [('dev', original), ('witness', original.replace('deployment = "dev"', |
| + f'deployment = "{s["deployment"]}"').replace('pools = ["hapair"]', |
| + 'pools = ["witness"]'))]: |
| + test.write_text(content) |
| + events = run('test', '-filter=tests/group_user_data.tftest.hcl', '-json', '-verbose') |
| + (directory / f'{label}-plan.jsonl').write_text(events) |
| + plans = [e['test_plan'] for line in events.splitlines() if (e := json.loads(line)).get('test_plan') |
| + and e.get('@testrun') == 'real_dev_user_data'] |
| + require(len(plans) == 1, 'missing module plan') |
| + resources = {r['address']: r['values'] for r in plans[0]['planned_values']['root_module']['resources']} |
| + expressions = next(r['expressions'] for r in plans[0]['configuration']['root_module']['resources'] |
| + if r['address'] == 'aws_launch_template.group') |
| + lt = configured_values(resources['aws_launch_template.group[0]'], expressions) |
| + require(len(lt['user_data']) <= 13107, 'module encoded user-data cap') |
| + raw = gzip.decompress(base64.b64decode(lt['user_data'])) |
| + (directory / f'{label}.sh').write_bytes(raw) |
| + result.append((raw, lt)) |
| + finally: |
| + shutil.copyfile(ROOT / 'infra/modules/region-host/tests/group_user_data.tftest.hcl', test) |
| + diff = check_diff(result[0][0], result[1][0], s) |
| + (directory / 'substitutions.diff').write_text(diff) |
| + print(diff) |
| + print('MODULE real-dev encoded bytes:', len(result[0][1]['user_data']), '/ 13107') |
| + return result[1] |
| + |
| + |
| +def policy(s, kms_key): |
| + parameter = f'arn:aws:ssm:{REGION}:{ACCOUNT}:parameter' |
| + return {'Version': '2012-10-17', 'Statement': [ |
| + {'Effect': 'Allow', 'Action': ['ssm:GetParameter', 'ssm:GetParameters'], |
| + 'Resource': [parameter + s['prefix'] + '/*', parameter + s['shared'] + '/*']}, |
| + {'Effect': 'Allow', 'Action': 'kms:Decrypt', 'Resource': kms_key, |
| + 'Condition': {'StringEquals': {'kms:ViaService': f'ssm.{REGION}.amazonaws.com'}, |
| + 'StringLike': {'kms:EncryptionContext:PARAMETER_ARN': |
| + [parameter + s['prefix'] + '/*', parameter + s['shared'] + '/*']}}}, |
| + {'Effect': 'Allow', 'Action': ['s3:GetObject', 's3:GetObjectVersion'], 'Resource': f'arn:aws:s3:::{BUCKET}/' + s['key']}, |
| + {'Effect': 'Allow', 'Action': 's3:PutObject', 'Resource': f'arn:aws:s3:::{BUCKET}/' + s['evidence'] + '/*'}, |
| + ]} |
| + |
| + |
| +def seed(s, version): |
| + dev = json.loads((ROOT / 'scripts/testdata/region-group-plan/dev-boot-config.json').read_text()) |
| + values = dict(AWS_REGION=REGION, CARLOS_POOLS='witness', CARLOS_DEPLOYMENT_BUCKET=BUCKET, |
| + CARLOS_HIBERNATE_BUCKET=dev['CARLOS_GROUP_DATA_BUCKET'], CARLOS_HIBERNATE_REGION=REGION, |
| + CARLOS_HIBERNATE_PREFIX='instances', CARLOS_REGION_HA='true', CARLOS_GROUP_ADMISSION='1', |
| + CARLOS_CHANGE_INDEX='read', CARLOS_HOST_METRICS='cloudwatch', CARLOS_SYSTEM_CHANNEL='stable', |
| + CARLOS_ALERT_SNS_TOPIC_ARN=f'arn:aws:sns:{REGION}:{ACCOUNT}:' + s['role'], |
| + CARLOS_RELEASE_PUBKEY=base64.b64encode(secrets.token_bytes(32)).decode(), |
| + CARLOS_SECRETS_KEY=base64.b64encode(secrets.token_bytes(32)).decode(), |
| + CARLOS_HA_FIXED_BOX_IDENTITIES='{}', CARLOS_SWAP='0') |
| + require(len(values) == 16, 'env seed count') |
| + values.update({'boot/bootstrap-object': json.dumps(dict(key=s['key'], version=version, known_readers=[], |
| + deployment_aws_region=REGION, floor='required')), |
| + 'boot/bootstrap-sha256': BOOT_SHA, 'boot/ingress': '["54.77.110.223","18.203.21.74"]', |
| + 'boot/CARLOS_TERMINATION_QUEUE_URL': dev['CARLOS_TERMINATION_QUEUE_URL']}) |
| + return {s['prefix'] + '/' + k: v for k, v in values.items()} |
| + |
| + |
| +COLLECTOR = r'''#!/usr/bin/python3 |
| +import hashlib,io,json,os,pathlib,shlex,subprocess,tarfile,time,urllib.request |
| +os.umask(0o077) |
| +print('WITNESS collector-start', flush=True) |
| +root=pathlib.Path('/var/lib/carlos-witness-@RUN@');root.mkdir(mode=0o700) |
| +redactions=[] |
| +host=pathlib.Path('/etc/carlos/host.env') |
| +if host.exists(): |
| + for line in host.read_text().splitlines(): |
| + if '=' in line: |
| + k,v=line.split('=',1) |
| + if 'KEY' in k or 'SECRET' in k or 'TOKEN' in k: |
| + redactions.extend([v.strip().strip('"').strip("'")]) |
| +def redact(text): |
| + for value in redactions: |
| + if value: text=text.replace(value,'[REDACTED]') |
| + return text |
| +def command(args): |
| + try: |
| + p=subprocess.run(args,capture_output=True,text=True,timeout=20) |
| + return dict(argv=args,rc=p.returncode,out=redact(p.stdout+p.stderr)) |
| + except Exception as e:return dict(argv=args,rc=255,out=str(e)) |
| +e=dict(commands={},files={},mounts={},time=time.time()) |
| +for path in @MOUNTS@: |
| + p=pathlib.Path(path) |
| + probe=p |
| + while not probe.exists():probe=probe.parent |
| + e['mounts'][path]=dict(probe=str(probe),flags=os.statvfs(probe).f_flag, |
| + noexec=bool(os.statvfs(probe).f_flag & os.ST_NOEXEC), |
| + findmnt=command(['findmnt','-T',str(probe),'-o','TARGET,SOURCE,FSTYPE,OPTIONS'])) |
| +for name,args in { |
| + 'cloud-status':['cloud-init','status','--long'], |
| + 'nft':['nft','list','ruleset'], 'nft-persist':['cat','/etc/nftables.conf'], |
| + 'sysctl':['sysctl','net.ipv4.conf.all.arp_ignore','net.ipv4.conf.default.arp_ignore','net.ipv4.conf.all.arp_announce','net.ipv4.conf.default.arp_announce'], |
| + 'apparmor':['aa-status'], 'lsm':['cat','/sys/kernel/security/lsm'], |
| + 'mac-denials':['journalctl','-k','-b','--no-pager','--grep','apparmor="DENIED"|avc:.*denied'], |
| + 'packages':['dpkg-query','-W','python3','coreutils','passwd','libc-bin','nftables','procps','chrony','awscli','systemd','cloud-init','apparmor','needrestart','selinux-basics'], |
| + 'user':['getent','passwd','carlos'], 'group':['getent','group','carlos'], |
| + 'tools':['/bin/sh','-c','command -v python3 timeout useradd getent install nft sysctl chronyc aws systemctl; python3 --version; aws --version; systemctl --version'], |
| + 'chrony':['chronyc','-n','sources'], |
| + 'timesyncd':['systemctl','is-active','systemd-timesyncd'], |
| + 'directories':['ls','-ld','/etc/carlos','/var/lib/carlos-group-boot','/opt/carlos','/data'], |
| + 'listing':['ls','-la','/etc/carlos','/var/lib/carlos-group-boot','/opt/carlos'], |
| + 'kernel':['uname','-a'], |
| + 'link':['ip','-d','link','show'], |
| + 'nft-check':['nft','-c','-f','/etc/nftables.conf'], |
| + 'mount-units':['systemctl','is-active','data-instances.mount','run-carlos-instances.mount','run-carlos-logs.mount'], |
| + 'selinux':['ls','-ld','/sys/fs/selinux'], |
| + 'free':['free','-m'], |
| + 'cloud-unit':['systemctl','show','cloud-final','-p','FragmentPath','-p','ExecStart'], |
| +}.items(): e['commands'][name]=command(args) |
| +for unit in @UNITS@: |
| + for op,args in [('status',['systemctl','status',unit,'--no-pager']), |
| + ('journal',['journalctl','-b','-u',unit,'--no-pager','-o','short-monotonic']), |
| + ('show',['systemctl','show',unit,'-p','Restart','-p','ActiveState','-p','ExecMainStartTimestampMonotonic','-p','ExecMainStatus','-p','Result','-p','ExecStartPre','-p','RestrictAddressFamilies','-p','ReadWritePaths'])]: |
| + e['commands'][unit+'-'+op]=command(args) |
| +for path in ['/etc/carlos/group.json','/etc/carlos/group-ingress.json','/etc/carlos/region-config.json', |
| + '/etc/carlos/group-identity.json','/etc/carlos/host.env','/etc/nftables.conf','/opt/carlos/carlos', |
| + '/var/lib/carlos-group-boot','/etc/systemd/system/carlos-instance-control.service.d/60-hairpin.conf']: |
| + p=pathlib.Path(path) |
| + try: |
| + st=p.stat();info=dict(uid=st.st_uid,gid=st.st_gid,mode=oct(st.st_mode & 0o7777),mtime=st.st_mtime_ns) |
| + if p.is_file() and path.endswith('.json'):info['keys']=sorted(json.loads(p.read_text())) |
| + if path.endswith('/group.json'):info['box_iid']=json.loads(p.read_text())['instance_id'] |
| + if path.endswith('/host.env'):info['keys']=[x.split('=',1)[0] for x in p.read_text().splitlines() if '=' in x] |
| + e['files'][path]=info |
| + except FileNotFoundError:e['files'][path]=None |
| +try: |
| + opener=urllib.request.build_opener(urllib.request.ProxyHandler({})) |
| + t=opener.open(urllib.request.Request('http://169.254.169.254/latest/api/token',method='PUT',headers={'X-aws-ec2-metadata-token-ttl-seconds':'60'}),timeout=2).read().decode() |
| + e['identity']=json.loads(opener.open(urllib.request.Request('http://169.254.169.254/latest/dynamic/instance-identity/document',headers={'X-aws-ec2-metadata-token':t}),timeout=2).read()) |
| +except Exception as ex:e['identity_error']=str(ex) |
| +for name,path in [('cloud-init-output.log','/var/log/cloud-init-output.log'),('cloud-init.log','/var/log/cloud-init.log')]: |
| + try:(root/name).write_text(redact(pathlib.Path(path).read_text(errors='replace'))) |
| + except OSError as ex:(root/name).write_text(str(ex)) |
| +(root/'evidence.json').write_text(json.dumps(e,sort_keys=True,indent=2)) |
| +archive=root/'evidence.tar.gz' |
| +with tarfile.open(archive,'w:gz') as tar: |
| + for name in ['evidence.json','cloud-init-output.log','cloud-init.log']:tar.add(root/name,arcname=name) |
| +print('WITNESS collector-evidence files='+str(len(e['files']))+' commands='+str(len(e['commands'])),flush=True) |
| +upload=command(['aws','--region','eu-west-1','s3api','put-object','--bucket','carlos-dev-640012953448','--key','root-runner/p3b1-f4-witness/@RUN@/evidence.tar.gz','--body',str(archive)]) |
| +print('WITNESS upload rc='+str(upload['rc']),flush=True) |
| +print('WITNESS collector-done',flush=True) |
| +''' |
| + |
| + |
| +def collector(s): |
| + return COLLECTOR.replace('@RUN@', s['run']).replace('@MOUNTS@', repr(MOUNTS)).replace('@UNITS@', repr(UNITS)).encode() |
| + |
| + |
| +def user_data(script, collection): |
| + boundary = 'p3b1-f4-' + hashlib.sha256(script + collection).hexdigest()[:24] |
| + body = f'MIME-Version: 1.0\nContent-Type: multipart/mixed; boundary="{boundary}"\n\n'.encode() |
| + for name, payload in [('001-boot', script), ('002-collect', collection)]: |
| + body += (f'--{boundary}\nContent-Type: text/x-shellscript; charset="utf-8"\n' |
| + f'Content-Transfer-Encoding: 8bit\nContent-Disposition: attachment; filename="{name}"\n\n').encode() |
| + body += payload + b'\n' |
| + body += f'--{boundary}--\n'.encode() |
| + parsed = BytesParser(policy=email.policy.default).parsebytes(body) |
| + parts = list(parsed.iter_parts()) |
| + require(len(parts) == 2 and parts[0].get_payload(decode=True) == script, 'part 1 byte integrity') |
| + require(parts[1].get_payload(decode=True) == collection, 'collector byte integrity') |
| + encoded = base64.b64encode(gzip.compress(body, mtime=0)).decode() |
| + require(len(encoded) <= 16384, f'MIME encoded size {len(encoded)} exceeds 16384') |
| + return encoded |
| + |
| + |
| +def launch_input(lt, encoded, s): |
| + # Fail on new configured attributes rather than silently omitting them. |
| + supported = {'image_id', 'instance_type', 'metadata_options', 'block_device_mappings', 'network_interfaces', |
| + 'monitoring', 'user_data', 'iam_instance_profile', 'tags', 'name', 'default_version', |
| + 'update_default_version', 'description', 'name_prefix', 'tag_specifications'} |
| + computed = {'id', 'arn', 'latest_version', 'tags_all', 'region'} |
| + require(not {k for k, v in lt.items() if v not in (None, [], {}, '', False) and k not in supported | computed}, |
| + 'unmapped launch template attributes') |
| + require(lt['image_id'] == AMI, 'AMI drift') |
| + metadata = lt['metadata_options'][0] |
| + require(metadata.get('http_tokens') == 'required' and metadata['http_put_response_hop_limit'] == 1, 'IMDS drift') |
| + meta_names = {'http_endpoint': 'HttpEndpoint', 'http_tokens': 'HttpTokens', |
| + 'http_put_response_hop_limit': 'HttpPutResponseHopLimit', 'http_protocol_ipv6': 'HttpProtocolIpv6', |
| + 'instance_metadata_tags': 'InstanceMetadataTags'} |
| + require(not {k for k,v in metadata.items() if v not in (None,'') and k not in meta_names}, 'metadata field drift') |
| + ebs_names = {'volume_size': 'VolumeSize', 'volume_type': 'VolumeType', 'encrypted': 'Encrypted', |
| + 'delete_on_termination': 'DeleteOnTermination', 'iops': 'Iops', 'throughput': 'Throughput', |
| + 'kms_key_id': 'KmsKeyId', 'snapshot_id': 'SnapshotId'} |
| + blocks = [] |
| + for block in lt['block_device_mappings']: |
| + ebs = block['ebs'][0] |
| + require(ebs['encrypted'] is True and ebs['delete_on_termination'] is True, 'EBS safety drift') |
| + require(not {k for k,v in ebs.items() if v not in (None,'',[]) and k not in ebs_names}, 'EBS field drift') |
| + require(not block.get('no_device') and not block.get('virtual_name'), 'unsupported block mapping') |
| + blocks.append(dict(DeviceName=block['device_name'], Ebs={ebs_names[k]:v for k,v in ebs.items() if v is not None and v != ''})) |
| + require(len(lt['network_interfaces']) == 1, 'network interface count') |
| + network = lt['network_interfaces'][0] |
| + require(network['associate_public_ip_address'] is True and network['delete_on_termination'] is True, 'public IPv4 required') |
| + allowed_net = {'associate_public_ip_address','delete_on_termination','security_groups','device_index'} |
| + require(not {k for k,v in network.items() if v not in (None,[],{},'',False,0) and k not in allowed_net}, 'network field drift') |
| + tags = dict(lt.get('tags') or {}, purpose='p3b1-f4-witness', Name=s['role'], witness_run=s['run']) |
| + result = dict(ImageId=lt['image_id'], InstanceType=lt['instance_type'], MinCount=1, MaxCount=1, |
| + ClientToken=s['role'], UserData=encoded, IamInstanceProfile={'Name':s['role']}, |
| + MetadataOptions={meta_names[k]:v for k,v in metadata.items() if v is not None and v != ''}, |
| + BlockDeviceMappings=blocks, |
| + NetworkInterfaces=[dict(DeviceIndex=0, SubnetId=SUBNET, Groups=[SG], AssociatePublicIpAddress=True, |
| + DeleteOnTermination=network['delete_on_termination'])], |
| + TagSpecifications=[dict(ResourceType=kind, Tags=[dict(Key=k,Value=v) for k,v in tags.items()]) |
| + for kind in ('instance','volume')]) |
| + if lt.get('monitoring'): |
| + result['Monitoring'] = {'Enabled': lt['monitoring'][0]['enabled']} |
| + return result |
| + |
| + |
| +class AWS: |
| + def __init__(self, dry=False): self.dry = dry |
| + def __call__(self, service, operation, **params): |
| + args = ['aws','--profile','kass','--region',REGION,'--no-cli-pager',service,operation, |
| + '--cli-input-json',json.dumps(params),'--output','json'] |
| + safe = dict(params) |
| + if operation == 'put-parameter': safe['Value'] = '[REDACTED]' |
| + if operation == 'run-instances': safe['UserData'] = f'[base64 gzip MIME {len(params["UserData"])} bytes]' |
| + print('AWS',service,operation,json.dumps(safe,sort_keys=True),flush=True) |
| + if self.dry: return {} |
| + p = subprocess.run(args, capture_output=True, text=True, timeout=90) |
| + if p.returncode: raise RuntimeError(f'{service} {operation}: {p.stderr[:1500]}') |
| + return json.loads(p.stdout or '{}') |
| + |
| + |
| +def assertions(e): |
| + files=e.get('files',{}); cmds=e.get('commands',{}) |
| + out=lambda k:cmds.get(k,{}).get('out','') |
| + rc=lambda k:cmds.get(k,{}).get('rc',255) |
| + exists=lambda k:bool(files.get(k)) |
| + ordered=['/etc/carlos/group-identity.json','/etc/carlos/region-config.json','/etc/carlos/group.json', |
| + '/etc/carlos/group-ingress.json','/etc/nftables.conf','/etc/carlos/host.env'] |
| + times=[files.get(k,{}).get('mtime',0) if files.get(k) else 0 for k in ordered] |
| + return [ |
| + ('W1 exec mount', not e.get('mounts',{}).get('/var/lib/carlos-group-boot',{'noexec':True})['noexec'], 'findmnt + statvfs'), |
| + ('W2 identity verified before ingress', exists(ordered[3]) and all(times[:4]) and times[:4]==sorted(times[:4]), 'exclusive writes after identity verifier'), |
| + ('W3 immutable records', all(exists(k) for k in ordered[:4]), 'group identity/region/marker/ingress'), |
| + ('W4 hairpin installed', rc('nft')==0 and all(x in out('nft') for x in ('carlos_group_imds','carlos_hairpin')), out('nft')[:200]), |
| + ('W5 dormant nft persisted', rc('nft-persist')==0 and all(x in out('nft-persist') for x in ('carlos_group_imds','carlos_hairpin')), out('nft-persist')[:200]), |
| + ('W6 host.env installed', exists('/etc/carlos/host.env') and files['/etc/carlos/host.env']['mode']=='0o600' and files['/etc/carlos/host.env']['uid']==0, 'metadata only; values omitted'), |
| + ('W7 Restart=no', 'Restart=no\n' in out('carlos-edge-show'), out('carlos-edge-show')[:250]), |
| + ('W8 edge ran', bool(re.search(r'ExecMainStartTimestampMonotonic=[1-9][0-9]*',out('carlos-edge-show'))), out('carlos-edge-show')[:250]), |
| + ('W9 publication denied', bool(re.search(r'agent: edges file pass failed[^\n]*AccessDenied', out('carlos-edge-journal'))) and 'tenant admission is open' not in out('carlos-edge-journal'), out('carlos-edge-journal')[-500:]), |
| + ('W10 work dir removed', '/var/lib/carlos-group-boot' in files and files['/var/lib/carlos-group-boot'] is None and exists('/etc/carlos/host.env'), 'final cleanup after start'), |
| + ('W11 sysctl', all(f'net.ipv4.conf.{axis}.arp_{name} = {value}' in out('sysctl') for axis in ('all','default') for name,value in [('ignore',1),('announce',2)]), out('sysctl')), |
| + ('W12 AMI tools', rc('tools')==0 and 'Python 3.13' in out('tools') and 'aws-cli/2.' in out('tools'), out('tools')), |
| + ('W13 MAC policy', rc('mac-denials') in (0,1) and not re.search(r'apparmor="DENIED"|avc:.*denied',out('mac-denials')), out('mac-denials')), |
| + ('W14 installed binary', exists('/opt/carlos/carlos'), 'reset ExecStart path'), |
| + ('W15 clock', rc('chrony')==0 and bool(re.search(r'\^[*+]\s+169\.254\.169\.123',out('chrony'))), out('chrony')), |
| + ('W16 write order', all(times) and times==sorted(times), 'identity -> region -> marker -> ingress -> nft persist -> host.env'), |
| + ('W17 executable install paths', all(p in e.get('mounts',{}) and not e['mounts'][p]['noexec'] for p in ('/opt','/var/lib/cloud')), 'statvfs for /opt and cloud-init'), |
| + ('W18 system user', rc('user')==0 and bool(re.search(r'^carlos:[^:]*:[0-9]+:[0-9]+:[^:]*:/data:/usr/sbin/nologin',out('user'))), out('user')), |
| + ('W19 mount units', rc('mount-units')==0 and out('mount-units').splitlines()==['active']*3, out('mount-units')), |
| + ('W20 reset unit', 'Result=success' in out('carlos-hairpin-reset-show') and bool(re.search(r'ExecMainStartTimestampMonotonic=[1-9][0-9]*',out('carlos-hairpin-reset-show'))),out('carlos-hairpin-reset-show')), |
| + ('W21 persisted nft syntax', rc('nft-check')==0, out('nft-check')), |
| + ('W22 SELinux absent', rc('selinux')==2 and 'No such file' in out('selinux') and 'selinux' not in out('lsm'),out('selinux')), |
| + ('W23 systemd features', 'systemd 257' in out('tools') and '/usr/bin/systemctl' in out('carlos-edge-show') and 'AF_NETLINK' in out('carlos-instance-control-show') and '/run/carlos-hairpin' in out('carlos-instance-control-show'),out('carlos-instance-control-show')), |
| + ] |
| + |
| + |
| +def report(path, rows, note=''): |
| + esc=lambda v:str(v).replace('|','\\|').replace('\n',' ')[:700] |
| + path.write_text('# P3b-1 F4 witness evidence\n\n'+note+'\n\n| Assertion | Status | Evidence |\n|---|---|---|\n'+ |
| + ''.join(f'| {esc(n)} | {"PASS" if ok else "FAIL"} | {esc(detail)} |\n' for n,ok,detail in rows)) |
| + |
| + |
| +def baseline(aws, iid=None): |
| + observed={} |
| + for tg in TGS: |
| + rows=aws('elbv2','describe-target-health',TargetGroupArn=tg).get('TargetHealthDescriptions',[]) |
| + actual={r['Target']['Id'] for r in rows} |
| + if not aws.dry: require(actual==FIXED and iid not in actual, 'fixed target membership changed') |
| + observed[tg]=sorted(actual) |
| + # Prefix listing is controller-only. Instance policy cannot list or write it. |
| + objects=aws('s3api','list-objects-v2',Bucket=BUCKET,Prefix='control/edges/').get('Contents',[]) |
| + observed['edges']=sorted(x['Key'] for x in objects) |
| + require(not any(x.rsplit('/',1)[-1].startswith('g-') for x in observed['edges']), 'unexpected preexisting group edges') |
| + return observed |
| + |
| + |
| +def cleanup(aws, s): |
| + leaked=[] |
| + def attempt(label, service, operation, **args): |
| + try:return aws(service,operation,**args) |
| + except Exception as ex: |
| + if any(code in str(ex) for code in ('NoSuchEntity','ParameterNotFound','InvalidInstanceID.NotFound')):return {} |
| + leaked.append(label);print('LEAKED',label,str(ex),file=sys.stderr);return {} |
| + instances=attempt(s['role'], 'ec2','describe-instances',Filters=[{'Name':'tag:witness_run','Values':[s['run']]}, |
| + {'Name':'tag:purpose','Values':['p3b1-f4-witness']}]) |
| + ids=[i['InstanceId'] for r in instances.get('Reservations',[]) for i in r['Instances'] if i['State']['Name']!='terminated'] |
| + if aws.dry: ids=['<witness-instance-id>'] |
| + if ids: |
| + attempt(str(ids),'ec2','terminate-instances',InstanceIds=ids) |
| + if not aws.dry: |
| + deadline=time.monotonic()+300 |
| + while time.monotonic()<deadline: |
| + result=attempt(str(ids),'ec2','describe-instances',InstanceIds=ids) |
| + states=[i['State']['Name'] for r in result.get('Reservations',[]) for i in r['Instances']] |
| + if len(states)==len(ids) and all(x=='terminated' for x in states):break |
| + time.sleep(5) |
| + else: leaked.extend(ids);print('LEAKED',ids,'termination not verified',file=sys.stderr) |
| + attempt(s['role'],'iam','remove-role-from-instance-profile',InstanceProfileName=s['role'],RoleName=s['role']) |
| + attempt(s['role'],'iam','delete-instance-profile',InstanceProfileName=s['role']) |
| + attempt(s['role'],'iam','delete-role-policy',RoleName=s['role'],PolicyName='witness') |
| + attempt(s['role'],'iam','delete-role',RoleName=s['role']) |
| + for name in seed(s,'cleanup').keys():attempt(name,'ssm','delete-parameter',Name=name) |
| + versions=attempt(s['key'],'s3api','list-object-versions',Bucket=BUCKET,Prefix=s['key']) |
| + for item in versions.get('Versions',[])+versions.get('DeleteMarkers',[]): |
| + if item['Key']==s['key']: |
| + attempt(s['key'],'s3api','delete-object',Bucket=BUCKET,Key=s['key'],VersionId=item['VersionId']) |
| + if aws.dry:aws('s3api','delete-object',Bucket=BUCKET,Key=s['key'],VersionId='<each-scratch-version>') |
| + return leaked |
| + |
| + |
| +def run_calls(aws, s, launch, directory): |
| + # The controller must first resolve LIVE_BLOCKERS. No live call reaches here |
| + # from main while the supplied role cannot satisfy the boot contract. |
| + aws('sts','get-caller-identity') |
| + aws('ec2','describe-images',ImageIds=[AMI]) |
| + aws('ec2','describe-subnets',SubnetIds=[SUBNET]) |
| + aws('ec2','describe-security-groups',GroupIds=[SG]) |
| + before=baseline(aws) |
| + key=aws('kms','describe-key',KeyId='alias/aws/ssm').get('KeyMetadata',{}).get('Arn','<resolved-alias/aws/ssm-key-arn>') |
| + trust={'Version':'2012-10-17','Statement':[{'Effect':'Allow','Principal':{'Service':'ec2.amazonaws.com'},'Action':'sts:AssumeRole'}]} |
| + aws('iam','create-role',RoleName=s['role'],AssumeRolePolicyDocument=json.dumps(trust),Tags=[dict(Key='purpose',Value='p3b1-f4-witness')]) |
| + aws('iam','put-role-policy',RoleName=s['role'],PolicyName='witness',PolicyDocument=json.dumps(policy(s,key))) |
| + aws('iam','create-instance-profile',InstanceProfileName=s['role']) |
| + aws('iam','add-role-to-instance-profile',InstanceProfileName=s['role'],RoleName=s['role']) |
| + copied=aws('s3api','copy-object',Bucket=BUCKET,Key=s['key'],CopySource=f'{BUCKET}/{BOOT_KEY}?versionId={BOOT_VERSION}') |
| + version=copied.get('VersionId','<scratch-copy-version>') |
| + for name,value in seed(s,version).items(): |
| + p=dict(Name=name,Value=value,Type='SecureString' if name.endswith('/CARLOS_SECRETS_KEY') else 'String',Overwrite=False) |
| + if p['Type']=='SecureString':p['KeyId']='alias/aws/ssm' |
| + aws('ssm','put-parameter',**p) |
| + if not aws.dry:time.sleep(15) |
| + response=aws('ec2','run-instances',**launch) |
| + iid=response.get('Instances',[{'InstanceId':'<witness-instance-id>'}])[0]['InstanceId'] |
| + deadline=time.monotonic()+(0 if aws.dry else 900) |
| + while True: |
| + aws('ec2','get-console-output',InstanceId=iid,Latest=True) |
| + # get-object uses an output filename, unlike the ordinary JSON-only calls. |
| + command=['aws','--profile','kass','--region',REGION,'s3api','get-object','--bucket',BUCKET,'--key',s['evidence']+'/evidence.tar.gz',str(directory/'evidence.tar.gz')] |
| + print('AWS',shlex.join(command)) |
| + if aws.dry:break |
| + p=subprocess.run(command,capture_output=True,timeout=90) |
| + if p.returncode==0: |
| + with tarfile.open(directory/'evidence.tar.gz','r:gz') as tar: |
| + entry=tar.getmember('evidence.json');require(entry.isfile() and entry.size<4*1024*1024,'evidence bounds') |
| + evidence=json.load(tar.extractfile(entry)) |
| + rows=assertions(evidence) |
| + report(directory/'evidence.md',rows) |
| + require(all(x[1] for x in rows),'witness assertion failures') |
| + break |
| + require(time.monotonic()<deadline,'collector deadline') |
| + time.sleep(10) |
| + after=baseline(aws,iid) |
| + require(before==after,'target/edges changes during witness') |
| + |
| + |
| +def main(): |
| + ap=argparse.ArgumentParser() |
| + ap.add_argument('--run',default='dry-run') |
| + ap.add_argument('--dry-run',action='store_true') |
| + ap.add_argument('--execute',action='store_true') |
| + ap.add_argument('--cleanup-only',metavar='RUN') |
| + ap.add_argument('--scratch',type=Path,default=SCRATCH) |
| + ap.add_argument('--tofu',type=Path,default=SCRATCH/'tofu/tofu') |
| + args=ap.parse_args() |
| + s=scope(args.cleanup_only or args.run) |
| + os.umask(0o077) |
| + args.scratch.mkdir(parents=True,exist_ok=True) |
| + directory=args.scratch/('witness-'+s['run']);directory.mkdir(exist_ok=True) |
| + if args.cleanup_only: |
| + require(not args.execute,'cleanup-only with execute') |
| + require(args.dry_run, 'live cleanup refused: this harness has admitted no live runs; resource ownership is not established') |
| + return bool(cleanup(AWS(dry=True),s)) |
| + script,lt=render(args.tofu,directory,s) |
| + encoded=user_data(script,collector(s)) |
| + launch=launch_input(lt,encoded,s) |
| + (directory/'launch.json').write_text(json.dumps(launch,indent=2)) |
| + (directory/'collector.py').write_bytes(collector(s)) |
| + print('MIME encoded bytes:',len(encoded),'/ 16384; part 1 sha256:',hashlib.sha256(script).hexdigest()) |
| + report(directory/'evidence.md', [('render substitutions',True,'exactly deployment and pool module inputs'), |
| + ('MIME part 1 integrity',True,hashlib.sha256(script).hexdigest()),('MIME size',True,len(encoded)), |
| + *[(f'live prerequisite {n}',False,reason) for n,reason in enumerate(LIVE_BLOCKERS,1)]], |
| + 'LOCAL DRY RUN ONLY. No real-AMI assertions have run.') |
| + if args.execute: |
| + require(not args.dry_run,'conflicting modes') |
| + require(not LIVE_BLOCKERS,'live launch refused: '+' '.join(LIVE_BLOCKERS)) |
| + aws=AWS(dry=not args.execute) |
| + def interrupted(signum, frame):raise KeyboardInterrupt(f'signal {signum}') |
| + for sig in (signal.SIGINT,signal.SIGTERM):signal.signal(sig,interrupted) |
| + try:run_calls(aws,s,launch,directory) |
| + finally: |
| + for sig in (signal.SIGINT,signal.SIGTERM):signal.signal(sig,signal.SIG_IGN) |
| + leaks=cleanup(aws,s) |
| + require(not leaks,'cleanup leaks') |
| + print('DRY RUN complete; live launch blocked pending read-scope/fixture decision') |
| + return 0 |
| + |
| + |
| +if __name__=='__main__': |
| + try:sys.exit(main()) |
| + except (ValueError,RuntimeError,subprocess.SubprocessError) as error: |
| + print('FAIL',error,file=sys.stderr);sys.exit(1) |