Modül 1: Temel Programlama ve Siber Güvenlik Temelleri

Konular

İlerleme0%

Hafta 1: Python Kurulumu ve Temel Syntax

Hafta 1: Python Kurulumu ve Temel Syntax

🎯 Öğrenme Hedefleri

Bu haftanın sonunda:

  • Python 3.x kurulumunu yapabileceksiniz
  • Temel veri tiplerini anlayacaksınız
  • Değişken tanımlama ve kullanımını öğreneceksiniz
  • Kontrol yapılarını (if/for/while) uygulayabileceksiniz

1. Python Kurulumu ve Ortam Hazırlığı

1.1 Python İndirme ve Kurulum

Windows için:

# Python.org'dan indirin
# https://www.python.org/downloads/

# Kurulum sırasında "Add Python to PATH" seçeneğini işaretleyin!

Linux (Ubuntu) için:

# Python genellikle yüklüdür, kontrol edin:
python3 --version

# Yoksa kurun:
sudo apt update
sudo apt install python3 python3-pip python3-venv

macOS için:

# Homebrew ile kurulum:
brew install python3

1.2 IDE Kurulumu - VS Code

📦 Kurulum Adımları:
├── 1. VS Code'u indir: https://code.visualstudio.com/
├── 2. Python eklentisini yükle: ms-python.python
├── 3. Pylance eklentisini yükle: ms-python.vscode-pylance
└── 4. Python Debugger: ms-python.debugpy

1.3 Sanal Ortam (Virtual Environment)

# Neden virtual environment kullanmalıyız?
# - Proje bağımlılıklarını izole eder
# - Farklı projelerde farklı kütüphane versiyonları
# - Sistem Python'unu korur

# Oluşturma:
python3 -m venv otomotiv_cyber_env

# Aktivasyon (Linux/macOS):
source otomotiv_cyber_env/bin/activate

# Aktivasyon (Windows):
otomotiv_cyber_env\Scripts\activate

# Deaktivasyon:
deactivate

2. Değişkenler ve Veri Tipleri

2.1 Temel Veri Tipleri

Python Veri Tipleri

#!/usr/bin/env python3
"""
Otomotiv Siber Güvenlik Eğitimi
Hafta 1: Değişkenler ve Veri Tipleri
"""

# ============ TAM SAYILAR (int) ============
ecu_id = 0x7E0              # Onaltılık (hexadecimal) - Motor ECU
can_baudrate = 500000       # 500 kbps
max_dtc_count = 255         # DTC sayısı
arbiration_id = 0b11111100000  # Binary format (11-bit)

print(f"ECU ID: {hex(ecu_id)}")
print(f"CAN Baudrate: {can_baudrate:,} bps")
print(f"Arbitration ID (bin): {bin(arbiration_id)}")

# ============ ONDALIKLI SAYILAR (float) ============
battery_voltage = 12.6      # Volt
fuel_level = 75.5           # Yüzde
engine_temp = 92.3          # Celsius
can_message_period = 0.01   # 10ms periyot

