Python yordamida Veb-serverlar Zaifliklarini Tahlil Qilish

Zaiflik tahlili veb-serverning xavfsizlik nuqtai nazaridan potentsial zaif joylarini aniqlashni o‘z ichiga oladi. Python dasturlash tili xavfsizlikka oid tahlillar uchun mos keladi va xavfsizlikka oid kutubxonalar ham mavjud. Bu qo‘llanma veb-serverlarda keng tarqalgan zaifliklarni Python yordamida qanday tekshirish mumkinligini o‘rgatadi.

Asosiy Maqsadlar

  1. Zaifliklarni aniqlash: Potensial xatolar va xavfsizlik muammolarini topish.

  2. Avtomatlashtirish: Python orqali skanerlash jarayonlarini avtomatlashtirish.

  3. Hisobot tuzish: Topilgan zaifliklarni hisobot qilish.

Zarur Kutubxonalar

Zaifliklarni aniqlashda requests, BeautifulSoup, va socket kabi kutubxonalar foydali bo‘ladi. Keng tarqalgan kutubxonalarni o‘rnatib olish uchun quyidagi buyruqdan foydalanishingiz mumkin:

pip install requests beautifulsoup4

1 Zaiflik Tahlili haqida Asosiy Nazariy Ma'lumotlar

Zaiflik tahlili orqali veb-serverda turli hujum usullari yordamida xavfsizlik xatolarini aniqlash mumkin. Eng keng tarqalgan zaiflik turlari:

  1. SQL Injection (SQLi) – Ma’lumotlar bazasiga maxsus so‘rov yuborib noto‘g‘ri ma’lumotlar olish yoki tahrirlash.

  2. Cross-Site Scripting (XSS) – Veb-sahifa orqali zararli skriptlar kiritish.

  3. Server Versiyalarini Ayyorona Tekshirish – Veb-server va kutubxonalar versiyasidagi potentsial zaifliklarni aniqlash.

  4. Ochilgan Portlarni Tekshirish – Xavfsizlikdan himoya qilinmagan ochiq portlarni aniqlash.

2 Python yordamida Asosiy Zaifliklarni Tekshirish

Server Bannerlarini Tekshirish

Ko‘plab serverlar HTTP javob sarlavhasida o‘zining versiya ma’lumotlarini beradi, bu esa versiyalardagi zaifliklardan foydalanishni osonlashtiradi.

import requests

def check_server_banner(url):
    try:
        response = requests.head(url)
        server_info = response.headers.get("Server")
        
        if server_info:
            print(f"Server: {server_info}")
        else:
            print("Server banner topilmadi.")

    except requests.RequestException as e:
        print(f"So‘rovda xato yuz berdi: {e}")

# URL uchun sinov
check_server_banner("https://example.com")

SQL Injection Tekshiruvi

SQL Injection zaifligi URL orqali kiritilgan SQL so‘rovlarini noto‘g‘ri ishlashiga sabab bo‘lishi mumkin. Buni oddiy sinov bilan tekshirish uchun ' OR '1'='1 kabi foydalanuvchi kiritmalaridan foydalaniladi.

def sql_injection_test(url):
    payloads = ["' OR '1'='1", "' OR 'a'='a", "' OR 'x'='y"]
    
    for payload in payloads:
        test_url = f"{url}?id={payload}"
        response = requests.get(test_url)
        
        if "error" in response.text.lower():
            print(f"SQL Injection zaifligi topildi: {test_url}")
        else:
            print(f"SQL Injection sinovi muvaffaqiyatsiz: {test_url}")

# URL uchun sinov
sql_injection_test("https://example.com/item")

Eslatma: Bu testlar faqat o‘z serveringizda yoki ruxsat bilan bajarilishi lozim.

XSS (Cross-Site Scripting) Tekshiruvi

XSS zaifligi foydalanuvchi kiritgan zararli JavaScript kodlarni veb-sahifada ishlatish imkonini beradi.

def xss_test(url):
    payloads = ["<script>alert('XSS')</script>", "<img src='invalid' onerror='alert(1)'>"]
    
    for payload in payloads:
        test_url = f"{url}?query={payload}"
        response = requests.get(test_url)
        
        if payload in response.text:
            print(f"XSS zaifligi topildi: {test_url}")
        else:
            print(f"XSS sinovi muvaffaqiyatsiz: {test_url}")

# URL uchun sinov
xss_test("https://example.com/search")

