File size: 4,446 Bytes
7ea1cf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SSH baglanti testi.



Calistirma:

    python test_ssh.py



Yaptiklari:

    1. .env'i okur, SSHConfig olusturur (eksik alan varsa erken hata).

    2. Kali'ye baglanir, ping atar.

    3. Kimlik / sistem dogrulayan bir dizi guvenli komut calistirir.

    4. Pentest araclarinin (nmap, gobuster, sqlmap, vs.) varligini kontrol eder.

    5. Adim adim yesil/kirmizi rapor basar.



Hata cikarsa son satira bakman yeterli; basarisiz olan adim aciklanir.

"""

from __future__ import annotations

import sys
from typing import Iterable

from logger import SessionLogger
from ssh_client import CommandResult, KaliSSH, SSHConnectionError

# (etiket, komut, basari icin stdout icinde aranacak alt-string ya da None)
SANITY_COMMANDS: tuple[tuple[str, str, str | None], ...] = (
    ("kullanici", "whoami", None),
    ("hostname", "hostname", None),
    ("kernel", "uname -a", "Linux"),
    ("dagitim", "cat /etc/os-release | head -n 5", "kali"),
    ("ip adresleri", "hostname -I", None),
    ("calisma dizini", "pwd", None),
)

PENTEST_TOOLS: tuple[str, ...] = (
    "nmap",
    "gobuster",
    "dirb",
    "sqlmap",
    "msfconsole",
    "hydra",
    "nikto",
)


def _color(code: str, text: str) -> str:
    return f"\033[{code}m{text}\033[0m"


def _ok(msg: str) -> None:
    print(_color("32", "[OK]   ") + msg)


def _fail(msg: str) -> None:
    print(_color("31", "[FAIL] ") + msg)


def _info(msg: str) -> None:
    print(_color("36", "[..]   ") + msg)


def _short(text: str, n: int = 200) -> str:
    text = text.strip().replace("\n", " | ")
    return text if len(text) <= n else text[:n] + "..."


def run_sanity(kali: KaliSSH, items: Iterable[tuple[str, str, str | None]]) -> bool:
    all_ok = True
    for label, cmd, expect in items:
        try:
            res: CommandResult = kali.run(cmd, timeout=15)
        except SSHConnectionError as exc:
            _fail(f"{label}: {exc}")
            all_ok = False
            continue

        if not res.ok:
            _fail(f"{label}: exit={res.exit_code} | {_short(res.stderr or res.stdout)}")
            all_ok = False
            continue

        if expect and expect.lower() not in res.stdout.lower():
            _fail(f"{label}: '{expect}' beklenirdi ama stdout: {_short(res.stdout)}")
            all_ok = False
            continue

        _ok(f"{label}: {_short(res.stdout)}")
    return all_ok


def check_tools(kali: KaliSSH, tools: Iterable[str]) -> None:
    print()
    _info("Pentest araclari kontrolu (eksik olan varsa: sudo apt install ...)")
    for tool in tools:
        try:
            res = kali.run(f"command -v {tool}", timeout=10)
        except SSHConnectionError as exc:
            _fail(f"{tool}: {exc}")
            continue

        if res.ok and res.stdout.strip():
            _ok(f"{tool}: {res.stdout.strip()}")
        else:
            _fail(f"{tool}: bulunamadi")


def main() -> int:
    print(_color("1", "=== Kali SSH baglanti testi ==="))

    # Test scriptinin kendi [OK]/[FAIL] ciktisi var; logger'i sadece dosyaya yaz.
    log = SessionLogger.create(echo_to_console=False)
    log.info("ssh_test_start")

    try:
        kali = KaliSSH.from_config(logger=log)
    except Exception as exc:  # noqa: BLE001
        _fail(f"Konfigurasyon hatasi: {exc}")
        log.close()
        return 2

    _info(
        f"Hedef: {kali.cfg.username}@{kali.cfg.host}:{kali.cfg.port} "
        f"(anahtar: {kali.cfg.key_path})"
    )

    try:
        kali.connect()
    except SSHConnectionError as exc:
        _fail(str(exc))
        log.close()
        return 1
    _ok("TCP + kimlik dogrulama basarili")

    if not kali.ping():
        _fail("Ping (echo pong) basarisiz; kanal saglikli degil")
        kali.close()
        log.close()
        return 1
    _ok("Kanal saglikli (echo pong)")

    print()
    _info("Sanity komutlari calistiriliyor...")
    sanity_ok = run_sanity(kali, SANITY_COMMANDS)

    check_tools(kali, PENTEST_TOOLS)

    kali.close()
    log.info("ssh_test_done", sanity_ok=sanity_ok)
    log.close()

    print()
    if sanity_ok:
        print(_color("32;1", "TUM SANITY KONTROLLERI GECTI."))
        return 0

    print(_color("31;1", "BAZI KONTROLLER BASARISIZ. Yukaridaki [FAIL] satirlarini incele."))
    return 1


if __name__ == "__main__":
    sys.exit(main())