print(f"
Batarya: {battery_voltage}V")
print(f"Yakıt: {fuel_level:.1f}%")
print(f"Motor Sıcaklığı: {engine_temp:.2f}°C")

# ============ METİN (str) ============
vin_number = "WBA3A5G59DNP26082"
manufacturer = "BMW"
model = "3 Series"
firmware_version = "v2.4.1-secure"

print(f"
VIN: {vin_number}")
print(f"Araç: {manufacturer} {model}")
print(f"Firmware: {firmware_version}")

# ============ BOOLEAN (bool) ============
is_engine_running = True
airbag_deployed = False
abs_active = False
security_access_granted = False

print(f"
Motor Çalışıyor: {is_engine_running}")
print(f"Güvenlik Erişimi: {security_access_granted}")

# ============ TİP DÖNÜŞÜMLERI ============
can_id_str = "7E0"
can_id_int = int(can_id_str, 16)  # String hex -> int
print(f"
CAN ID: 0x{can_id_str} = {can_id_int} (decimal)")

temperature_str = "92.3"
temperature_float = float(temperature_str)
print(f"Sıcaklık: {temperature_float}°C")

2.2 Tip Kontrolü ve Güvenli Dönüşüm

#!/usr/bin/env python3
"""
Güvenli Tip Dönüşümü - Otomotiv Uygulaması
"""

def safe_convert_to_int(value, base=10):
    """
    Güvenli integer dönüşümü.
    
    Args:
        value: Dönüştürülecek değer
        base: Sayı tabanı (10, 16, 2)
    
    Returns:
        int veya None
    """
    try:
        if isinstance(value, str):
            # Hex prefix kontrolü
            if value.startswith('0x') or value.startswith('0X'):
                return int(value, 16)
            # Binary prefix kontrolü
            elif value.startswith('0b') or value.startswith('0B'):
                return int(value, 2)
            else:
                return int(value, base)
        return int(value)
    except (ValueError, TypeError) as e:
        print(f"[HATA] Dönüşüm başarısız: {e}")
        return None

# Test
test_values = ["7E0", "0x7E0", "2016", "invalid", 255, 12.7]

for val in test_values:
    result = safe_convert_to_int(val, base=16 if isinstance(val, str) and not val.startswith('0') else 10)
    print(f"{val!r:15} -> {result}")

3. Koleksiyonlar (Collections)

3.1 Listeler (list)

#!/usr/bin/env python3
"""
CAN Frame Verileri ile Liste İşlemleri
"""

# ============ CAN FRAME LİSTESİ ============
can_data = [0x02, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]
print(f"CAN Data: {[hex(b) for b in can_data]}")

# Eleman erişimi
service_id = can_data[1]  # UDS Service ID
print(f"Service ID: {hex(service_id)}")  # 0x10 = Diagnostic Session Control

# Slicing
payload = can_data[1:4]  # Service + Sub-function
print(f"Payload: {[hex(b) for b in payload]}")

# Liste metodları
can_data.append(0x55)     # Sona ekle
can_data.insert(0, 0x08)  # Başa DLC ekle
print(f"Güncel Frame: {[hex(b) for b in can_data]}")

# ============ ECU LİSTESİ ============
ecu_list = [
    {"id": 0x7E0, "name": "Engine ECU", "protocol": "UDS"},
    {"id": 0x7E1, "name": "Transmission ECU", "protocol": "UDS"},
    {"id": 0x7E2, "name": "ABS ECU", "protocol": "UDS"},
    {"id": 0x7C0, "name": "Body Control", "protocol": "KWP"},
]

# Liste üzerinde döngü
print("
🔧 Araçtaki ECU'lar:")
for ecu in ecu_list:
    print(f"  - {ecu['name']} (ID: {hex(ecu['id'])})")

# Filtreleme (List Comprehension)
uds_ecus = [ecu for ecu in ecu_list if ecu["protocol"] == "UDS"]
print(f"
UDS ECU sayısı: {len(uds_ecus)}")

3.2 Tuple (Değiştirilemez Listeler)

#!/usr/bin/env python3
"""
Sabit Değerler için Tuple Kullanımı
"""

# CAN Frame yapısı (sabit)
CAN_FRAME_STRUCTURE = (
    ("SOF", 1, "Start of Frame"),
    ("Arbitration ID", 11, "Mesaj önceliği"),
    ("RTR", 1, "Remote Transmission Request"),
    ("IDE", 1, "Identifier Extension"),
    ("r0", 1, "Reserved"),
    ("DLC", 4, "Data Length Code"),
    ("Data", 64, "0-8 byte veri"),
    ("CRC", 15, "Cyclic Redundancy Check"),
    ("ACK", 2, "Acknowledge"),
    ("EOF", 7, "End of Frame"),
)

print("📊 CAN Frame Yapısı:")
print("-" * 50)
for field, bits, desc in CAN_FRAME_STRUCTURE:
    print(f"{field:20} | {bits:3} bit | {desc}")

# UDS Service ID'leri (sabit)
UDS_SERVICES = (
    (0x10, "DiagnosticSessionControl"),
    (0x11, "ECUReset"),
    (0x22, "ReadDataByIdentifier"),
    (0x27, "SecurityAccess"),
    (0x2E, "WriteDataByIdentifier"),
    (0x31, "RoutineControl"),
    (0x34, "RequestDownload"),
    (0x36, "TransferData"),
    (0x37, "RequestTransferExit"),
)

print("
📋 UDS Servisleri:")
for sid, name in UDS_SERVICES:
    print(f"  0x{sid:02X}: {name}")

3.3 Sözlükler (dict)

#!/usr/bin/env python3
"""
ECU Veritabanı - Dictionary Kullanımı
"""

# ============ ECU DATABASE ============
ecu_database = {
    0x7E0: {
        "name": "Engine Control Module",
        "manufacturer": "Bosch",
        "firmware": "v3.2.1",
        "security_level": 3,
        "supported_services": [0x10, 0x11, 0x22, 0x27, 0x2E, 0x31],
        "dtc_list": ["P0300", "P0171", "P0420"]
    },
    0x7E1: {
        "name": "Transmission Control Module",
        "manufacturer": "ZF",
        "firmware": "v2.8.4",
        "security_level": 2,
        "supported_services": [0x10, 0x22, 0x27],
        "dtc_list": ["P0700", "P0715"]
    },
    0x7E2: {
        "name": "ABS Control Module",
        "manufacturer": "Continental",
        "firmware": "v4.1.0",
        "security_level": 4,  # En yüksek güvenlik
        "supported_services": [0x10, 0x22, 0x27, 0x31],
        "dtc_list": ["C0035", "C0040"]
    }
}

# Erişim
engine_ecu = ecu_database.get(0x7E0)
if engine_ecu:
    print(f"Motor ECU: {engine_ecu['name']}")
    print(f"Firmware: {engine_ecu['firmware']}")
    print(f"Güvenlik Seviyesi: {engine_ecu['security_level']}")

# Yeni ECU ekleme
ecu_database[0x7C0] = {
    "name": "Body Control Module",
    "manufacturer": "Hella",
    "firmware": "v1.5.2",
    "security_level": 1,
    "supported_services": [0x10, 0x22],
    "dtc_list": []
}

# Tüm ECU'ları listele
print("
📋 ECU Veritabanı:")
for ecu_id, info in ecu_database.items():
    print(f"
🔹 {hex(ecu_id)}: {info['name']}")
    print(f"   Üretici: {info['manufacturer']}")
    print(f"   Güvenlik: Level {info['security_level']}")

4. Kontrol Yapıları

4.1 Koşullu İfadeler (if/elif/else)

#!/usr/bin/env python3
"""
UDS Response Analizi - Kontrol Yapıları
"""

def analyze_uds_response(response_bytes):
    """
    UDS yanıtını analiz et.
    
    Args:
        response_bytes: bytes - UDS yanıt verisi
    
    Returns:
        dict - Analiz sonucu
    """
    if len(response_bytes) < 1:
        return {"status": "error", "message": "Boş yanıt"}
    
    first_byte = response_bytes[0]
    
    # Pozitif yanıt kontrolü
    if first_byte >= 0x41 and first_byte <= 0x7F:
        service_id = first_byte - 0x40
        return {
            "status": "positive",
            "service": hex(service_id),
            "message": f"Başarılı yanıt: Service 0x{service_id:02X}"
        }
    
    # Negatif yanıt kontrolü
    elif first_byte == 0x7F:
        if len(response_bytes) >= 3:
            rejected_service = response_bytes[1]
            nrc = response_bytes[2]
            
            # NRC (Negative Response Code) açıklamaları
            nrc_descriptions = {
                0x10: "generalReject",
                0x12: "subFunctionNotSupported",
                0x13: "incorrectMessageLengthOrInvalidFormat",
                0x14: "responseTooLong",
                0x22: "conditionsNotCorrect",
                0x31: "requestOutOfRange",
                0x33: "securityAccessDenied",
                0x35: "invalidKey",
                0x36: "exceededNumberOfAttempts",
                0x37: "requiredTimeDelayNotExpired",
                0x72: "generalProgrammingFailure",
                0x78: "requestCorrectlyReceived-ResponsePending"
            }
            
            nrc_desc = nrc_descriptions.get(nrc, "Unknown NRC")
            
            return {
                "status": "negative",
                "service": hex(rejected_service),
                "nrc": hex(nrc),
                "nrc_description": nrc_desc,
                "message": f"Reddedildi: Service 0x{rejected_service:02X}, NRC: 0x{nrc:02X} ({nrc_desc})"
            }
        else:
            return {"status": "error", "message": "Eksik negatif yanıt"}
    
    else:
        return {"status": "unknown", "message": f"Bilinmeyen yanıt: 0x{first_byte:02X}"}

# Test
test_responses = [
    bytes([0x50, 0x01]),              # Pozitif: DiagnosticSessionControl
    bytes([0x62, 0xF1, 0x90]),        # Pozitif: ReadDataByIdentifier
    bytes([0x7F, 0x27, 0x35]),        # Negatif: SecurityAccess - InvalidKey
    bytes([0x7F, 0x10, 0x33]),        # Negatif: DiagSessionCtrl - SecurityAccessDenied
    bytes([0x7F, 0x31, 0x78]),        # Negatif: RoutineControl - ResponsePending
]

print("🔍 UDS Yanıt Analizi:")
print("=" * 60)
for resp in test_responses:
    result = analyze_uds_response(resp)
    print(f"
Yanıt: {resp.hex().upper()}")
    print(f"Durum: {result['status']}")
    print(f"Mesaj: {result['message']}")

4.2 Döngüler (for/while)

#!/usr/bin/env python3
"""
CAN Bus Message Scanning - Döngü Kullanımı
"""

import time
from typing import List, Dict

def scan_can_ids(start_id: int = 0x000, end_id: int = 0x7FF) -> List[Dict]:
    """
    CAN ID aralığını tara (simülasyon).
    
    Args:
        start_id: Başlangıç ID
        end_id: Bitiş ID
    
    Returns:
        Bulunan ECU'ların listesi
    """
    # Simülasyon için bilinen ECU'lar
    known_ecus = {
        0x7E0: "Engine ECU",
        0x7E1: "Transmission ECU",
        0x7E2: "ABS ECU",
        0x7E8: "Engine ECU Response",
        0x7C0: "Body Control",
    }
    
    found_ecus = []
    
    print(f"🔍 CAN ID Tarama: 0x{start_id:03X} - 0x{end_id:03X}")
    print("-" * 50)
    
    for can_id in range(start_id, end_id + 1):
        # Her 100 ID'de ilerleme göster
        if can_id % 100 == 0:
            progress = ((can_id - start_id) / (end_id - start_id)) * 100
            print(f"
[{progress:5.1f}%] Taranan: 0x{can_id:03X}", end="")
        
        # Bilinen ECU bulundu mu?
        if can_id in known_ecus:
            found_ecus.append({
                "id": can_id,
                "hex": f"0x{can_id:03X}",
                "name": known_ecus[can_id],
                "type": "request" if can_id < 0x7E8 else "response"
            })
    
    print(f"
[100.0%] Tarama tamamlandı!")
    print(f"
✅ Bulunan ECU sayısı: {len(found_ecus)}")
    
    return found_ecus

# While döngüsü örneği - Security Access
def security_access_with_retry(max_attempts: int = 3):
    """
    Security Access retry mekanizması.
    """
    attempt = 0
    unlocked = False
    
    while attempt < max_attempts and not unlocked:
        attempt += 1
        print(f"
🔐 Security Access Deneme {attempt}/{max_attempts}")
        
        # Simülasyon: %30 başarı şansı
        import random
        success = random.random() < 0.3
        
        if success:
            unlocked = True
            print("✅ Güvenlik erişimi sağlandı!")
        else:
            print("❌ Erişim reddedildi")
            if attempt < max_attempts:
                print("⏳ 1 saniye bekleniyor...")
                # time.sleep(1)  # Gerçek uygulamada
    
    if not unlocked:
        print(f"
⚠️ {max_attempts} deneme sonrası erişim sağlanamadı!")
    
    return unlocked

# Test
if __name__ == "__main__":
    # CAN ID tarama
    ecus = scan_can_ids(0x700, 0x7FF)
    
    print("
📋 Bulunan ECU'lar:")
    for ecu in ecus:
        print(f"  {ecu['hex']}: {ecu['name']} ({ecu['type']})")
    
    # Security Access
    print("
" + "=" * 50)
    security_access_with_retry(3)

📝 Hafta 1 Pratik Alıştırmalar

Alıştırma 1: CAN ID Dönüştürücü

#!/usr/bin/env python3
"""
Alıştırma: CAN ID Format Dönüştürücü
Kullanıcıdan CAN ID alıp farklı formatlarda gösterin.
"""

def can_id_converter():
    print("=" * 40)
    print("CAN ID FORMAT DÖNÜŞTÜRÜCÜ")
    print("=" * 40)
    
    # Kullanıcıdan input (simülasyon)
    test_inputs = ["7E0", "0x7E8", "2016", "0b11111100000"]
    
    for user_input in test_inputs:
        print(f"
Giriş: {user_input}")
        print("-" * 30)
        
        try:
            # Otomatik format algılama
            if user_input.startswith('0x'):
                value = int(user_input, 16)
            elif user_input.startswith('0b'):
                value = int(user_input, 2)
            elif all(c in '0123456789ABCDEFabcdef' for c in user_input):
                value = int(user_input, 16)
            else:
                value = int(user_input)
            
            print(f"Decimal:     {value}")
            print(f"Hexadecimal: 0x{value:03X}")
            print(f"Binary:      {bin(value)}")
            print(f"11-bit:      {value & 0x7FF:011b}")
            
        except ValueError as e:
            print(f"[HATA] Geçersiz format: {e}")

can_id_converter()

Alıştırma 2: DTC Parser

#!/usr/bin/env python3
"""
Alıştırma: DTC (Diagnostic Trouble Code) Parser
P0420 gibi DTC kodlarını parse edin.
"""

def parse_dtc(dtc_code: str) -> dict:
    """
    DTC kodunu parse et.
    
    Format: XNNNN
    X: Sistem (P=Powertrain, C=Chassis, B=Body, U=Network)
    1. N: 0=Generic, 1=Manufacturer
    2-4. N: Specific fault
    """
    if len(dtc_code) != 5:
        return {"error": "Geçersiz DTC formatı"}
    
    systems = {
        'P': 'Powertrain (Motor/Şanzıman)',
        'C': 'Chassis (Şasi/ABS/ESP)',
        'B': 'Body (Kaporta/Aydınlatma)',
        'U': 'Network (CAN/LIN İletişim)'
    }
    
    subsystems = {
        'P': {'0': 'Yakıt/Hava', '1': 'Yakıt/Hava', '2': 'Enjeksiyon',
              '3': 'Ateşleme', '4': 'Emisyon', '5': 'Hız/Rölanti',
              '6': 'ECU', '7': 'Şanzıman', '8': 'Şanzıman'},
        'C': {'0': 'Genel', '1': 'ABS', '2': 'Direksiyon'},
        'B': {'0': 'Genel', '1': 'Kilitler', '2': 'Camlar'},
        'U': {'0': 'Genel', '1': 'CAN', '2': 'LIN'}
    }
    
    system_char = dtc_code[0].upper()
    generic = dtc_code[1]
    subsystem = dtc_code[2]
    specific = dtc_code[3:5]
    
    return {
        "code": dtc_code.upper(),
        "system": systems.get(system_char, "Unknown"),
        "type": "Generic (SAE)" if generic == '0' else "Manufacturer Specific",
        "subsystem": subsystems.get(system_char, {}).get(subsystem, "Unknown"),
        "fault_number": specific
    }

# Test DTC'ler
test_dtcs = ["P0420", "P0171", "C0035", "B1234", "U0100"]

print("🔍 DTC ANALİZİ")
print("=" * 50)

for dtc in test_dtcs:
    result = parse_dtc(dtc)
    print(f"
📌 {result['code']}")
    print(f"   Sistem: {result['system']}")
    print(f"   Tip: {result['type']}")
    print(f"   Alt Sistem: {result['subsystem']}")

📚 Kaynaklar