"""Auditoría defensiva: integridad, certificado TLS, cabeceras HTTP y firma local.""" import argparse, hashlib, hmac, json, ssl, socket, tempfile, datetime from pathlib import Path from urllib.parse import urlsplit from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec from cryptography.exceptions import InvalidSignature def digest(path): with Path(path).open('rb') as f: return hashlib.file_digest(f, 'sha256').hexdigest() def describe(cert): now = datetime.datetime.now(datetime.timezone.utc) return {'subject': cert.subject.rfc4514_string(), 'issuer': cert.issuer.rfc4514_string(), 'not_before': cert.not_valid_before_utc.isoformat(), 'not_after': cert.not_valid_after_utc.isoformat(), 'valid_now': cert.not_valid_before_utc <= now <= cert.not_valid_after_utc, 'sha256': cert.fingerprint(hashes.SHA256()).hex(), 'note': 'Vigencia temporal no equivale a confianza de cadena.'} def read_cert(path): data = Path(path).read_bytes() cert = x509.load_pem_x509_certificate(data) if b'-----BEGIN CERTIFICATE-----' in data else x509.load_der_x509_certificate(data) return describe(cert) def tls(host): if not host or any(c in host for c in '/:@?# '): raise ValueError('Introduce solo un dominio de tu propiedad o autorizado.') with socket.create_connection((host,443),timeout=8) as raw: with ssl.create_default_context().wrap_socket(raw,server_hostname=host) as s: return {'tls':s.version(), 'cipher':s.cipher()[0], 'verified_by_system': True, **describe(x509.load_der_x509_certificate(s.getpeercert(binary_form=True)))} def signed_demo(): key=ec.generate_private_key(ec.SECP256R1()); msg=b'AppInitDev: manifiesto de ejemplo' sig=key.sign(msg,ec.ECDSA(hashes.SHA256())); public=key.public_key() public.verify(sig,msg,ec.ECDSA(hashes.SHA256())) try: public.verify(sig,msg+b'!',ec.ECDSA(hashes.SHA256())) except InvalidSignature: return {'original_valid':True,'tampered_rejected':True,'algorithm':'ECDSA P-256 / SHA-256'} raise AssertionError('Alteración no rechazada') def demo(): with tempfile.TemporaryDirectory() as d: p=Path(d)/'message.txt';p.write_bytes(b'abc'); actual=digest(p) assert hmac.compare_digest(actual,'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad') key=ec.generate_private_key(ec.SECP256R1()); name=x509.Name([x509.NameAttribute(x509.NameOID.COMMON_NAME,'Lab local')]);now=datetime.datetime.now(datetime.timezone.utc) cert=(x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-datetime.timedelta(minutes=1)).not_valid_after(now+datetime.timedelta(days=1)).sign(key,hashes.SHA256())) p=Path(d)/'demo.pem';p.write_bytes(cert.public_bytes(serialization.Encoding.PEM)); info=read_cert(p);assert info['valid_now'] return {'sha256_abc':actual,'certificate_demo_valid_now':info['valid_now'],**signed_demo()} def main(): p=argparse.ArgumentParser(description=__doc__);sub=p.add_subparsers(dest='action',required=True);sub.add_parser('demo'); h=sub.add_parser('hash');h.add_argument('file');h.add_argument('--expected');c=sub.add_parser('cert');c.add_argument('file');t=sub.add_parser('tls');t.add_argument('host');a=p.parse_args() if a.action=='demo': r=demo() elif a.action=='hash': actual=digest(a.file);r={'sha256':actual,'matches':None if a.expected is None else hmac.compare_digest(actual,a.expected.lower())} elif a.action=='cert':r=read_cert(a.file) else:r=tls(a.host) print(json.dumps(r,ensure_ascii=False,indent=2)) if r.get('matches') is False: raise SystemExit(2) if __name__=='__main__':main()