import http.server
import socketserver
import ssl
import requests
import json

PORT = 5000  # Set port to the desired port number
HOST = 'sub1.kalkikrivadna.com'  # Specify your subdomain here

class VPNDetectionHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path.startswith('/check-vpn'):
            self.do_GET_with_prefix('check-vpn')
        else:
            html = '''
            <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Secure Network Access Terminal</title>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <style>
        body {
    margin: 0;
    padding: 0;
    min-height: 100vh;
    font-family: 'Open Sans', sans-serif;
    background: linear-gradient(45deg, #000 0%, #001100 100%);
    color: #0F0;
    display: flex;
    flex-direction: column;
    position: relative;
}

.terminal {
    background: rgba(0,0,0,0.8);
    border: 2px solid #0F0;
    width: 400px;
    height: auto;
    padding: 30px;
    box-shadow: 0 0 20px rgba(0,255,0,0.5), 
                inset 0 0 20px rgba(0,255,0,0.3);
    position: relative;
    z-index: 2;
    text-align: center; /* Center all text in terminal */
}

h1 {
    font-family: 'Orbitron', monospace; /* Keep Orbitron only for heading */
font-size: 25px ! important;
    text-align: center;
    margin-bottom: 20px;
}

#statusMessage, #ipDisplay, #uaDisplay {
    font-family: 'Roboto', sans-serif;
    text-align: center;
    margin: 10px 0;
}

.warning {
    font-family: 'Roboto', sans-serif;
    color: white;
    text-align: center;
    margin: 20px 0;
    line-height: 1.5;
    font-size: 0.95rem;
}

#vpnDetected {
    color: red;
font-family: 'Orbitron', monospace; 
    font-weight: 500;
    text-align: center;
    margin: 15px 0;
font-family: 'Orbitron', monospace;
    font-family: 'Roboto', sans-serif;
}

.demonstration {
    text-align: center;
font-size: 18px;
    padding: 0 15px;
    margin: 15px 0;
    font-family: 'Roboto', sans-serif;
    line-height: 1.4;
}

.content-wrapper {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    margin-top: 20px;
    margin-bottom: 60px;
}


.back-to-main {
    position: fixed;
font-family: 'Orbitron', monospace; 
    top: 20px;
    left: 20px;
    padding: 10px 20px;
    background: rgba(0, 255, 0, 0.1);
    border: 1px solid #0f0;
    color: #0f0;
    text-decoration: none;
    font-size: 16px;
    z-index: 10000;
    width: auto;
}

button {
    padding: 8px 16px;
    background-color: rgba(0, 255, 0, 0.2);
    color: #0F0;
    border: 2px solid #0F0;
    cursor: pointer;
    font-family: 'Orbitron', monospace;
    transition: all 0.3s ease;
    margin: 8px;
    width: 180px; /* Fixed width for buttons */
    font-size: 14px;
}

.matrix-footer {
    position: fixed;
font-family: 'Poppins', sans-serif;
   bottom: 0;
    left: 0;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.9);
    color: #4ade80;
    text-align: center;
    padding: 12px 0;
    z-index: 10000;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.5);
}

/* Mobile Portrait Mode */
@media screen and (max-width: 768px) and (orientation: portrait) {
    .content-wrapper {
        padding: 10px;
        margin-top: 50px;
    }

    .terminal {
        width: 100%;
        padding: 20px;
        margin: 0;
        border-left: none;
        border-right: none;
    }

   
    button {
        width: calc(100% - 20px);
        margin: 5px 10px;
        padding: 12px;
        font-size: 16px;
    }

    h1 {
        font-size: 1.2rem;
        margin: 10px 0;
    }

    .warning {
        font-size: 0.9rem;
        padding: 0 10px;
    }

    .matrix-footer {
        padding: 10px 0;
        font-size: 0.9rem;
    }
}

/* Keep iframe styling */
iframe {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: none;
    z-index: 1;
}

#alarmLight {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: green;
    margin: 15px auto;
    box-shadow: 0 0 15px green;
    transition: all 0.3s ease;
}

.alarm-active {
    background-color: red !important;
    box-shadow: 0 0 30px red !important;
    animation: pulse 1s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}


</style>
</head>
<body>

    <iframe src="https://kalkikrivadna.com/matrix.html"></iframe>
    <a href="https://kalkikrivadna.com/cyberkalkitoolsob.html" class="back-to-main">Back to Toolkit</a>
    
    <div class="content-wrapper">
        <div class="terminal">
            <h1>Secure Network Access Terminal</h1>
            <div id="alarmLight"></div>
            <div id="ipDisplay" style="display:none;">IP: [hidden]</div>
            <div id="uaDisplay" style="display:none;">User Agent: [hidden]</div>
            <div id="statusMessage"></div>
            <button id="submitBtn">Check Network</button>
            <button id="reloadBtn" onclick="location.reload();">Reload</button>
            <button id="stopBtn" style="display:none;">Stop Alarm</button>
            <div class="warning">
    <div class="demonstration" style="color: white;">
        DEMONSTRATION: Detects and Blocks Proxies, SOCKS4/4a & SOCKS5/5h, The Onion Router (TOR), Mysterium Network Nodes, Web Proxies, Compromised Servers, and more.
    </div>
        </div>
    </div>

    <footer class="matrix-footer">
        <div>© 2024 Cyber Kalki Matrix Tools | Prepare for Next Level of Digital Defense</div>
    </footer>


                <audio id="alarmSound" style="display:none;">
                    <source src="https://www.cs.csubak.edu/~mvargas/Get_not_megaman_to_space/assets/audio/alarm.mp3" type="audio/wav">
                </audio>
                <script>
                    const submitBtn = document.getElementById('submitBtn');
                    const stopBtn = document.getElementById('stopBtn');
                    const ipDisplay = document.getElementById('ipDisplay');
                    const uaDisplay = document.getElementById('uaDisplay');
                    const statusMessage = document.getElementById('statusMessage');
                    const alarmLight = document.getElementById('alarmLight');
                    const alarmSound = document.getElementById('alarmSound');

                    function triggerAlarm() {
                        // Activate red alarm light
                        alarmLight.classList.add('alarm-active');

                        // Play alarm sound
                        alarmSound.loop = true;
                        alarmSound.play().catch(e => {
                            console.log('Autoplay prevented, manual interaction needed');
                        });

                        // Show stop button when alarm is active
                        stopBtn.style.display = 'inline-block';

                        // Optional: Create a flashing effect on the body
                        document.body.style.backgroundColor = 'rgba(255,0,0,0.2)';
                    }

                    function stopAlarm() {
                        // Deactivate red alarm light
                        alarmLight.classList.remove('alarm-active');

                        // Stop alarm sound
                        alarmSound.pause();
                        alarmSound.currentTime = 0;

                        // Reset body background
                        document.body.style.backgroundColor = 'black';

                        // Hide stop button
                        stopBtn.style.display = 'none';
                    }

                    async function detectConnection() {
                        // Reset previous alarm state
                        stopAlarm();

                        submitBtn.disabled = true;  // Disable the button immediately
                        statusMessage.textContent = 'Checking network...';
                        statusMessage.style.color = 'yellow';

                        try {
                            // Detect IP using ipify
                            const ipResponse = await fetch('https://api.ipify.org?format=json');
                            const ipData = await ipResponse.json();
                            const userIP = ipData.ip;

                            // Check VPN using custom endpoint
                            const vpnCheckUrl = `/check-vpn?ip=${userIP}`;
                            const vpnResponse = await fetch(vpnCheckUrl);
                            const vpnData = await vpnResponse.json();

                            if (vpnData.is_vpn) {
                                // VPN detected - Trigger Full Alarm
                                triggerAlarm();

                                // VPN detected
                                statusMessage.textContent = 'VPN DETECTED - ACCESS BLOCKED';
                                statusMessage.style.color = 'red';
                                ipDisplay.style.display = 'none';  // Hide IP
                                uaDisplay.style.display = 'none';  // Hide User Agent
                            } else {
                                // Display IP and User Agent since there's no VPN
                                ipDisplay.textContent = `IP: ${userIP}`;
                                uaDisplay.textContent = `User Agent: ${navigator.userAgent}`;
                                ipDisplay.style.display = 'block';  // Show IP
                                uaDisplay.style.display = 'block';  // Show User Agent
                                statusMessage.textContent = 'Network Clear - Access Granted';
                                statusMessage.style.color = 'green';
                            }
                        } catch (error) {
                            console.error('Detection Error:', error);
                            submitBtn.disabled = false;  // Enable the button on error
                            statusMessage.textContent = 'Network Check Failed';
                            statusMessage.style.color = 'red';
                        }
                    }

                    // Event listeners
                    submitBtn.addEventListener('click', detectConnection);
                    stopBtn.addEventListener('click', stopAlarm);
                </script>
            </body>
            </html>
            '''
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(html.encode())

    def do_GET_with_prefix(self, prefix):
        """Handle special routes"""
        if self.path.startswith(f'/{prefix}'):
            # VPN Check Route
            if prefix == 'check-vpn':
                # Extract IP from query parameter
                ip = self.path.split('?ip=')[1] if '?ip=' in self.path else None

                if not ip:
                    self.send_error(400, "IP not provided")
                    return

                try:
                    # Use proxycheck.io to verify VPN
                    vpn_check_url = f'https://proxycheck.io/v2/{ip}?key=28bkv6-lm5vi6-g8063j-569463&vpn=1'
                    response = requests.get(vpn_check_url)
                    vpn_data = response.json()

                    # Determine if it's a VPN
                    is_vpn = (vpn_data.get(ip, {}).get('proxy') == 'yes')

                    self.send_response(200)
                    self.send_header('Content-type', 'application/json')
                    self.end_headers()
                    self.wfile.write(json.dumps({
                        'ip': ip,
                        'is_vpn': is_vpn
                    }).encode())
                except Exception as e:
                    self.send_error(500, f"VPN Check Failed: {str(e)}")

def run(server_class=http.server.HTTPServer, handler_class=VPNDetectionHandler, port=PORT):
    """Run the HTTPS server."""
    server_address = (HOST, port)  # Bind to the specified HOST
    httpd = server_class(server_address, handler_class)

    context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    certfile = '/etc/letsencrypt/live/sub1.kalkikrivadna.com/fullchain.pem'
    keyfile = '/etc/letsencrypt/live/sub1.kalkikrivadna.com/privkey.pem'
    context.load_cert_chain(certfile=certfile, keyfile=keyfile)
    httpd.socket = context.wrap_socket(httpd.socket, server_side=True)

    print(f'Starting HTTPS server on https://{HOST}:{port}...')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print('\nShutting down the server...')
    except Exception as e:
        print(f"Server error: {e}")
    finally:
        httpd.socket.close()

# Main execution block
if __name__ == "__main__":
    run(port=PORT)  # Pass 'port' as a positional argument






    