Ochilgan Portlarni Tekshirish

Ochiq portlar orqali server xavfsizligi zaiflashishi mumkin. socket moduli yordamida ochiq portlarni tekshirish mumkin.

import socket

def check_open_ports(ip, ports):
    open_ports = []
    
    for port in ports:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        
        if sock.connect_ex((ip, port)) == 0:
            open_ports.append(port)
        
        sock.close()
    
    if open_ports:
        print(f"Ochiq portlar topildi: {open_ports}")
    else:
        print("Ochiq portlar topilmadi.")

# IP uchun sinov
check_open_ports("192.168.1.1", [80, 443, 21, 22, 8080])

TLS/SSL Sertifikatni Tekshirish

TLS/SSL sertifikatlarining amal qilish muddatini tekshirish orqali xavfsizlikni oshirish mumkin.

import ssl
import socket
from datetime import datetime

def check_ssl_expiry(hostname):
    context = ssl.create_default_context()
    conn = context.wrap_socket(
        socket.socket(socket.AF_INET),
        server_hostname=hostname,
    )
    
    conn.settimeout(5)
    conn.connect((hostname, 443))
    ssl_info = conn.getpeercert()
    
    expiry_date = datetime.strptime(ssl_info["notAfter"], "%b %d %H:%M:%S %Y %Z")
    remaining_days = (expiry_date - datetime.now()).days
    
    print(f"Sertifikat amal qilish muddati: {expiry_date}")
    print(f"Sertifikat qolgani: {remaining_days} kun")

# Domen uchun sinov
check_ssl_expiry("example.com")

3 Avtomatik Zaiflik Tahlili va Hisobot Tayyorlash

Barcha yuqoridagi tekshiruvlarni avtomatlashtiruvchi funksiyani yarataylik. Bu kod bir nechta URL’ni tekshiradi va natijani konsolda chiqaradi.

def vulnerability_scan(url):
    print(f"\n[+] {url} manzili uchun zaifliklarni tekshirish\n")
    
    # 1. Server bannerlarini tekshirish
    check_server_banner(url)
    
    # 2. SQL Injection tekshiruvi
    sql_injection_test(url)
    
    # 3. XSS tekshiruvi
    xss_test(url)

# URL’lar ro‘yxati
urls = ["https://example.com", "https://another-example.com"]

for url in urls:
    vulnerability_scan(url)

4 Xulosa va Tavsiyalar

Ushbu qo‘llanma veb-serverlar zaifliklarini Python yordamida qanday tahlil qilish mumkinligini o‘rgatadi. Python’da zaifliklarni aniqlash uchun ko‘plab kutubxonalar mavjud va ular yordamida xavfsizlik tahlilini avtomatlashtirish imkoniyatlari keng.

Tavsiya:

  • Barcha tahlillarni faqat ruxsat etilgan tizimlarda bajaring.

  • Topilgan zaifliklarni imkon qadar tezroq bartaraf etish yo‘llarini ishlab chiqing.

  • Serverlarni muntazam yangilang va xavfsizlik yangilanishlarini amalga oshiring.

Quyida Python yordamida veb-server zaifliklarini tahlil qiluvchi to‘liq dastur taqdim etilgan. Ushbu dastur quyidagi funksiyalarni bajaradi:

  1. Server bannerini tekshirish.

  2. SQL Injection zaifligini aniqlash.

  3. XSS (Cross-Site Scripting) zaifligini aniqlash.

  4. Ochiq portlarni tekshirish.

  5. SSL sertifikatining amal qilish muddatini tekshirish.

Dasturda har bir zaiflikni aniqlash bo‘yicha alohida funksiya va ularni birlashtiruvchi asosiy funksiyani yaratdik.

import requests
import socket
import ssl
from datetime import datetime

# 1. Server bannerini tekshirish
def check_server_banner(url):
    try:
        response = requests.head(url)
        server_info = response.headers.get("Server")
        
        if server_info:
            print(f"[Server banneri]: {server_info}")
        else:
            print("[Server banneri]: Ma'lumot topilmadi.")

    except requests.RequestException as e:
        print(f"[Xato] Server bannerini tekshirishda xatolik: {e}")

