erisim_kontrol.py
#!/usr/bin/env python3
"""Tek bir HTTPS adresinin sunduğu ilk HTTP durumunu doğrula."""
import argparse
import http.client
import math
import ssl
import sys
from urllib.parse import urlsplit
def durumlar(value):
try:
codes = {int(part) for part in value.split(',')}
except ValueError as exc:
raise argparse.ArgumentTypeError('Örnek: 200,302') from exc
if not all(200 <= code <= 599 for code in codes):
raise argparse.ArgumentTypeError('Durum kodları 200–599 arasında olmalı.')
return codes
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('url', help='Kimlik bilgisi veya sorgu dizesi içermeyen HTTPS adresi')
p.add_argument('--status', type=durumlar, default={200}, help='Kabul edilen kodlar (varsayılan: 200)')
p.add_argument('--ca-file', help='İsteğe bağlı ek güven kökü (PEM)')
p.add_argument('--timeout', type=float, default=6, help='Soket zaman aşımı, saniye')
a = p.parse_args()
if not math.isfinite(a.timeout) or not 0 < a.timeout <= 60:
p.error('--timeout 0’dan büyük, en fazla 60 olmalı.')
if any(ord(char) <= 32 or ord(char) >= 127 for char in a.url):
p.error('URL için ASCII, gerekirse Punycode/yüzde kodlaması kullanın.')
try:
u = urlsplit(a.url)
port = u.port if u.port is not None else 443
except ValueError as exc:
p.error(str(exc))
if (u.scheme != 'https' or not u.hostname or not 1 <= port <= 65535
or '@' in u.netloc or '?' in a.url or '#' in a.url):
p.error('Yalnızca düz bir HTTPS URL’si verin; kimlik bilgisi, sorgu ve fragment kullanmayın.')
conn = None
try:
ctx = ssl.create_default_context()
if a.ca_file:
ctx.load_verify_locations(cafile=a.ca_file)
conn = http.client.HTTPSConnection(u.hostname, port, timeout=a.timeout, context=ctx)
conn.request('GET', u.path or '/')
with conn.getresponse() as response:
code = response.status
print(f'TLS doğrulandı; HTTP {code}; beklenen: {sorted(a.status)}')
return 0 if code in a.status else 1
except (OSError, http.client.HTTPException, ValueError) as exc:
print(f'HTTPS başarısız: {exc}', file=sys.stderr)
return 2
finally:
if conn is not None:
conn.close()
if __name__ == '__main__':
sys.exit(main())
test_erisim_kontrol.py
import http.server
from pathlib import Path
import ssl
import subprocess
import sys
import tempfile
import threading
import unittest
class Panel(http.server.BaseHTTPRequestHandler):
def do_GET(self):
code = {'/': 200, '/giris': 302, '/engel': 403}.get(self.path, 404)
self.send_response(code)
if code == 302:
self.send_header('Location', '/')
self.end_headers()
def log_message(self, *_):
pass
class ErisimTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
tmp = tempfile.TemporaryDirectory()
cls.addClassCleanup(tmp.cleanup)
cls.cert = Path(tmp.name) / 'local.pem'
key = Path(tmp.name) / 'local.key'
subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1',
'-subj', '/CN=localhost', '-addext', 'subjectAltName=DNS:localhost',
'-keyout', str(key), '-out', str(cls.cert)], check=True, capture_output=True)
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Panel)
cls.addClassCleanup(server.server_close)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cls.cert, key)
server.socket = context.wrap_socket(server.socket, server_side=True)
cls.port = server.server_port
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cls.addClassCleanup(thread.join, 5)
cls.addClassCleanup(server.shutdown)
def run_cli(self, path='/', host='localhost', trust=True, extra=()):
args = [sys.executable, str(Path(__file__).with_name('erisim_kontrol.py')),
f'https://{host}:{self.port}{path}']
if trust:
args += ['--ca-file', str(self.cert)]
return subprocess.run(args + list(extra), capture_output=True, text=True, timeout=10)
def test_https_200(self):
result = self.run_cli()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('HTTP 200', result.stdout)
def test_access_redirect_is_not_followed(self):
result = self.run_cli('/giris', extra=('--status', '200,302'))
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('HTTP 302', result.stdout)
def test_unexpected_http_status(self):
result = self.run_cli('/engel')
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn('HTTP 403', result.stdout)
def test_untrusted_certificate(self):
result = self.run_cli(trust=False)
self.assertEqual(result.returncode, 2)
self.assertIn('CERTIFICATE_VERIFY_FAILED', result.stderr)
def test_wrong_certificate_name(self):
result = self.run_cli(host='127.0.0.1')
self.assertEqual(result.returncode, 2)
self.assertIn('CERTIFICATE_VERIFY_FAILED', result.stderr)
def test_query_rejected(self):
result = self.run_cli('/?q=fixture')
self.assertEqual(result.returncode, 2)
self.assertIn('Yalnızca düz bir HTTPS', result.stderr)
if __name__ == '__main__':
unittest.main()