-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip_reputation_checker.py
More file actions
252 lines (214 loc) · 8.65 KB
/
ip_reputation_checker.py
File metadata and controls
252 lines (214 loc) · 8.65 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#!/usr/bin/env python3
"""
IP Address Reputation Checker
This script checks the reputation of an IP address using multiple sources.
Default IP: 8.8.8.8 (Google's public DNS)
Usage:
python ip_reputation_checker.py [IP_ADDRESS]
Example:
python ip_reputation_checker.py 8.8.8.8
python ip_reputation_checker.py 192.168.1.1
"""
import requests
import json
import sys
import argparse
from datetime import datetime
import ipaddress
import re
class IPReputationChecker:
def __init__(self):
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'IP-Reputation-Checker/1.0'
})
def validate_ip(self, ip_str):
"""Validate if the string is a valid IP address"""
try:
ipaddress.ip_address(ip_str)
return True
except ValueError:
return False
def get_ipinfo_data(self, ip):
"""Get IP information from ipinfo.io"""
try:
url = f"https://ipinfo.io/{ip}/json"
response = self.session.get(url, timeout=10)
response.raise_for_status()
return response.json()
except Exception as e:
return {"error": str(e)}
def check_abuseipdb(self, ip):
"""Check IP against AbuseIPDB (free tier, no API key required for basic check)"""
try:
# Note: This is a basic check. For production use, you'd want an API key
url = "https://api.abuseipdb.com/api/v2/check"
headers = {
'Accept': 'application/json',
'Key': 'YOUR_API_KEY_HERE' # Users should get their own API key
}
# For demo purposes, we'll simulate the response structure
# In real usage, users need to sign up for a free API key at abuseipdb.com
return {
"status": "demo",
"message": "API key required for full check",
"suggestion": "Sign up at https://www.abuseipdb.com/ for free API key"
}
except Exception as e:
return {"error": str(e)}
def check_virustotal(self, ip):
"""Check IP against VirusTotal (requires API key for full access)"""
try:
# VirusTotal requires API key for IP reputation checks
# This is a placeholder for the structure
return {
"status": "api_key_required",
"message": "VirusTotal API key required",
"suggestion": "Sign up at https://www.virustotal.com/ for free API key"
}
except Exception as e:
return {"error": str(e)}
def check_ipqualityscore(self, ip):
"""Check IP using IPQualityScore (free tier available)"""
try:
# IPQualityScore offers free tier with limited requests
# This is a placeholder for the structure
return {
"status": "api_key_required",
"message": "IPQualityScore API key required",
"suggestion": "Sign up at https://www.ipqualityscore.com/ for free API key"
}
except Exception as e:
return {"error": str(e)}
def analyze_ip_behavior(self, ip):
"""Analyze IP behavior based on known patterns"""
analysis = {
"ip": ip,
"analysis_time": datetime.now().isoformat(),
"risk_factors": []
}
# Check if it's a private IP
try:
ip_obj = ipaddress.ip_address(ip)
if ip_obj.is_private:
analysis["risk_factors"].append("Private IP address")
analysis["risk_level"] = "Low"
elif ip_obj.is_multicast:
analysis["risk_factors"].append("Multicast IP address")
analysis["risk_level"] = "Medium"
elif ip_obj.is_loopback:
analysis["risk_factors"].append("Loopback IP address")
analysis["risk_level"] = "Low"
else:
analysis["risk_level"] = "Unknown"
except:
analysis["risk_level"] = "Invalid"
return analysis
def check_ip_reputation(self, ip):
"""Main function to check IP reputation from multiple sources"""
if not self.validate_ip(ip):
return {"error": f"Invalid IP address: {ip}"}
print(f"🔍 Checking reputation for IP: {ip}")
print("=" * 50)
results = {
"ip": ip,
"timestamp": datetime.now().isoformat(),
"sources": {}
}
# Get basic IP information
print("📍 Getting IP location and basic info...")
ipinfo_data = self.get_ipinfo_data(ip)
results["sources"]["ipinfo"] = ipinfo_data
# Check against reputation services
print("🛡️ Checking against reputation databases...")
results["sources"]["abuseipdb"] = self.check_abuseipdb(ip)
results["sources"]["virustotal"] = self.check_virustotal(ip)
results["sources"]["ipqualityscore"] = self.check_ipqualityscore(ip)
# Analyze IP behavior
print("🔬 Analyzing IP behavior patterns...")
results["behavioral_analysis"] = self.analyze_ip_behavior(ip)
return results
def print_results(self, results):
"""Pretty print the reputation check results"""
if "error" in results:
print(f"❌ Error: {results['error']}")
return
print(f"\n📊 REPUTATION REPORT FOR {results['ip']}")
print(f"⏰ Checked at: {results['timestamp']}")
print("=" * 60)
# IP Info section
print("\n🌍 IP LOCATION & BASIC INFO:")
ipinfo = results["sources"].get("ipinfo", {})
if "error" in ipinfo:
print(f" ❌ Error getting IP info: {ipinfo['error']}")
else:
for key, value in ipinfo.items():
if key != "readme":
print(f" • {key.title()}: {value}")
# Reputation checks
print("\n🛡️ REPUTATION CHECKS:")
reputation_sources = ["abuseipdb", "virustotal", "ipqualityscore"]
for source in reputation_sources:
source_data = results["sources"].get(source, {})
print(f"\n {source.upper()}:")
if "error" in source_data:
print(f" ❌ Error: {source_data['error']}")
else:
for key, value in source_data.items():
print(f" • {key.title()}: {value}")
# Behavioral analysis
print("\n🔬 BEHAVIORAL ANALYSIS:")
behavior = results["behavioral_analysis"]
print(f" • Risk Level: {behavior.get('risk_level', 'Unknown')}")
if behavior.get("risk_factors"):
print(" • Risk Factors:")
for factor in behavior["risk_factors"]:
print(f" - {factor}")
else:
print(" • No specific risk factors identified")
# Summary
print("\n📋 SUMMARY:")
risk_level = behavior.get("risk_level", "Unknown")
if risk_level == "Low":
print(" ✅ This IP appears to be low risk")
elif risk_level == "Medium":
print(" ⚠️ This IP has some risk factors")
elif risk_level == "High":
print(" 🚨 This IP appears to be high risk")
else:
print(" ❓ Risk level could not be determined")
print("\n💡 NOTE: For comprehensive reputation checking, consider:")
print(" • Getting free API keys from reputation services")
print(" • Implementing rate limiting for API calls")
print(" • Caching results to avoid repeated API calls")
def main():
parser = argparse.ArgumentParser(
description="Check IP address reputation using multiple sources",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python ip_reputation_checker.py 8.8.8.8
python ip_reputation_checker.py 192.168.1.1
python ip_reputation_checker.py --help
"""
)
parser.add_argument(
"ip",
nargs="?",
default="8.8.8.8",
help="IP address to check (default: 8.8.8.8)"
)
parser.add_argument(
"--json",
action="store_true",
help="Output results in JSON format"
)
args = parser.parse_args()
checker = IPReputationChecker()
results = checker.check_ip_reputation(args.ip)
if args.json:
print(json.dumps(results, indent=2))
else:
checker.print_results(results)
if __name__ == "__main__":
main()