Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions .github/workflows/generator-generic-ossf-slsa3-publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.

# This workflow lets you generate SLSA provenance file for your project.
# The generation satisfies level 3 for the provenance requirements - see https://slsa.dev/spec/v0.1/requirements
# The project is an initiative of the OpenSSF (openssf.org) and is developed at
# https://github.com/slsa-framework/slsa-github-generator.
# The provenance file can be verified using https://github.com/slsa-framework/slsa-verifier.
# For more information about SLSA and how it improves the supply-chain, visit slsa.dev.

name: SLSA generic generator
on:
workflow_dispatch:
release:
types: [created]

jobs:
build:
runs-on: ubuntu-latest
outputs:
digests: ${{ steps.hash.outputs.digests }}

steps:
- uses: actions/checkout@v4

# ========================================================
#
# Step 1: Build your artifacts.
#
# ========================================================
- name: Build artifacts
run: |
# These are some amazing artifacts.
echo "artifact1" > artifact1
echo "artifact2" > artifact2

# ========================================================
#
# Step 2: Add a step to generate the provenance subjects
# as shown below. Update the sha256 sum arguments
# to include all binaries that you generate
# provenance for.
#
# ========================================================
- name: Generate subject for provenance
id: hash
run: |
set -euo pipefail

# List the artifacts the provenance will refer to.
files=$(ls artifact*)
# Generate the subjects (base64 encoded).
echo "hashes=$(sha256sum $files | base64 -w0)" >> "${GITHUB_OUTPUT}"

provenance:
needs: [build]
permissions:
actions: read # To read the workflow path.
id-token: write # To sign the provenance.
contents: write # To add assets to a release.
uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.4.0
with:
base64-subjects: "${{ needs.build.outputs.digests }}"
upload-assets: true # Optional: Upload to a new release
Binary file not shown.
Binary file not shown.
64 changes: 64 additions & 0 deletions collections/scam-detection-ai/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from flask import Flask, render_template, request
from email_analyzer import analyze_email
from email_fetcher import fetch_emails
from message_analyzer import analyze_message

app = Flask(__name__)

@app.route('/')
def index():
return render_template('index.html')

@app.route('/analyze', methods=['POST'])
def analyze():
if 'email_text' in request.form:
email_text = request.form['email_text']
analysis = analyze_email(email_text)
total_score = sum(analysis.values())
is_scam = total_score >= 3
return render_template('result.html', analysis=analysis, is_scam=is_scam, analysis_type='Email')

elif 'message_text' in request.form:
message_text = request.form['message_text']
analysis = analyze_message(message_text)
total_score = sum(analysis.values())
is_scam = total_score >= 2
return render_template('result.html', analysis=analysis, is_scam=is_scam, analysis_type='Message')

elif 'fetch_emails' in request.form:
username = request.form['username']
password = request.form['password']
emails = fetch_emails(username, password)

analyzed_emails = []
if emails:
for email_message in emails:
body = ""
if email_message.is_multipart():
for part in email_message.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True).decode()
break
else:
body = email_message.get_payload(decode=True).decode()

analysis = analyze_email(body)
total_score = sum(analysis.values())
is_scam = total_score >= 3

subject, _ = email.header.decode_header(email_message["Subject"])[0]
if isinstance(subject, bytes):
subject = subject.decode()

analyzed_emails.append({
"subject": subject,
"from": email_message['From'],
"analysis": analysis,
"is_scam": is_scam
})
return render_template('results_list.html', emails=analyzed_emails)

return "Invalid request", 400

if __name__ == '__main__':
app.run(debug=True)
27 changes: 27 additions & 0 deletions collections/scam-detection-ai/chrome-extension/background.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "analyzeText",
title: "Analyze for Scams",
contexts: ["selection"]
});
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "analyzeText") {
fetch('http://localhost:5000/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `message_text=${encodeURIComponent(info.selectionText)}`
})
.then(response => response.text())
.then(data => {
chrome.storage.local.set({ analysisResult: data });
})
.catch(error => {
console.error('Error:', error);
chrome.storage.local.set({ analysisResult: 'Error analyzing text.' });
});
}
});
16 changes: 16 additions & 0 deletions collections/scam-detection-ai/chrome-extension/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"manifest_version": 3,
"name": "Scam Detection AI",
"version": "1.0",
"description": "Analyzes selected text for scams.",
"permissions": [
"activeTab",
"contextMenus"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html"
}
}
17 changes: 17 additions & 0 deletions collections/scam-detection-ai/chrome-extension/popup.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>Scam Detection AI</title>
<style>
body { width: 300px; font-family: sans-serif; }
textarea { width: 100%; height: 100px; }
</style>
</head>
<body>
<h1>Scam Detection AI</h1>
<textarea id="textToAnalyze" placeholder="Text to analyze..."></textarea>
<button id="analyzeButton">Analyze</button>
<div id="result"></div>
<script src="popup.js"></script>
</body>
</html>
27 changes: 27 additions & 0 deletions collections/scam-detection-ai/chrome-extension/popup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
document.addEventListener('DOMContentLoaded', () => {
chrome.storage.local.get(['analysisResult'], (result) => {
if (result.analysisResult) {
document.getElementById('result').innerHTML = result.analysisResult;
chrome.storage.local.remove(['analysisResult']);
}
});
});

