40 lines
1.9 KiB
Python
40 lines
1.9 KiB
Python
"""Run: python3 test_client_ip.py. Real client IP is trusted only from configured proxy hops."""
|
|||
|
|
import http.client
|
||
|
|
import threading
|
||
|
|
|
||
|
|
from honeypot import Engine, Server
|
||
|
|
from trusted_proxy import forwarded_client
|
||
|
|
|
||
|
|
assert forwarded_client({'CF-Connecting-IP': '8.8.8.8'}) == ('8.8.8.8', 'CF-Connecting-IP')
|
||
|
|
assert forwarded_client({'CF-Connecting-IP': '10.0.0.1', 'X-Forwarded-For': '1.1.1.1'}) == ('1.1.1.1', 'X-Forwarded-For')
|
||
|
|
assert forwarded_client({'X-Forwarded-For': '10.0.0.1, 9.9.9.9, 10.0.0.2'}) == ('9.9.9.9', 'X-Forwarded-For')
|
||
|
|
assert forwarded_client({'CF-Connecting-IP': 'not-an-ip'}) == (None, None)
|
||
|
|
assert forwarded_client({}) == (None, None)
|
||
|
|
|
||
|
|
|
||
|
|
def run(trusted):
|
||
|
|
rows = []
|
||
|
|
engine = Engine(lambda event, **data: rows.append(dict(event=event, **data)), delay=0)
|
||
|
|
server = Server(('127.0.0.1', 0), engine, trusted_forwarded=trusted)
|
||
|
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||
|
|
thread.start()
|
||
|
|
try:
|
||
|
|
connection = http.client.HTTPConnection('127.0.0.1', server.server_port, timeout=3)
|
||
|
|
connection.request('GET', '/', headers={'CF-Connecting-IP': '8.8.8.8',
|
||
|
|
'X-Forwarded-For': '10.0.0.1, 1.1.1.1'})
|
||
|
|
assert connection.getresponse().status == 200
|
||
|
|
connection.close()
|
||
|
|
finally:
|
||
|
|
server.shutdown()
|
||
|
|
server.server_close()
|
||
|
|
thread.join(3)
|
||
|
|
return next(row for row in rows if row['event'] == 'request')
|
||
|
|
|
||
|
|
|
||
|
|
# Untrusted hop: the spoofable header is ignored and the socket peer is authoritative.
|
||
|
|
assert run(()).get('peer') == '127.0.0.1'
|
||
|
|
# Trusted hop (loopback stands in for the edge proxy): the real client IP wins, proxy is retained.
|
||
|
|
request = run(('127.0.0.0/8',))
|
||
|
|
assert request['peer'] == '8.8.8.8' and request['client_ip_source'] == 'CF-Connecting-IP'
|
||
|
|
assert request['proxy_peer'] == '127.0.0.1'
|
||
|
|
print('PASS: forwarded client IP trusted only from configured proxies; spoofing rejected')
|