File size: 7,918 Bytes
db47ffe
 
fdfed2c
a0a9eb2
 
e148d3f
0dcd077
 
 
 
fdfed2c
cf45775
0dcd077
ae123fe
0db809a
 
0dcd077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dba222e
5467685
dba222e
a0a9eb2
5467685
a0a9eb2
5467685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0a9eb2
 
e148d3f
0dcd077
a0a9eb2
5467685
a0a9eb2
e148d3f
a0a9eb2
 
 
5467685
 
a0a9eb2
 
5467685
 
 
a0a9eb2
5467685
 
 
 
 
 
a0a9eb2
dba222e
0dcd077
 
 
 
 
 
dba222e
a0a9eb2
 
5467685
 
 
a0a9eb2
5467685
 
 
 
 
 
 
 
 
db47ffe
 
 
 
 
 
 
 
 
5467685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0a9eb2
5467685
 
 
 
 
 
e148d3f
5467685
 
db47ffe
5467685
e148d3f
5467685
 
 
 
 
 
 
 
 
 
 
db47ffe
 
 
 
 
 
5467685
0dcd077
5467685
0dcd077
5467685
4d10c8c
5467685
a0a9eb2
5467685
ae123fe
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
import os
import logging
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
from transformers import pipeline
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import time


logging.basicConfig(filename='phishing_urls.log', level=logging.INFO, format='%(asctime)s - %(message)s')

model = pipeline('text-classification', model="Ajay1311/phish")

SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 465  # Try 465 for SSL if 587 fails
SENDER_EMAIL = "pukumar2003@gmail.com"
SENDER_PASSWORD = "qwaw bfdb xdlt qyup"
RECIPIENT_EMAIL = "pukumar2003@gmail.com"
IS_HUGGINGFACE_SPACES = "false".lower() == "true"

def send_email_via_gmail(subject, body, use_ssl=False):
    """Function to send email via Gmail SMTP server with retries."""
    if IS_HUGGINGFACE_SPACES:
        logging.warning("Email sending disabled in Hugging Face Spaces due to SMTP restrictions.")
        return "Email sending disabled in Hugging Face Spaces due to network restrictions."

    message = MIMEMultipart()
    message["From"] = SENDER_EMAIL
    message["To"] = RECIPIENT_EMAIL
    message["Subject"] = subject
    message.attach(MIMEText(body, "plain"))

    max_retries = 3
    retry_delay = 5  # seconds
    timeout = 10  # seconds
    port = 465 if use_ssl else SMTP_PORT
    for attempt in range(max_retries):
        try:
            if use_ssl:
                with smtplib.SMTP_SSL(SMTP_SERVER, port, timeout=timeout) as server:
                    server.login(SENDER_EMAIL, SENDER_PASSWORD)
                    server.sendmail(SENDER_EMAIL, RECIPIENT_EMAIL, message.as_string())
            else:
                with smtplib.SMTP(SMTP_SERVER, port, timeout=timeout) as server:
                    server.starttls()
                    server.login(SENDER_EMAIL, SENDER_PASSWORD)
                    server.sendmail(SENDER_EMAIL, RECIPIENT_EMAIL, message.as_string())
            logging.info(f"Email sent successfully via port {port}")
            return "Phishing report email sent successfully!"
        except (smtplib.SMTPException, OSError) as e:
            logging.error(f"Failed to send email via port {port} (attempt {attempt + 1}/{max_retries}): {e}")
            if attempt < max_retries - 1:
                time.sleep(retry_delay)
                continue
            return f"Failed to send email: {e}"

def log_phishing(url_or_text):
    """Log phishing URLs or content into a log file."""
    logging.info(f"Phishing detected: {url_or_text}")

def create_speedometer_chart(confidence, is_phishing):
    """Generate speedometer chart showing confidence of phishing detection."""
    fig, ax = plt.subplots(figsize=(6, 3), subplot_kw={'projection': 'polar'})

    confidence_pct = confidence * 100
    theta = np.linspace(np.pi, 0, 100)
    ax.plot(theta, [1]*100, color='lightgray', linewidth=15, alpha=0.3)

    angle = np.pi * (1 - (confidence_pct / 100))
    ax.plot([np.pi, angle], [0, 1], color='red' if is_phishing else 'green', linewidth=4)

    ax.fill_between(theta, 0, 1, where=(theta >= angle), color='red' if is_phishing else 'green', alpha=0.25)

    ax.set_rticks([])
    ax.set_xticks([])
    ax.set_yticklabels([])
    ax.set_facecolor("white")
    ax.spines['polar'].set_visible(False)
    ax.set_ylim(0, 1.1)

    label = f"{'PHISHING' if is_phishing else 'BENIGN'}\n{confidence_pct:.1f}%"
    ax.text(0, -0.2, label, ha='center', va='center', fontsize=14, fontweight='bold', color='black')

    return fig