# 2. SQL Injection zaifligini tekshirish
def sql_injection_test(url):
    payloads = ["' OR '1'='1", "' OR 'a'='a", "' OR 'x'='y"]
    vulnerable = False
    
    for payload in payloads:
        test_url = f"{url}?id={payload}"
        try:
            response = requests.get(test_url)
            if "error" in response.text.lower():
                print(f"[SQL Injection zaifligi]: {test_url}")
                vulnerable = True
                break
        except requests.RequestException as e:
            print(f"[Xato] SQL Injection sinovida xatolik: {e}")
    
    if not vulnerable:
        print("[SQL Injection]: Zaiflik topilmadi.")

# 3. XSS (Cross-Site Scripting) zaifligini tekshirish
def xss_test(url):
    payloads = ["<script>alert('XSS')</script>", "<img src='invalid' onerror='alert(1)'>"]
    vulnerable = False
    
    for payload in payloads:
        test_url = f"{url}?query={payload}"
        try:
            response = requests.get(test_url)
            if payload in response.text:
                print(f"[XSS zaifligi]: {test_url}")
                vulnerable = True
                break
        except requests.RequestException as e:
            print(f"[Xato] XSS sinovida xatolik: {e}")
    
    if not vulnerable:
        print("[XSS]: Zaiflik topilmadi.")

# 4. Ochiq portlarni tekshirish
def check_open_ports(ip, ports):
    open_ports = []
    
    for port in ports:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        
        if sock.connect_ex((ip, port)) == 0:
            open_ports.append(port)
        
        sock.close()
    
    if open_ports:
        print(f"[Ochiq portlar]: {open_ports}")
    else:
        print("[Ochiq portlar]: Zaiflik topilmadi.")

# 5. SSL sertifikatning amal qilish muddatini tekshirish
def check_ssl_expiry(hostname):
    context = ssl.create_default_context()
    conn = context.wrap_socket(
        socket.socket(socket.AF_INET),
        server_hostname=hostname,
    )
    
    conn.settimeout(5)
    try:
        conn.connect((hostname, 443))
        ssl_info = conn.getpeercert()
        expiry_date = datetime.strptime(ssl_info["notAfter"], "%b %d %H:%M:%S %Y %Z")
        remaining_days = (expiry_date - datetime.now()).days
        
        print(f"[SSL Sertifikat muddati]: Amal qilish muddati - {expiry_date}")
        print(f"[SSL Sertifikat muddati]: Qolgan kunlar - {remaining_days} kun")
    except Exception as e:
        print(f"[Xato] SSL sertifikatini tekshirishda xatolik: {e}")
    finally:
        conn.close()

# Asosiy tahlil funksiyasi
def vulnerability_scan(url, ip):
    print(f"\n[+] {url} manzili uchun zaifliklarni tekshirish\n")
    
    # 1. Server bannerlarini tekshirish
    check_server_banner(url)
    
    # 2. SQL Injection tekshiruvi
    sql_injection_test(url)
    
    # 3. XSS tekshiruvi
    xss_test(url)
    
    # 4. Ochiq portlarni tekshirish
    check_open_ports(ip, [80, 443, 21, 22, 8080])
    
    # 5. SSL sertifikatni tekshirish
    check_ssl_expiry(url.replace("https://", "").replace("http://", ""))

# URL va IP adreslarni tahlil qilish uchun misol
url = "https://example.com"
ip = "93.184.216.34"  # `example.com` IP adresi

vulnerability_scan(url, ip)

Dastur qanday ishlaydi:

  1. Server bannerini tekshirish: check_server_banner funksiyasi server javobidagi Server header ma’lumotlarini ko‘rib chiqadi va server haqida ma’lumotni chiqaradi.

  2. SQL Injection zaifligi: sql_injection_test funksiyasi URL’ga SQL Injection payloadlarini yuborib, zaiflik mavjudligini tekshiradi.

  3. XSS zaifligi: xss_test funksiyasi URL’ga XSS payloadlarini yuboradi va javobda payloadning mavjudligini tekshiradi.

  4. Ochiq portlarni tekshirish: check_open_ports funksiyasi berilgan IP adresdagi portlarni tekshiradi va ochiq portlarni aniqlaydi.

  5. SSL sertifikat amal qilish muddatini tekshirish: check_ssl_expiry funksiyasi SSL sertifikat amal qilish muddatini ko‘rib chiqadi va qolgan kunlarni aniqlaydi.

Eslatma: Dastur faqat ruxsat etilgan serverlarda ishlatilishi kerak, shuningdek, IP adres va URL lar aniq bo‘lishi lozim.

Last updated