
项目说明
Malicious URL & Domain Reputation Scoring Model
A URL and domain reputation system that scores links for malicious intent before a user clicks. This project mirrors what security gateways, email filters, and SOC enrichment systems do by analyzing URLs using lexical, DNS-like, and reputation features to classify links as benign, suspicious, or malicious.
How URL Reputation Works in Security Gateways
URL reputation is a critical component of modern security infrastructure. Security gateways, email filters, and web proxies use reputation systems to:
Pre-Click Protection
Email Security: Scan links in incoming emails before delivery, flagging or quarantining malicious URLsWeb Gateways: Block access to known malicious domains at the network edgeBrowser Extensions: Warn users about suspicious links before they clickSOC Enrichment: Provide context for security analysts in incidentsThe Reputation Pipeline
Integration Points
Secure Email Gateways (SEG): Microsoft Defender for Office 365, Mimecast, ProofpointSecure Web Gateways (SWG): Zscaler, Cisco Umbrella, Palo AltoSIEM/SOAR: Splunk, Sentinel, Cortex XSOAR for incident enrichmentAPI Gateways: Custom applications checking URLs before processingWhy It Matters
Speed: Prevents users from reaching malicious sitesScale: Automated protection for thousands of URLs per secondAccuracy: ML models detect patterns humans might missConsistency: Uniform protection across the organizationFeature Signals and Why They Matter
The system extracts 11 features from each URL to assess malicious intent:
1. URL Length (url_length)
What it measures: Total character count of the URL
Why it matters: Malicious URLs are often unusually long to:
Obfuscate the actual domainInclude tracking parametersBypass length-based filtersHide malicious keywords in long stringsTypical ranges:
Benign: 20-60 charactersSuspicious: 60-100 charactersMalicious: 100+ characters2. Path Length (path_length)
What it measures: Character count of the URL path (after domain)
Why it matters: Long paths often indicate:
Phishing pages mimicking legitimate structuresDirectory tra attemptsObfuscated landing pagesRedirection chains3. Number of Dots (num_dots)
What it measures: Count of dot characters in the URL
Why it matters: Excessive dots suggest:
Subdomain abuse (e.g., secure.login.fake.com)Domain hiding techniquesTyposquatting (e.g., gooogle.com)Internationalized domain name (IDN) attacks4. Number of Hyphens (num_hyphens)
What it measures: Count of hyphen characters in the URL
Why it matters: Hyphens are commonly used in:
Lookalike domains (e.g., secure-paypal-login.com)Keyword stuffing for SEO manipulationSeparating words in suspicious domainsBypassing keyword filters5. Number of Digits (num_digits)
What it measures: Count of numeric characters in the URL
Why it matters: High digit counts indicate:
Randomized domain names (DGAs - Domain Generation Algorithms)Tracking IDs and session tokensIP address usage instead of domain namesObfuscation techniques6. HTTPS Usage (uses_https)
What it measures: Binary flag (1 if HTTPS, 0 if HTTP)
Why it matters: While HTTPS doesn't guarantee safety:
Legitimate services increasingly use HTTPSMalicious sites also use HTTPS (free certificates)HTTP-only sites are increasingly suspiciousContext matters when combined with other signals7. IP Address in URL (has_ip)
What it measures: Binary flag (1 if URL contains IP address)
Why it matters: Direct IP addresses are highly suspicious because:
Legitimate services use domain namesIP addresses bypass domain reputation systemsCommon in phishing and malware distributionIndicates potential infrastructure compromise8. Subdomain Count (subdomain_count)
What it measures: Number of subdomain levels
Why it matters: Excessi suggest:
Subdomain abuse for hosting malicious contentFree subdomain services (e.g., github.io, wordpress.com)Attempting to appear legitimate with corporate-like structuresBypassing domain blacklists9. Shannon Entropy (entropy)
What it measures: Randomness of character distribution (0-8 bits)
Why it matters: High entropy indicates:
Randomized strings (DGAs, tracking IDs)Obfuscation techniquesMachine-generated URLsLow human readabilityTypical ranges:
Benign: 2.5-3.5 bitsSuspicious: 3.5-4.5 bitsMalicious: 4.5+ bits10. Suspicious Word Count (suspicious_word_count)
What it measures: Count of words from a suspicious keyword list
Keywords: login, , update, secure, account, free, bonus, gift
Why it matters: These words are commonly used in:
Phishing attacks creating urgency or trustSocial engineering manipulationFake authentication pagesToo-good-to-be-true offers11. High-Risk TLD (high_risk_tld)
What it measures: Binary flag (1 if TLD is in high-risk list)
High-risk TLDs: ru, cn, tk, ml, ga, cf
Why it matters: These TLDs are associated with:
Lower registration costs (attracting abuse)Less stringent requirementsHigher historical rates of malicious hostingGeographic regions with different threat profilesRisk Score Interpretation
The system produces a risk score from 0-100 based on the model's confidence and classification.
Score Calculation
Risk Thresholds
| Score Range | Classification | Interpretation | Recommended Action |
|-------------|----------------|----------------|-------------------|
| 0-30 | Low Risk | Likely benign | Allow with standard logging |
| 31-50 | Medium Risk | Suspicious characteristics | Allow with warning or additional |
| 51-70 | High Risk | Strong malicious indicators | Block or require user confirmation |
| 71-100 | Critical Risk | Very likely malicious | Block immediately and alert security team |
Example Scores
| URL | Label | Confidence | Risk Score | Interpretation |
|-----|-------|------------|------------|----------------|
| | benign | 0.95 | 1.5 | Very low risk - legitimate Google domain |
| | malicious | 0.92 | 92 | Critical risk - obvious phishing attempt |
| | suspicious | 0.75 | 75 | High risk - suspicious offer domain |
| | benign | 0.98 | 0.6 | Very low risk - legitimate Microsoft domain |
| | malicious | 0.88 | 88 | Critical risk - high-risk TLD with suspicious keywords |
Using Risk Scores in Practice
Email Security:
Score 0-30: DeliScore 31-50: Deliver with warning bannerScore 51-70: Quarantine for reviewScore 71-100: Block and notify security teamWeb Gateway:
Score 0-30: Allow accessScore 31-50: Allow with user warningScore 51-70: Block with o optionScore 71-100: Block completelySOC Enrichment:
All scores: Log for analysisScore 50+: Flag for analyst reviewScore 70+: Create security incidentExplainability Approach
The system provides explainable decisions using feature importance from the RandomForest model.
Feature Importance
RandomForest models naturally provide feature importance scores indicating which features contributed most to the classification decision.
Top Features Output
Each scoring result includes the top 5 contributing features:
Why Explainability Matters
For Security Analysts:
Understand why a URL was flagged model decisionsIdentify false positiImpro rulesFor Users:
Trust the system's decisionsLearn to recognize malicious patternsMake informed o decisionsFor Compliance:
Audit trail of security decisionsRegulatory requirements for explainable AIIncident in supportInterpreting Top Features
Example:
1. suspicious_word_count: Contains "secure", "login", "update" - classic phishing keywords
2. high_risk_tld: Uses .com (not high-risk in this case, but model learned pattern)
3. num_hyphens: Multiple hyphens separating suspicious words
4. entropy: High randomness indicating potential obfuscation
5. url_length: Longer than typical legitimate PayPal URLs
Limitations of Current Explainability
Global : Feature importance is global (model-wide), not local (per-URL)Correlation: Doesn't show feature interactions or correlationsDirection: Doesn't indicate whether high or low contributedFuture Impro: SHAP , LIME, or permutation importance for local explanationsBatch Usage
The system supports both batch processing for analysis and real-time scoring for integration.
Batch Scoring
Use Cases:
Analyzing historical URL datasetsPeriodic reputation auditsTraining data preparationSecurity research and threat huntingHow to Use:
Input Format (CSV):
Output Format (CSV):
Ad:
Process thousands of URLs efficientlyGenerate reports for stakeholdersBuild training datasetsOffline analysis without network dependenciesReal-Time Scoring
Use Cases:
Email gateway integrationWeb proxy filteringAPI endpoint for applicationsBrowser extension backendsHow to Use (API):
Response:
Ad:
Instant protection for usersIntegration with existing security infrastructureLow latency (<100ms per URL)Scalable with horizontal deploymentPerformance Considerations
Batch:
Throughput: ~10,000 URLs/second (depends on hardware)Latency: Not applicable (bulk processing)Resource usage: CPU-intensi processingReal-Time:
Throughput: ~100 URLs/second per instanceLatency: 50-100ms per URLResource usage: Constant baseline, spikes with trafficScaling:
Batch: Parallel processing across multiple cores/machinesReal-Time: Load balancing across multiple API instancesLimitations
No Live DNS Resolution
What it means: The system does not perform actual DNS lookups or network queries.
Implications:
Cannot detect IP-based reputationCannot check domain age or registration historyCannot SSL certificate Cannot detect fast-flux networksWorkaround: Integrate with external DNS reputation services (, Cisco Umbrella, etc.)
No Hosting Intelligence
What it means: The system does not analyze the actual hosting infrastructure.
Implications:
Cannot detect compromised legitimate domainsCannot check hosting provider reputationCannot identify shared hosting abuseCannot detect CDN-based attacksWorkaround: Integrate with threat intelligence feeds and hosting reputation APIs
No Content Analysis
What it means: The system does not fetch or analyze the actual web page content.
Implications:
Cannot detect page content (phishing forms, malware downloads)Cannot analyze Ja behaviorCannot detect drive-by downloadsCannot check for page obfuscationWorkaround: Integrate with web crawling and content analysis tools
Static Feature Set
What it means: The system uses a fixed set of 11 lexical features.
Implications:
May miss emerging attack patternsLimited to URL structure analysisCannot adapt to new e techniquesRequires retraining to add new featuresWorkaround: Regular model retraining with new data, feature engineering iterations
Training Data Dependency
What it means: Model performance depends on the quality and representati of training data.
Implications:
May ha positives on unusual but legitimate URLsMay miss no patterns not in training dataRequires labeled datasets (benign/malicious/suspicious)Performance degrades over time as attack techniques evolveWorkaround: Continuous monitoring, feedback loops, periodic retraining
No Geographic Context
What it means: The system does not consider the geographic location of the requester.
Implications:
Cannot detect anomalous access patternsCannot apply geo-based policiesCannot detect foreign IP accessing domestic resourcesWorkaround: Integrate with IP geolocation and access control systems
Extensions
WHOIS Age Analysis
Concept: Check domain registration age and expiration.
Implementation:
Why it matters:
Newly registered domains are more likely maliciousLegitimate domains typically ha historiesFast-flux attacks use short-liAge is a strong reputation signalPassive DNS Integration
Concept: Analyze historical DNS records and IP associations.
Implementation:
Why it matters:
Detect domain hijackingIdentify IP reputation through historical associationsDetect fast-flux networksTrack domain e over timeThreat Feed Integration
Concept: Incorporate external threat intelligence feeds.
Implementation:
Why it matters:
Le community intelligenceDetect known malicious URLsReduce false negativesProvide context from multiple sourcesSSL/TLS Certificate Analysis
Concept: Analyze SSL certificate metadata.
Implementation:
Why it matters:
Detect self-signed certificatesIdentify certificate issuer reputationCheck certificate periodDetect certificate spoofingBeha Analysis
Concept: Track URL behavior over time (clicks, redirects, etc.).
Implementation:
Why it matters:
Detect compromise of pre benign domainsIdentify redirection abuseTrack campaign patternsEnable proactiDeep Learning Models
Concept: Replace or augment RandomForest with neural networks.
Implementation:
Why it matters:
Capture complex non-linear patternsLearn from sequential data (character-le)Better generalization to noAutomatic feature learningEnsemble Methods
Concept: Combine multiple models for impro.
Implementation:
Why it matters:
Reduce model biasImproBetter handling of edge casesConfidence through consensusInstallation
Prerequisites
Python 3.8 or higherpip package managerSetup
1. Clone the repository
2. Create en
3. Install dependencies
Usage
Training the Model
Train the RandomForest classifier on the provided dataset:
This will:
Load URLs from data/raw/urls.csvExtract features for each URLTrain a RandomForest classifierSave the model to src/models/url_rf.joblibSave the label encoder to src/models/label_encoder.joblibPrint classification report with metricsBatch Scoring
Score a CSV file of URLs:
This will:
Score all URLs in data/raw/urls.csvSa to data/processed/scored_urls.csvGenerate a markdown report at docs/examples/url_report.mdReal-Time API
Start the FastAPI server:
The API will be a at
#### API Endpoint
POST /score - Request body:
{"url": " - Response: JSON with label, confidence, risk_score, and top_features
#### Example Request
#### Example Response
Project Structure
Model Performance
The RandomForest classifier is trained with the following hyperparameters:
n_estimators: 400 treesrandom_state: 42 for reproducibilityn_jobs: -1 (use all a cores)Expected Metrics
With a properly labeled and balanced dataset:
Accuracy: 85-95%Precision: 80-90% (minimizing false positives)Recall: 85-95% (minimizing false negatives)F1-Score: 82-92%Improving Performance
1. Increase training data: More labeled URLs impro generalization
2. Feature engineering: Add new features based on attack patterns
3. Hyperparameter tuning: Use grid search or random search
4. Ensemble methods: Combine multiple models
5. Regular retraining: Update model with new threat data
Contributing
Contributions are welcome. Please ensure:
New features are well-documentedCode follows existing styleChanges are tested with URL patternsPerformance impact is consideredLicense
This project is provided as-is for educational and organizational use.
Support
For issues, questions, or contributions, please open an issue on the GitHub repository.
Acknowledgments
This project demonstrates how machine learning can be applied to URL reputation analysis, mirroring techniques used in enterprise security gateways and email filters.
项目信息
开发语言:Python
Star 数:1
技术要点
该项目属于防护思路方向的开源资源,代码结构清晰,适合安全研究人员学习参考。项目围绕Security Engineer building AI-driven defensive tools: Zero-Trust access engines, URL reputation systems, and human firewall chatbots展开,提供了可运行的实现,对理解相关安全机制、工具原理与攻防技术具有较高的研究价值。
从技术实现角度看,此类项目的核心在于对底层原理的深入理解与工程化落地。开发者在研究过程中可以结合官方文档与社区讨论,梳理项目的初始化流程、核心模块职责与数据流转,逐步掌握其中的技术细节与设计思路。
使用与学习建议
1. 下载源码压缩包,解压到本地环境。
2. 根据项目类型准备对应的运行环境与依赖。
3. 按照 README 中的步骤完成配置与部署。
4. 在隔离的测试环境中运行验证,避免影响生产系统。
免责声明
本资源来源于开源社区,仅供安全研究、技术学习与合法授权范围内的攻防演练使用,请勿用于任何非法或侵害他人权益的用途。使用本项目产生的一切后果由使用者自行承担。