document.getElementById('analyzeButton').addEventListener('click', () => {
const text = document.getElementById('textToAnalyze').value;
fetch('http://localhost:5000/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `message_text=${encodeURIComponent(text)}`
})
.then(response => response.text())
.then(data => {
document.getElementById('result').innerHTML = data;
})
.catch(error => {
console.error('Error:', error);
document.getElementById('result').innerText = 'Error analyzing text.';
});
});
107 changes: 107 additions & 0 deletions collections/scam-detection-ai/email_analyzer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import re

import requests

def get_domain_reputation(domain):
"""
Checks the reputation of a domain using a mock API.
In a real application, this would integrate with a service like VirusTotal.
"""
# This is a mock response.
if "fake" in domain or "suspicious" in domain:
return "Malicious"
return "Clean"

def analyze_email(email_text):
"""
Analyzes an email for potential scam indicators.

Args:
email_text: The full text of the email.

Returns:
A dictionary containing the analysis results.
"""
scam_indicators = {
"urgency": 0,
"generic_greeting": 0,
"suspicious_links": 0,
"unusual_sender": 0,
"payment_requests": 0,
"attachments": 0,
"domain_analysis": {}
}

# Urgency keywords
urgency_keywords = ["urgent", "immediate", "action required", "limited time", "expire"]
for keyword in urgency_keywords:
if re.search(r'\b' + keyword + r'\b', email_text, re.IGNORECASE):
scam_indicators["urgency"] = 1
break

# Generic greeting
generic_greetings = ["dear customer", "dear user", "sir/madam"]
for greeting in generic_greetings:
if greeting in email_text.lower():
scam_indicators["generic_greeting"] = 1
break

# Suspicious links (basic check for non-standard URLs)
if re.search(r'http[s]?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/[a-zA-Z0-9_.-]+', email_text):
scam_indicators["suspicious_links"] = 1

# Unusual sender (very basic check)
if "From:" in email_text:
from_line = email_text.split("From:")[1].split("\n")[0]
if re.search(r'<.*@.*>', from_line) and not re.search(r'<.*@.*\..*>', from_line):
scam_indicators["unusual_sender"] = 1

# Payment requests
payment_keywords = ["payment", "invoice", "wire transfer", "bank account", "credit card"]
for keyword in payment_keywords:
if re.search(r'\b' + keyword + r'\b', email_text, re.IGNORECASE):
scam_indicators["payment_requests"] = 1
break

# Attachments
if "Content-Disposition: attachment" in email_text:
scam_indicators["attachments"] = 1

# Domain analysis
urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', email_text)
domains = [re.search(r'//(.*?)/', url).group(1) for url in urls if re.search(r'//(.*?)/', url)]

for domain in domains:
reputation = get_domain_reputation(domain)
scam_indicators["domain_analysis"][domain] = reputation

return scam_indicators

if __name__ == '__main__':
sample_email = """
From: Suspicious Sender <suspicious@example.com>
Subject: Urgent Action Required: Your Account Will Be Deactivated

Dear user,

We have detected suspicious activity on your account. For your security, we have temporarily suspended your account.
To reactivate your account, you must verify your identity by clicking the link below and updating your payment information.

http://suspicious-link.com/verify

Failure to do so within 24 hours will result in permanent account deactivation.

Thank you for your cooperation.

Sincerely,
The Security Team
"""

analysis = analyze_email(sample_email)
print(analysis)

total_score = sum(analysis.values())
if total_score >= 3:
print("\nThis email is likely a scam!")
else:
print("\nThis email seems legitimate.")
Loading
Loading