Monitor paste sites like Pastebin and GitHub Gists for leaked credentials, API keys, and sensitive data dumps using automated scraping and keyword matching to detect breaches early.
cybersecurity
threat-intelligence
paste-monitoring
credential-leak
pastebin
data-breach
threat-intelligence
osint
early-warning
1.0
mahipal
Apache-2.0
ID.RA-01
ID.RA-05
DE.CM-01
DE.AE-02
T1591
T1592
T1593
T1589
T1003
version
tactics
techniques
1.1
reconnaissance
resource-development
initial-access
id
name
tactic
source
T1593
Search Open Websites/Domains
reconnaissance
attack
id
name
tactic
source
T1593.002
Search Open Websites/Domains: Search Engines
reconnaissance
attack
id
name
tactic
source
T1650
Acquire Access
resource-development
attack
id
name
tactic
source
T1555.003
Credentials from Password Stores: Credentials from Web Browsers
reconnaissance
attack
id
name
tactic
source
T1110.004
Brute Force: Credential Stuffing
initial-access
attack
id
name
tactic
source
F1029
Gather Customer Information
reconnaissance
f3
Performing Paste Site Monitoring for Credentials
Overview
Paste sites (Pastebin, GitHub Gists, Ghostbin, Dpaste, Hastebin) are frequently used as staging areas for leaked credentials, database dumps, API keys, and sensitive data before wider distribution on dark web forums and Telegram channels. Monitoring these sites provides early breach detection, enabling organizations to respond before stolen data is weaponized. This skill covers building automated paste site monitors using the Pastebin Scraping API, keyword-based alerting, credential pattern matching, and integration with incident response workflows.
When to Use
When conducting security assessments that involve performing paste site monitoring for credentials
When following incident response procedures for related security events
When performing scheduled security testing or auditing activities
When validating security controls through hands-on testing
Prerequisites
Python 3.9+ with requests, beautifulsoup4, regex, pymisp libraries
Pastebin PRO account with Scraping API access ($49.95/month for programmatic access)
GitHub API token for Gist monitoring
Keyword lists specific to your organization (domains, project names, internal terms)
Elasticsearch or database for paste storage and search
Key Concepts
Paste Site Threat Landscape
Over 300,000 user credentials are posted on Pastebin annually, averaging 1,000 username/password pairs per leak. Paste sites serve three primary threat intelligence purposes: early breach detection (credentials appear on paste sites before dark web), threat actor profiling (actors use paste sites for C2 configuration, data staging, tool sharing), and malware discovery (encoded payloads, configuration files, C2 addresses).
Monitoring Approaches
Active monitoring queries paste site APIs or scraping endpoints at regular intervals. The Pastebin Scraping API provides real-time access to new public pastes. For GitHub, the search API allows monitoring Gists and repository commits for exposed secrets. Passive monitoring uses services like IntelX, Dehashed, or Have I Been Pwned that aggregate paste site data.
importrequestsimportreimportjsonimporttimefromdatetimeimportdatetimeclassPastebinMonitor:SCRAPING_URL="https://scrape.pastebin.com/api_scraping.php"RAW_URL="https://scrape.pastebin.com/api_scrape_item.php"def__init__(self,keywords,output_dir="paste_alerts"):self.keywords=[k.lower()forkinkeywords]self.output_dir=output_dirself.seen_keys=set()self.credential_patterns={"email_password":re.compile(r'[\w.+-]+@[\w-]+\.[\w.]+[\s:;|,]+[\S]{6,}',re.IGNORECASE),"aws_key":re.compile(r'AKIA[0-9A-Z]{16}'),"aws_secret":re.compile(r'[0-9a-zA-Z/+=]{40}'),"github_token":re.compile(r'ghp_[0-9a-zA-Z]{36}'),"slack_token":re.compile(r'xox[baprs]-[0-9a-zA-Z-]+'),"private_key":re.compile(r'-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----'),"jwt_token":re.compile(r'eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+'),"connection_string":re.compile(r'(?:mongodb|postgres|mysql|redis)://[^\s]+'),"api_key_generic":re.compile(r'(?:api[_-]?key|apikey|access[_-]?token)[\s]*[=:]\s*["\']?[\w-]{20,}',re.IGNORECASE),}deffetch_recent_pastes(self,limit=100):"""Fetch recent public pastes from Pastebin Scraping API."""params={"limit":limit}try:resp=requests.get(self.SCRAPING_URL,params=params,timeout=30)ifresp.status_code==200:pastes=resp.json()print(f"[+] Fetched {len(pastes)} recent pastes")returnpasteselse:print(f"[-] API error: {resp.status_code}")return[]exceptExceptionase:print(f"[-] Fetch error: {e}")return[]defget_paste_content(self,paste_key):"""Get the raw content of a paste."""params={"i":paste_key}try:resp=requests.get(self.RAW_URL,params=params,timeout=15)ifresp.status_code==200:returnresp.textreturn""exceptException:return""defanalyze_paste(self,content,paste_metadata):"""Analyze paste content for credentials and keywords."""findings={"keyword_matches":[],"credential_matches":{},"severity":"low",}content_lower=content.lower()# Check keywordsforkeywordinself.keywords:ifkeywordincontent_lower:count=content_lower.count(keyword)findings["keyword_matches"].append({"keyword":keyword,"count":count,})# Check credential patternsforpattern_name,patterninself.credential_patterns.items():matches=pattern.findall(content)ifmatches:findings["credential_matches"][pattern_name]={"count":len(matches),"samples":matches[:3],}# Calculate severitycred_count=sum(m["count"]forminfindings["credential_matches"].values())iffindings["keyword_matches"]andcred_count>0:findings["severity"]="critical"eliffindings["keyword_matches"]:findings["severity"]="high"elifcred_count>10:findings["severity"]="high"elifcred_count>0:findings["severity"]="medium"returnfindingsdefmonitor_loop(self,interval=120,iterations=None):"""Continuous monitoring loop."""count=0whileiterationsisNoneorcount<iterations:pastes=self.fetch_recent_pastes()alerts=[]forpasteinpastes:paste_key=paste.get("key","")ifpaste_keyinself.seen_keys:continueself.seen_keys.add(paste_key)content=self.get_paste_content(paste_key)ifnotcontent:continuefindings=self.analyze_paste(content,paste)iffindings["severity"]!="low":alert={"paste_key":paste_key,"title":paste.get("title","Untitled"),"user":paste.get("user","Anonymous"),"date":paste.get("date",""),"size":paste.get("size",0),"url":f"https://pastebin.com/{paste_key}","findings":findings,"detected_at":datetime.now().isoformat(),}alerts.append(alert)print(f" [ALERT-{findings['severity'].upper()}] "f"{paste_key}: {findings['keyword_matches']}")ifalerts:self._save_alerts(alerts)count+=1ifiterationsisNoneorcount<iterations:time.sleep(interval)returnalertsdef_save_alerts(self,alerts):"""Save alerts to JSON file."""filename=f"{self.output_dir}/alerts_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"importosos.makedirs(self.output_dir,exist_ok=True)withopen(filename,"w")asf:json.dump(alerts,f,indent=2)print(f"[+] Saved {len(alerts)} alerts to {filename}")monitor=PastebinMonitor(keywords=["mycompany.com","internal-project","employee-name"],)alerts=monitor.monitor_loop(interval=120,iterations=5)
Step 2: GitHub Gist and Code Search Monitoring
classGitHubSecretMonitor:def__init__(self,github_token,org_keywords):self.token=github_tokenself.keywords=org_keywordsself.headers={"Authorization":f"token {github_token}","Accept":"application/vnd.github.v3+json",}defsearch_code(self,query,per_page=30):"""Search GitHub code for leaked secrets."""url="https://api.github.com/search/code"params={"q":query,"per_page":per_page}resp=requests.get(url,headers=self.headers,params=params)ifresp.status_code==200:results=resp.json().get("items",[])print(f"[+] GitHub code search: {len(results)} results for '{query}'")returnresultsreturn[]defsearch_gists(self,keyword):"""Search public Gists for sensitive data."""url="https://api.github.com/gists/public"params={"per_page":100}resp=requests.get(url,headers=self.headers,params=params)matches=[]ifresp.status_code==200:gists=resp.json()forgistingists:description=(gist.get("description")or"").lower()files=gist.get("files",{})forfilename,file_infoinfiles.items():ifkeyword.lower()indescriptionorkeyword.lower()infilename.lower():matches.append({"gist_id":gist["id"],"description":gist.get("description",""),"filename":filename,"url":gist["html_url"],"created_at":gist["created_at"],})returnmatchesdefmonitor_org_secrets(self,org_domain):"""Monitor for organization secrets leaked on GitHub."""queries=[f'"{org_domain}" password',f'"{org_domain}" api_key',f'"{org_domain}" secret',f'"{org_domain}" token',f'"{org_domain}" credentials',]all_findings=[]forqueryinqueries:results=self.search_code(query)forresultinresults:all_findings.append({"query":query,"repo":result.get("repository",{}).get("full_name",""),"path":result.get("path",""),"url":result.get("html_url",""),"score":result.get("score",0),})time.sleep(10)# GitHub rate limitingreturnall_findingsgh_monitor=GitHubSecretMonitor("YOUR_GITHUB_TOKEN",["mycompany.com"])findings=gh_monitor.monitor_org_secrets("mycompany.com")
Step 3: Alert and Incident Response Integration
defgenerate_credential_leak_alert(alert_data):"""Generate incident alert for credential leak detection."""alert={"title":f"Credential Leak Detected - {alert_data.get('severity','unknown').upper()}","source":alert_data.get("url",""),"detected_at":alert_data.get("detected_at",""),"severity":alert_data.get("severity","medium"),"summary":f"Paste containing organization keywords and credentials found","keyword_matches":alert_data.get("findings",{}).get("keyword_matches",[]),"credential_types":list(alert_data.get("findings",{}).get("credential_matches",{}).keys()),"recommended_actions":["Verify if leaked credentials are valid","Force password reset for affected accounts","Rotate exposed API keys and tokens","Check access logs for unauthorized usage","Report paste for takedown","Update monitoring keywords if new patterns found",],}returnalert
Validation Criteria
Pastebin Scraping API queried successfully with rate limiting
Credential patterns detected (email:password, API keys, private keys)
Organization-specific keywords matched with context