-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathct_monitor.py
More file actions
128 lines (107 loc) · 4.11 KB
/
Copy pathct_monitor.py
File metadata and controls
128 lines (107 loc) · 4.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# SPDX-FileCopyrightText: © 2024 Phala Network <dstack@phala.network>
#
# SPDX-License-Identifier: Apache-2.0
"""Monitor certificate transparency logs for a given domain."""
import argparse
import sys
import time
import requests
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
BASE_URL = "https://crt.sh"
class PoisonedLog(Exception):
"""Indicate a poisoned certificate transparency log entry."""
pass
class Monitor:
"""Monitor certificate transparency logs for a domain."""
def __init__(self, domain: str):
"""Initialize the monitor with a validated domain."""
if not self.validate_domain(domain):
raise ValueError("Invalid domain name")
self.domain = domain
self.last_checked = None
def get_logs(self, count: int = 100):
"""Fetch recent certificate transparency log entries."""
url = f"{BASE_URL}/?q={self.domain}&output=json&limit={count}"
response = requests.get(url)
return response.json()
def check_one_log(self, log: object):
"""Fetch and inspect a single certificate log entry."""
log_id = log["id"]
cert_url = f"{BASE_URL}/?d={log_id}"
cert_data = requests.get(cert_url).text
# Extract PEM-encoded certificate
import re
pem_match = re.search(
r"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----",
cert_data,
re.DOTALL,
)
if pem_match:
pem_cert = pem_match.group(0)
# Parse PEM certificate
cert = x509.load_pem_x509_certificate(pem_cert.encode(), default_backend())
# Extract the public key
public_key = cert.public_key()
pem_public_key = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
print("Public Key:")
print(pem_public_key.hex())
# Extract and print the issuer
print("Issuer:")
for attr in cert.issuer:
oid = attr.oid
if oid._name is not None:
name = oid._name
print(f" {name}: {attr.value}")
else:
print(f" {oid.dotted_string}: {attr.value}")
else:
print("No valid certificate found in the response.")
def check_new_logs(self):
"""Check for new log entries since the last check."""
logs = self.get_logs(count=10000)
print("num logs", len(logs))
for log in logs:
print(f"log id={log['id']}")
if log["id"] <= (self.last_checked or 0):
break
self.check_one_log(log)
print("next")
if len(logs) > 0:
self.last_checked = logs[0]["id"]
def run(self):
"""Run the monitor loop indefinitely."""
print(f"Monitoring {self.domain}...")
while True:
try:
self.check_new_logs()
except PoisonedLog as err:
print(err, file=sys.stderr)
return
except Exception as err:
print(err, file=sys.stderr)
time.sleep(60) # Sleep for 1 minute (60 seconds)
@staticmethod
def validate_domain(domain: str):
"""Validate that the given string is a well-formed DNS domain name."""
import re
# Regular expression for validating domain names
domain_regex = re.compile(
r"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$"
)
if not domain_regex.match(domain):
raise ValueError("Invalid domain name")
return True
def main():
"""Parse arguments and start the certificate transparency monitor."""
parser = argparse.ArgumentParser(
description="Monitor certificate transparency logs"
)
parser.add_argument("-d", "--domain", help="The domain to monitor")
args = parser.parse_args()
monitor = Monitor(args.domain)
monitor.run()