def analyze_phishing(text):
    """Function to analyze if text contains phishing content and perform actions accordingly."""
    if not text.strip():
        return "No input provided.", None, "Please enter valid email or URL content for analysis."
    
    result = model(text)
    label = result[0]['label']
    score = result[0]['score']
    is_phishing = label.lower() == 'phishing'
    chart = create_speedometer_chart(score, is_phishing)

    if is_phishing:
        analysis = f"""
        ⚠️ **Phishing Likely Detected**  
        The provided input has characteristics associated with phishing content.  
        **Confidence:** {score*100:.1f}%
        
        **Indicators of phishing may include:**
        - Suspicious or misspelled URLs
        - Requests for personal credentials
        - Unusual urgency or threats
        - Unexpected attachments or links
        **Recommendation:** Do not interact with the content until verified by your IT or security team.
        """

        # Try sending email with port 587, fallback to 465
        email_result = send_email_via_gmail("Phishing Detected", f"Phishing detected with confidence {score*100:.1f}%: {text}")
        if "Failed to send email" in email_result:
            email_result = send_email_via_gmail("Phishing Detected", f"Phishing detected with confidence {score*100:.1f}%: {text}", use_ssl=True)
        log_phishing(text)
        analysis += f"\n**Email Notification:** {email_result}"

    else:
        analysis = f"""
        ✅ **No Threat Detected**  
        The content appears legitimate based on the current model.  
        **Confidence:** {score*100:.1f}%
        
        **General Safety Tips:**
        - Avoid clicking unknown links
        - Be cautious with personal data
        - Always confirm requests from unknown senders
        **Recommendation:** Proceed with standard caution.
        """

    return f"{'Phishing Detected' if is_phishing else 'Content Safe'} (Confidence: {score*100:.1f}%)", chart, analysis

def open_awareness_page():
    """Return HTML to open the CyberSwaRaksha awareness page in a new tab."""
    return """
    <script>
    window.open('https://pukumars2003.github.io/CyberSwaRaksha/', '_blank');
    </script>
    <p>Opening CyberSwaRaksha awareness page...</p>
    """

theme = gr.themes.Soft(primary_hue="blue", secondary_hue="gray").set(
    button_primary_background_fill="*primary_600",
    button_primary_text_color="white",
    block_label_background_fill="*neutral_100",
    block_title_text_color="*primary_600",
)

with gr.Blocks(theme=theme, css="""
    .container { max-width: 800px; margin: 0 auto; }
    .header { text-align: center; margin-bottom: 20px; }
    .header h1 { color: #1f2937; font-size: 2.2rem; }
    .header p { color: #4b5563; font-size: 1rem; }
    .footer { text-align: center; margin-top: 40px; font-size: 0.9rem; color: #6b7280; }
    .result-box { font-size: 1.1rem; font-weight: bold; text-align: center; }
""") as demo:
    with gr.Column(elem_classes="container"):
        gr.HTML("""<div class="header"><h1>Cyber Swa Raksha</h1><p>Protect From Phishing By Yourself</p></div>""")
        
        with gr.Group():
            input_text = gr.Textbox(
                placeholder="Enter email content, message, or suspicious URL...",
                lines=4,
                label="Input Text"
            )
        
        with gr.Row():
            analyze_btn = gr.Button("Analyze", variant="primary")
            awareness_btn = gr.Button("Cyber Safety Tips", variant="secondary")
            clear_btn = gr.Button("Clear")
        
        with gr.Group():
            result_text = gr.Textbox(label="Detection Summary", elem_classes="result-box")
            result_plot = gr.Plot(label="Confidence Meter")
            analysis_md = gr.Markdown(label="Detailed Analysis")

        analyze_btn.click(
            analyze_phishing,
            inputs=input_text,
            outputs=[result_text, result_plot, analysis_md]
        )

        awareness_btn.click(
            open_awareness_page,
            inputs=None,
            outputs=gr.HTML(label="Awareness Page")
        )

        clear_btn.click(
            lambda: ("", None, ""),
            inputs=None,
            outputs=[input_text, result_plot, analysis_md]
        )

        gr.HTML("""<div class="footer">Cyber Swa Raksha</div>""")

if __name__ == "__main__":
    demo.launch()