├── Framework ├── IPHlpApi.Lib ├── install.c ├── iphlpapi.h ├── main.c ├── main.h └── udp.c ├── LICENSE ├── README.md ├── batch.bat ├── install.reg ├── printAnalyze ├── db2interface.py ├── db2interface.pyc ├── pginterface.py ├── printacces.py ├── printaccesspec.py ├── printdumpsession.py ├── printid.py ├── printload.py ├── printres.py ├── printreseau.py ├── printscontext.py ├── printscontextassociated.py ├── printtcontext.py ├── printtcontextassociated.py └── server.py ├── savePost ├── client_test.py ├── db2interface.py ├── line.py ├── line.pyc ├── lineThread.py ├── lineThread.pyc ├── pginterface.py ├── pginterface.pyc ├── server.py ├── xmlParser.py └── xmlParser.pyc ├── script.bat ├── sys ├── MAKEFILE ├── SOURCES ├── createprocess.c ├── driver.h ├── file.c ├── framework.c ├── network.c ├── registry.c └── shared.h └── traceAnalyzer ├── client_test.py ├── db2interface.py ├── db2interface.pyc ├── line.py ├── line.pyc ├── lineThread.py ├── lineThread.pyc ├── pginterface.py ├── pginterface.pyc ├── server.py ├── xmlParser.py └── xmlParser.pyc /Framework/IPHlpApi.Lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/Framework/IPHlpApi.Lib -------------------------------------------------------------------------------- /Framework/install.c: -------------------------------------------------------------------------------- 1 | #include "main.h" 2 | 3 | char name[]="dkf"; 4 | char path[]="C:\\dkf.sys";//C:\CEA\Programmation\Driver\sys\objfre_win7_x86\i386"C:\\EasyHook.sys";// 5 | void installation() 6 | { 7 | InstallDriver (schSCManager, name,path); 8 | StartDriver (schSCManager,name); 9 | } 10 | 11 | void suppression() 12 | { 13 | StopDriver (schSCManager,name); 14 | RemoveDriver (schSCManager,name); 15 | } 16 | 17 | BOOL 18 | InstallDriver( 19 | IN SC_HANDLE SchSCManager, 20 | IN LPCTSTR DriverName, 21 | IN LPCTSTR ServiceExe 22 | ) 23 | /*++ 24 | 25 | Routine Description: 26 | 27 | Arguments: 28 | 29 | Return Value: 30 | 31 | --*/ 32 | { 33 | SC_HANDLE schService; 34 | DWORD err; 35 | 36 | schService = CreateService (SchSCManager, // SCManager database 37 | DriverName, // name of service 38 | DriverName, // name to display 39 | SERVICE_ALL_ACCESS, // desired access 40 | SERVICE_KERNEL_DRIVER, // service type 41 | SERVICE_AUTO_START, // start type 42 | SERVICE_ERROR_NORMAL, // error control type 43 | ServiceExe, // service's binary 44 | NULL, // no load ordering group 45 | NULL, // no tag identifier 46 | NULL, // no dependencies 47 | NULL, // LocalSystem account 48 | NULL // no password 49 | ); 50 | 51 | if (schService == NULL) 52 | { 53 | err = GetLastError(); 54 | 55 | if (err == ERROR_SERVICE_EXISTS) 56 | { 57 | // 58 | // A common cause of failure (easier to read than an error code) 59 | // 60 | 61 | printf ("failure: CreateService, ERROR_SERVICE_EXISTS\n"); 62 | } 63 | else 64 | { 65 | printf ("failure: CreateService (0x%02x)\n", 66 | (int)err 67 | ); 68 | } 69 | 70 | return FALSE; 71 | } 72 | else 73 | { 74 | printf ("CreateService SUCCESS\n"); 75 | } 76 | 77 | CloseServiceHandle (schService); 78 | 79 | return TRUE; 80 | } 81 | 82 | 83 | 84 | BOOL 85 | RemoveDriver( 86 | IN SC_HANDLE SchSCManager, 87 | IN LPCTSTR DriverName 88 | ) 89 | /*++ 90 | 91 | Routine Description: 92 | 93 | Arguments: 94 | 95 | Return Value: 96 | 97 | --*/ 98 | { 99 | SC_HANDLE schService; 100 | BOOL ret; 101 | 102 | schService = OpenService (SchSCManager, 103 | DriverName, 104 | SERVICE_ALL_ACCESS 105 | ); 106 | 107 | if (schService == NULL) 108 | { 109 | printf ("failure: OpenService (0x%02x)\n", (int)GetLastError()); 110 | return FALSE; 111 | } 112 | 113 | ret = DeleteService (schService); 114 | 115 | if (ret) 116 | { 117 | printf ("DeleteService SUCCESS\n"); 118 | } 119 | else 120 | { 121 | printf ("failure: DeleteService (0x%02x)\n", 122 | (int)GetLastError() 123 | ); 124 | } 125 | 126 | CloseServiceHandle (schService); 127 | 128 | return ret; 129 | } 130 | 131 | 132 | 133 | BOOL 134 | StartDriver( 135 | IN SC_HANDLE SchSCManager, 136 | IN LPCTSTR DriverName 137 | ) 138 | { 139 | SC_HANDLE schService; 140 | BOOL ret; 141 | DWORD err; 142 | 143 | schService = OpenService (SchSCManager, 144 | DriverName, 145 | SERVICE_ALL_ACCESS 146 | ); 147 | 148 | if (schService == NULL) 149 | { 150 | printf ("failure: OpenService (0x%02x)\n", (int)GetLastError()); 151 | return FALSE; 152 | } 153 | 154 | ret = StartService (schService, // service identifier 155 | 0, // number of arguments 156 | NULL // pointer to arguments 157 | ); 158 | if (ret) 159 | { 160 | printf ("StartService SUCCESS\n"); 161 | } 162 | else 163 | { 164 | err = GetLastError(); 165 | 166 | if (err == ERROR_SERVICE_ALREADY_RUNNING) 167 | { 168 | // 169 | // A common cause of failure (easier to read than an error code) 170 | // 171 | 172 | printf ("failure: StartService, ERROR_SERVICE_ALREADY_RUNNING\n"); 173 | } 174 | else 175 | { 176 | printf ("failure: StartService (0x%02x)\n", 177 | (int)err 178 | ); 179 | } 180 | } 181 | 182 | CloseServiceHandle (schService); 183 | 184 | return ret; 185 | } 186 | 187 | 188 | 189 | BOOL 190 | StopDriver( 191 | IN SC_HANDLE SchSCManager, 192 | IN LPCTSTR DriverName 193 | ) 194 | { 195 | SC_HANDLE schService; 196 | BOOL ret; 197 | SERVICE_STATUS serviceStatus; 198 | 199 | schService = OpenService (SchSCManager, 200 | DriverName, 201 | SERVICE_ALL_ACCESS 202 | ); 203 | 204 | if (schService == NULL) 205 | { 206 | printf ("failure: OpenService (0x%02x)\n", (int)GetLastError()); 207 | return FALSE; 208 | } 209 | 210 | ret = ControlService (schService, 211 | SERVICE_CONTROL_STOP, 212 | &serviceStatus 213 | ); 214 | if (ret) 215 | { 216 | printf ("ControlService SUCCESS\n"); 217 | } 218 | else 219 | { 220 | printf ("failure: ControlService (0x%02x)\n", 221 | (int)GetLastError() 222 | ); 223 | } 224 | 225 | CloseServiceHandle (schService); 226 | 227 | return ret; 228 | } 229 | 230 | 231 | -------------------------------------------------------------------------------- /Framework/main.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/Framework/main.c -------------------------------------------------------------------------------- /Framework/main.h: -------------------------------------------------------------------------------- 1 | #define _WIN32_WINNT 0x501 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | 14 | 15 | #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x)) 16 | #define FREE(x) HeapFree(GetProcessHeap(), 0, (x)) 17 | 18 | #define FILE_DEVICE_DKF 0x12345678 19 | #define IOCTL_DKF_START (ULONG) CTL_CODE(FILE_DEVICE_DKF,0x00, METHOD_BUFFERED, FILE_ANY_ACCESS) 20 | #define IOCTL_DKF_STOP (ULONG) CTL_CODE(FILE_DEVICE_DKF,0x01, METHOD_BUFFERED, FILE_ANY_ACCESS) 21 | #define IOCTL_DKF_SHUTDOWN (ULONG) CTL_CODE(FILE_DEVICE_DKF,0x02, METHOD_BUFFERED, FILE_ANY_ACCESS) 22 | 23 | #define DEFAULT_BUFLEN 5096 24 | #define DEFAULT_PORT 9998 25 | 26 | 27 | typedef struct TCPInfo { 28 | char localip[128]; 29 | int localport; 30 | char distip[128]; 31 | int distport; 32 | char state[20]; 33 | } TCPInfo; 34 | 35 | typedef struct UDPInfo { 36 | char localip[128]; 37 | int localport; 38 | } UDPInfo; 39 | 40 | NTSTATUS ( WINAPI *NtLoadDriver ) ( IN PUNICODE_STRING DriverServiceName ); 41 | NTSTATUS ( WINAPI *NtUnLoadDriver ) ( IN PUNICODE_STRING DriverServiceName ); 42 | VOID (WINAPI * RtlInitUnicodeString ) ( PUNICODE_STRING DestinationString, PCWSTR SourceString); 43 | 44 | 45 | BOOL InstallDriver(IN SC_HANDLE SchSCManager,IN LPCTSTR DriverName, IN LPCTSTR ServiceExe); 46 | BOOL RemoveDriver(IN SC_HANDLE SchSCManager,IN LPCTSTR DriverName); 47 | BOOL StartDriver(IN SC_HANDLE SchSCManager,IN LPCTSTR DriverName); 48 | BOOL StopDriver(IN SC_HANDLE SchSCManager,IN LPCTSTR DriverName); 49 | void installation(); 50 | void suppression(); 51 | void MakeXML(char * buffer); 52 | void ListenDriver(); 53 | TCPInfo GetIpTcp(int pidsearch); 54 | void MakeXMLNet(char * buffer); 55 | void ListenDriverNet(); 56 | 57 | 58 | UDPInfo GetUdpInfo(int pidsearch); 59 | void Initialize(); 60 | 61 | void SetDebugPrivilege(); 62 | 63 | int connection(); 64 | int sendmesg(char * sendbuf); 65 | int closeconnection(); 66 | 67 | SC_HANDLE schSCManager; 68 | 69 | -------------------------------------------------------------------------------- /Framework/udp.c: -------------------------------------------------------------------------------- 1 | #include "main.h" 2 | 3 | 4 | typedef enum { 5 | UDP_TABLE_BASIC, 6 | UDP_TABLE_OWNER_PID, 7 | UDP_TABLE_OWNER_MODULE 8 | } UDP_TABLE_CLASS, *PUDP_TABLE_CLASS; 9 | 10 | 11 | 12 | typedef struct _MIB_UDPROW_OWNER_PID { 13 | DWORD dwLocalAddr; 14 | DWORD dwLocalPort; 15 | DWORD dwOwningPid; 16 | } MIB_UDPROW_OWNER_PID, *PMIB_UDPROW_OWNER_PID; 17 | typedef struct _MIB_UDPTABLE_OWNER_PID { 18 | DWORD dwNumEntries; 19 | MIB_UDPROW_OWNER_PID table[ANY_SIZE]; 20 | } MIB_UDPTABLE_OWNER_PID, *PMIB_UDPTABLE_OWNER_PID; 21 | 22 | DWORD (WINAPI * GetExtendedUdpTable) ( 23 | PVOID pUdpTable, 24 | PDWORD pdwSize, 25 | BOOL bOrder, 26 | ULONG ulAf, 27 | UDP_TABLE_CLASS TableClass, 28 | ULONG Reserved 29 | ); 30 | 31 | 32 | void Initialize() 33 | { 34 | 35 | HMODULE hmod; 36 | hmod = LoadLibrary("Iphlpapi.dll"); 37 | 38 | if(hmod) 39 | { 40 | GetExtendedUdpTable = ( DWORD (WINAPI *) ( PVOID , PDWORD, BOOL, ULONG, UDP_TABLE_CLASS , ULONG ) ) GetProcAddress(hmod, "GetExtendedUdpTable"); 41 | } 42 | 43 | 44 | } 45 | 46 | UDPInfo GetUdpInfo(int pidsearch) 47 | { 48 | 49 | PMIB_UDPTABLE_OWNER_PID pUdpTable; 50 | DWORD dwSize = 0; 51 | DWORD dwRetVal = 0; 52 | 53 | struct in_addr IpAddr; 54 | int i=0; 55 | UDPInfo udp; 56 | 57 | pUdpTable = (MIB_UDPTABLE_OWNER_PID *) MALLOC(sizeof (MIB_UDPTABLE_OWNER_PID)); 58 | if (pUdpTable == NULL) { 59 | printf("Error allocating memory\n"); 60 | return udp; 61 | } 62 | 63 | dwSize = sizeof (PMIB_UDPTABLE_OWNER_PID); 64 | // Make an initial call to GetTcpTable to 65 | // get the necessary size into the dwSize variable 66 | if ((dwRetVal = GetExtendedUdpTable(pUdpTable, &dwSize, TRUE,AF_INET, UDP_TABLE_OWNER_PID, 0)) == 67 | ERROR_INSUFFICIENT_BUFFER) { 68 | FREE(pUdpTable); 69 | pUdpTable = (MIB_UDPTABLE_OWNER_PID *) MALLOC(dwSize); 70 | if (pUdpTable == NULL) { 71 | printf("Error allocating memory\n"); 72 | return udp; 73 | } 74 | } 75 | // Make a second call to GetTcpTable to get 76 | // the actual data we require 77 | 78 | dwRetVal = GetExtendedUdpTable(pUdpTable, &dwSize, TRUE,AF_INET, UDP_TABLE_OWNER_PID, 0); 79 | 80 | if (dwRetVal == NO_ERROR) 81 | { 82 | while(pUdpTable->table[i].dwOwningPid != pidsearch && i<(int) pUdpTable->dwNumEntries) 83 | i++; 84 | 85 | IpAddr.S_un.S_addr = (u_long) pUdpTable->table[i].dwLocalAddr; 86 | strcpy(udp.localip, inet_ntoa(IpAddr) ); 87 | udp.localport =ntohs((u_short)pUdpTable->table[i].dwLocalPort) ; 88 | 89 | } else { 90 | printf("\tGetTcpTable failed with %i\n", (int)dwRetVal); 91 | FREE(pUdpTable); 92 | return udp; 93 | } 94 | 95 | if (pUdpTable != NULL) { 96 | FREE(pUdpTable); 97 | pUdpTable = NULL; 98 | } 99 | 100 | return udp; 101 | } 102 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Malware_Analyzer 2 | Framework complet d'analyse de malware 3 | 4 | - Détournement du flux par hook de la SSDT 5 | - Envoie des traces à un programme grâce à des pipes named (en C) 6 | - Envoie des traces à un serveur qui le stocke dans une base de donnée (traitement réalisé en python) 7 | - Extraction des informations pertinentes à partir de la base de données (toujours en python) 8 | 9 | -------------------------------------------------------------------------------- /batch.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | 4 | rem toto 5 | setlocal enabledelayedexpansion 6 | 7 | :loop 8 | echo "dans loop" 9 | FOR /F "tokens=*" %%i in ('dir /B "\inetpub\ftproot\toto"') do SET TOOLOUTPUT=%%i 10 | echo "!errorlevel!" 11 | if %TOOLOUTPUT% == "" echo "Nothing" 12 | 13 | 14 | endlocal 15 | 16 | FOR /F "tokens=*" %%i in ('dir /B "\inetpub\ftproot\toto"') do SET TOOLOUTPUT=%%i 17 | 18 | 19 | echo "rototot %TOOLOUTPUT%" 20 | pause -------------------------------------------------------------------------------- /install.reg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/install.reg -------------------------------------------------------------------------------- /printAnalyze/db2interface.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import MySQLdb as DB2 3 | from datetime import date, datetime, timedelta 4 | 5 | class dbconfig: 6 | database = 'framecea' # Database to connect to. Please use an empty database for best results. 7 | user = 'postgres' # User ID to connect with 8 | password = 'db2011' # Password for given User ID 9 | hostname = 'localhost' # Hostname 10 | port = 5432 # Port Number 11 | 12 | class dbinterface: 13 | 14 | __idalarm = 0 15 | __idurlnext = 0 16 | 17 | def __init__(self, dbconfig): 18 | self.dbconfig = dbconfig 19 | self.conn =DB2.connect ( host='127.0.0.1', db='framecea', user='root', passwd='azerty') 20 | # self.conn = DB2.connect ( '127.0.0.1:framecea:postgres:db2011') 21 | 22 | 23 | self.cpt = 0 24 | 25 | 26 | def newIdSession(self, boolean): 27 | request = "SELECT idsession FROM session" 28 | 29 | cursor = self.conn.cursor() 30 | 31 | cursor.execute(request) 32 | self.conn.commit() 33 | 34 | # row = cursor.fetchall() 35 | if boolean == 0: 36 | while(1): 37 | row = cursor.fetchone() 38 | if row == None: break 39 | sessionMax = row[0] 40 | print("Session ID: "+str(row[0])) 41 | 42 | print("Max ID : " + str(sessionMax)) 43 | else: 44 | while(1): 45 | row = cursor.fetchone() 46 | if row == None: break 47 | sessionMax = row[0] 48 | 49 | cursor.close() 50 | 51 | return sessionMax 52 | 53 | 54 | #(id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return integer, pid int, ppid int, scontext varchar(256), nameSubject CLOB(10K), nameObject CLOB(10K), tcontext varchar(256), perms varchar(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 55 | 56 | 57 | def dumpSContextSession(self, id): 58 | 59 | request = "SELECT DISTINCT SCONTEXT, pid, nameSubject FROM trace WHERE idsession=" +str(id) 60 | cursor = self.conn.cursor() 61 | cursor.execute(request) 62 | liste = [] 63 | while(1): 64 | row = cursor.fetchone() 65 | if row == None: break 66 | liste.append(str(row)) 67 | 68 | cursor.close() 69 | for titi in liste: 70 | print titi 71 | 72 | def dumpTContextSession(self, id): 73 | 74 | request = "SELECT DISTINCT tcontext from trace WHERE idsession=" +str(id) 75 | cursor = self.conn.cursor() 76 | cursor.execute(request) 77 | liste = [] 78 | while(1): 79 | row = cursor.fetchone() 80 | if row == None: break 81 | liste.append(str(row[0])) 82 | 83 | cursor.close() 84 | for titi in liste: 85 | print titi 86 | 87 | def dumpSession(self, id): 88 | 89 | request = "SELECT * from trace WHERE idsession=" +str(id) 90 | cursor = self.conn.cursor() 91 | cursor.execute(request) 92 | liste = [] 93 | while(1): 94 | row = cursor.fetchone() 95 | if row == None: break 96 | liste.append(str(row)) 97 | 98 | cursor.close() 99 | for titi in liste: 100 | print titi 101 | 102 | def TContextForSContext(self, id, context): 103 | request = "SELECT DISTINCT tcontext from trace WHERE idsession=" +str(id) + " AND SCONTEXT like '%" + str(context) + "%'" 104 | print request 105 | cursor = self.conn.cursor() 106 | cursor.execute(request) 107 | liste = [] 108 | while(1): 109 | row = cursor.fetchone() 110 | if row == None: break 111 | liste.append(str(row[0])) 112 | 113 | cursor.close() 114 | for titi in liste: 115 | print titi 116 | 117 | def SContextForTContext(self, id, context): 118 | request = "SELECT scontext from trace WHERE idsession=" +str(id) + " AND TCONTEXT like '%" + str(context) + "%'" 119 | print request 120 | cursor = self.conn.cursor() 121 | cursor.execute(request) 122 | liste = [] 123 | while(1): 124 | row = cursor.fetchone() 125 | if row == None: break 126 | liste.append(str(row[0])) 127 | 128 | cursor.close() 129 | for titi in liste: 130 | print titi 131 | 132 | def AccessForContext(self, id, scontext, tcontext): 133 | request = "SELECT * from trace WHERE idsession=" +str(id) + " AND SCONTEXT like '%" + str(scontext) + "%' AND TCONTEXT like '%" + str(tcontext) + "%'" 134 | print request 135 | cursor = self.conn.cursor() 136 | cursor.execute(request) 137 | liste = [] 138 | while(1): 139 | row = cursor.fetchone() 140 | if row == None: break 141 | liste.append(str(row)) 142 | cursor.close() 143 | for item in liste: 144 | print item 145 | 146 | def SpecificAccess(self, id, droit): 147 | request = "SELECT * from trace WHERE idsession=" +str(id) + " AND PERMS like ' " + str(droit) +" '" 148 | print request 149 | cursor = self.conn.cursor() 150 | cursor.execute(request) 151 | liste = [] 152 | while(1): 153 | row = cursor.fetchone() 154 | if row == None: break 155 | liste.append(str(row)) 156 | cursor.close() 157 | for item in liste: 158 | print item 159 | def SpecificAccessForScontext(self, id, droit, scontext): 160 | request = "SELECT * from trace WHERE idsession=" +str(id) + " AND PERMS like ' " + str(droit) +" ' AND SCONTEXT like '%" + str(scontext)+ "%'" 161 | print request 162 | cursor = self.conn.cursor() 163 | cursor.execute(request) 164 | liste = [] 165 | while(1): 166 | row = cursor.fetchone() 167 | if row == None: break 168 | liste.append(str(row)) 169 | cursor.close() 170 | for item in liste: 171 | print item 172 | 173 | def LoadAll(self, id): 174 | request = "SELECT * from trace WHERE idsession=" +str(id) + " AND TYPE like 'load'" 175 | print request 176 | cursor = self.conn.cursor() 177 | cursor.execute(request) 178 | liste = [] 179 | while(1): 180 | row = cursor.fetchone() 181 | if row == None: break 182 | liste.append(str(row)) 183 | cursor.close() 184 | for item in liste: 185 | print item 186 | 187 | def LoadForContext(self, id, scontext): 188 | request = "SELECT * from trace WHERE idsession=" +str(id) + " AND TYPE like 'load' AND SCONTEXT like '%" + str(scontext) +"%'" 189 | print request 190 | cursor = self.conn.cursor() 191 | cursor.execute(request) 192 | liste = [] 193 | while(1): 194 | row = cursor.fetchone() 195 | if row == None: break 196 | liste.append(str(row)) 197 | cursor.close() 198 | for item in liste: 199 | print item 200 | 201 | 202 | def dumpIPSession(self, id): 203 | 204 | request = "SELECT scontext,ipSource, PortSource,ipDest,PortDest, proto from tracenet WHERE idsession=" +str(id) 205 | cursor = self.conn.cursor() 206 | cursor.execute(request) 207 | liste = [] 208 | while(1): 209 | row = cursor.fetchone() 210 | if row == None: break 211 | liste.append(str(row)) 212 | 213 | cursor.close() 214 | for item in liste: 215 | print item 216 | 217 | def dumpIPScontext(self, id, scontext): 218 | 219 | request = "SELECT ipSource, PortSource,ipDest,PortDest, proto from tracenet WHERE idsession=" +str(id) + " AND SCONTEXT like '%" + str(scontext) +"%'" 220 | cursor = self.conn.cursor() 221 | cursor.execute(request) 222 | liste = [] 223 | while(1): 224 | row = cursor.fetchone() 225 | if row == None: break 226 | liste.append(str(row)) 227 | 228 | cursor.close() 229 | for item in liste: 230 | print item 231 | 232 | def dumpIPProto(self, id, proto): 233 | 234 | request = "SELECT scontext,ipSource, PortSource,ipDest,PortDest from tracenet WHERE idsession=" +str(id) + " AND proto like '%" + str(proto) +"%'" 235 | cursor = self.conn.cursor() 236 | cursor.execute(request) 237 | liste = [] 238 | while(1): 239 | row = cursor.fetchone() 240 | if row == None: break 241 | liste.append(str(row)) 242 | 243 | cursor.close() 244 | for item in liste: 245 | print item 246 | 247 | 248 | def dumpIPAccess(self, id, scontext, proto): 249 | 250 | request = "SELECT ipSource, PortSource,ipDest,PortDest from tracenet WHERE idsession=" +str(id) + " AND proto like '%" + str(proto) +"%' AND SCONTEXT like '%" + str(scontext) +"%'" 251 | cursor = self.conn.cursor() 252 | cursor.execute(request) 253 | liste = [] 254 | while(1): 255 | row = cursor.fetchone() 256 | if row == None: break 257 | liste.append(str(row)) 258 | 259 | cursor.close() 260 | for item in liste: 261 | print item 262 | 263 | def dumpIPStato(self, id, scontext): 264 | 265 | request = "SELECT scontext,ipSource, PortSource,ipDest,PortDest, state from tracenet WHERE idsession=" +str(id) + " AND proto like '%" + str(proto) +"%'" 266 | cursor = self.conn.cursor() 267 | cursor.execute(request) 268 | liste = [] 269 | while(1): 270 | row = cursor.fetchone() 271 | if row == None: break 272 | liste.append(str(row)) 273 | 274 | cursor.close() 275 | for item in liste: 276 | print item 277 | 278 | # [tri.append(item.lstrip()) for item in liste if not item.lstrip() in tri] 279 | # tri.sort() 280 | 281 | """ 282 | def insertNet(self, id, idsession, ts, type, ret, pid, ppid, scontext, nameSubject, ipsource, portsource, ipdest, portdest, state, typeconnect, netsize, proto, data): 283 | try: 284 | tsp = datetime(1601, 1, 1) + timedelta(microseconds=int(ts)/10) 285 | request = "INSERT INTO tracenet(id,idsession,tstamp,type,return,pid,ppid,scontext,nameSubject,ipSource,PortSource,ipDest,PortDest,state,typeconnect,netsize,proto,data) VALUES("+str(id)+"," 286 | request = request+str(idsession)+",'" 287 | request = request+DB2.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second, tsp.microsecond).get_SQL_value()+"','" 288 | request = request+str(type)+"','"+str(ret)+"',"+str(pid)+","+str(ppid)+",'" 289 | request = request+scontext.replace("'","''")+"','" 290 | request = request+nameSubject.replace("'","''")+"','" 291 | request = request+ipsource+"',"+portsource+",'" 292 | request = request+ipdest+"',"+portdest+",'" 293 | request = request+state+"','"+typeconnect+"',"+netsize+",'"+proto+"','" 294 | request = request+data.replace("'","''")+"')" 295 | except: 296 | self.log.debug("db2interface:insertNet:"+request) 297 | return 298 | #self.log.debug("InsertLine: "+request) 299 | cursor = self.conn.cursor() 300 | try: 301 | request = request.decode("unicode","replace") 302 | except: 303 | try: 304 | request = request.encode('ascii', 'xmlcharrefreplace') 305 | #request.encode("utf8") 306 | except: 307 | request = "%s" % request 308 | try: 309 | try: 310 | request = request.encode("utf8") 311 | except: 312 | print("Error encoding UTF8") 313 | cursor.execute(request) 314 | except: 315 | print("Error DB2: "+request) 316 | request = request.encode('ascii', 'xmlcharrefreplace') 317 | try: 318 | cursor.execute(request) 319 | except: 320 | print("Error DB2 ASCII: "+request) 321 | 322 | if self.cpt == 1000: 323 | self.conn.commit() 324 | self.cpt = 0 325 | else: 326 | self.cpt = self.cpt + 1 327 | 328 | # self.conn.commit() 329 | cursor.close() 330 | return 1 331 | """ 332 | -------------------------------------------------------------------------------- /printAnalyze/db2interface.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/printAnalyze/db2interface.pyc -------------------------------------------------------------------------------- /printAnalyze/pginterface.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import pgdb as DB2 3 | from datetime import date, datetime, timedelta 4 | 5 | class dbconfig: 6 | database = 'framecea' # Database to connect to. Please use an empty database for best results. 7 | user = 'postgres' # User ID to connect with 8 | password = 'db2011' # Password for given User ID 9 | hostname = 'localhost' # Hostname 10 | port = 5432 # Port Number 11 | 12 | class dbinterface: 13 | 14 | __idalarm = 0 15 | __idurlnext = 0 16 | 17 | def __init__(self, dbconfig, logging, dblock): 18 | self.dbconfig = dbconfig 19 | self.log = logging 20 | self.dblock = dblock 21 | try: 22 | self.conn = DB2.connect ( '127.0.0.1:framecea:postgres:db2011') 23 | #self.conn = DB2.connect (dsn = self.dbconfig.database, user = self.dbconfig.user, password = self.dbconfig.password, host = self.dbconfig.hostname ) 24 | except: 25 | print("Connexion failed: toto") 26 | self.cpt = 0 27 | 28 | def newIdSession(self): 29 | request = "SELECT MAX(idsession) FROM session" 30 | insertLine = "INSERT INTO session(samplename,ostype) VALUES(' ',' ')" 31 | 32 | cursor = self.conn.cursor() 33 | 34 | self.dblock.acquire() 35 | 36 | cursor.execute(insertLine) 37 | 38 | cursor.execute(request.encode("utf-8","replace")) 39 | 40 | row = cursor.fetchone() 41 | sessionMax = row[0] 42 | 43 | #self.log.debug("Session Max ID: "+str(sessionMax)) 44 | 45 | self.conn.commit() 46 | 47 | self.dblock.release() 48 | 49 | cursor.close() 50 | 51 | return sessionMax 52 | 53 | 54 | #(id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return integer, pid int, ppid int, scontext varchar(256), nameSubject CLOB(10K), nameObject CLOB(10K), tcontext varchar(256), perms varchar(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 55 | def insert(self, id, idsession, ts, type, ret, pid, ppid, scontext, nameSubject, nameObject, tcontext, perms, data): 56 | tsp = datetime(1601, 1, 1) + timedelta(microseconds=int(ts)/10) 57 | request = "INSERT INTO trace(id,idsession,tstamp,type,return,pid,ppid,scontext,nameSubject,nameObject,tcontext,perms,data) VALUES("+str(id)+"," 58 | request = request+str(idsession)+",'" 59 | request = request+str(DB2.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second))+"','" 60 | request = request+str(type)+"','"+str(ret)+"',"+str(pid)+","+str(ppid)+",'" 61 | request = request+scontext.replace("'","''")+"','" 62 | request = request+nameSubject.replace("'","''").replace("\\","/")+"','" 63 | request = request+nameObject.replace("'","''").replace("\\","/") +"','" 64 | request = request+tcontext.replace("'","''")+"','" 65 | request = request+perms+"','" 66 | request = request+data.replace("'","''")+"')" 67 | #self.log.debug("InsertLine: "+request) 68 | cursor = self.conn.cursor() 69 | try: 70 | request = request.decode("unicode","replace") 71 | except: 72 | try: 73 | request = request.encode('ascii', 'xmlcharrefreplace') 74 | #request.encode("utf8") 75 | except: 76 | request = "%s" % request 77 | request = request.encode("utf8") 78 | #except: 79 | # print("Error encoding UTF8") 80 | cursor.execute(request) 81 | 82 | self.conn.commit() 83 | print request 84 | # if self.cpt == 1: 85 | # self.conn.commit() 86 | # self.conn.commit() 87 | # self.cpt = 0 88 | #else: 89 | # self.cpt = self.cpt + 1 90 | 91 | # self.conn.commit() 92 | cursor.close() 93 | return 1 94 | 95 | def insertNet(self, id, idsession, ts, type, ret, pid, ppid, scontext, nameSubject, ipsource, portsource, ipdest, portdest, state, typeconnect, netsize, proto, data): 96 | try: 97 | tsp = datetime(1601, 1, 1) + timedelta(microseconds=int(ts)/10) 98 | request = "INSERT INTO tracenet(id,idsession,tstamp,type,return,pid,ppid,scontext,nameSubject,ipSource,PortSource,ipDest,PortDest,state,typeconnect,netsize,proto,data) VALUES("+str(id)+"," 99 | request = request+str(idsession)+",'" 100 | request = request+DB2.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second)+"','" 101 | request = request+str(type)+"','"+str(ret)+"',"+str(pid)+","+str(ppid)+",'" 102 | request = request+scontext.replace("'","''")+"','" 103 | request = request+nameSubject.replace("'","''").replace("\\","/")+"','" 104 | request = request+ipsource+"',"+portsource+",'" 105 | request = request+ipdest+"',"+portdest+",'" 106 | request = request+state+"','"+typeconnect+"',"+netsize+",'"+proto+"','" 107 | request = request+data.replace("'","''")+"')" 108 | except: 109 | self.log.debug("db2interface:insertNet:"+request) 110 | return 111 | #self.log.debug("InsertLine: "+request) 112 | cursor = self.conn.cursor() 113 | try: 114 | request = request.decode("unicode","replace") 115 | except: 116 | try: 117 | request = request.encode('ascii', 'xmlcharrefreplace') 118 | #request.encode("utf8") 119 | except: 120 | request = "%s" % request 121 | try: 122 | try: 123 | request = request.encode("utf8") 124 | except: 125 | print("Error encoding UTF8") 126 | cursor.execute(request) 127 | except: 128 | print("Error DB2: "+request) 129 | request = request.encode('ascii', 'xmlcharrefreplace') 130 | try: 131 | cursor.execute(request) 132 | except: 133 | print("Error DB2 ASCII: "+request) 134 | 135 | if self.cpt == 1000: 136 | self.conn.commit() 137 | self.cpt = 0 138 | else: 139 | self.cpt = self.cpt + 1 140 | 141 | # self.conn.commit() 142 | cursor.close() 143 | return 1 144 | 145 | -------------------------------------------------------------------------------- /printAnalyze/printacces.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from db2interface import * 3 | 4 | 5 | if __name__ == "__main__": 6 | 7 | dbconfig=dbconfig() 8 | db2 = dbinterface(dbconfig) 9 | boolean = 0 10 | boolean1 = 0 11 | boolean2 = 0 12 | session = 0 13 | scontext = "" 14 | tcontext = "" 15 | for arg in sys.argv: 16 | if boolean == 1: 17 | session = arg 18 | boolean = 0 19 | if arg == "-i": 20 | boolean = 1 21 | if boolean1 == 1: 22 | scontext = arg 23 | boolean1 = 0 24 | if arg == "-s": 25 | boolean1 = 1 26 | if boolean2 == 1: 27 | tcontext = arg 28 | boolean2 = 0 29 | if arg == "-t": 30 | boolean2= 1 31 | if boolean == 0: 32 | session = db2.newIdSession(1) 33 | 34 | if scontext != "" and tcontext != "" and session > 0: 35 | db2.AccessForContext(session, scontext, tcontext) 36 | else: 37 | print "syntaxe : -i id -s scontext -t tcontext" 38 | -------------------------------------------------------------------------------- /printAnalyze/printaccesspec.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from db2interface import * 3 | 4 | 5 | if __name__ == "__main__": 6 | 7 | dbconfig=dbconfig() 8 | db2 = dbinterface(dbconfig) 9 | boolean = 0 10 | boolean1 = 0 11 | boolean2 = 0 12 | session = 0 13 | access = "" 14 | scontext = "" 15 | for arg in sys.argv: 16 | if boolean2 == 1: 17 | scontext = arg 18 | boolean2 = 0 19 | if boolean == 1: 20 | session = arg 21 | boolean = 0 22 | if arg == "-i": 23 | boolean = 1 24 | if arg == "-s": 25 | boolean2 = 1 26 | if boolean1 == 1: 27 | access = arg 28 | boolean1 = 0 29 | if arg == "-a": 30 | boolean1 = 1 31 | if boolean == 0: 32 | session = db2.newIdSession(1) 33 | if scontext != "" and access != "" and session > 0: 34 | db2.SpecificAccessForScontext(session, access, scontext) 35 | elif access != "" and session > 0: 36 | db2.SpecificAccess(session, access) 37 | else: 38 | print "syntaxe : -i id -a access ou -i id -a access -s scontext" 39 | -------------------------------------------------------------------------------- /printAnalyze/printdumpsession.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from db2interface import * 3 | 4 | 5 | if __name__ == "__main__": 6 | 7 | dbconfig=dbconfig() 8 | db2 = dbinterface(dbconfig) 9 | session = 0 10 | boolean = 0 11 | for arg in sys.argv: 12 | if boolean == 1: 13 | session = arg 14 | boolean = 0 15 | if arg == "-i": 16 | boolean = 1 17 | if boolean == 0: 18 | session = db2.newIdSession(1) 19 | 20 | if session > 0: 21 | db2.dumpSession(session) 22 | -------------------------------------------------------------------------------- /printAnalyze/printid.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from db2interface import * 3 | 4 | 5 | if __name__ == "__main__": 6 | 7 | dbconfig=dbconfig() 8 | db2 = dbinterface(dbconfig) 9 | session = db2.newIdSession(0) 10 | -------------------------------------------------------------------------------- /printAnalyze/printload.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from db2interface import * 3 | if __name__ == "__main__": 4 | 5 | dbconfig=dbconfig() 6 | db2 = dbinterface(dbconfig) 7 | boolean = 0 8 | boolean1 = 0 9 | boolean2 = 0 10 | session = 0 11 | scontext = "" 12 | tcontext = "" 13 | for arg in sys.argv: 14 | if boolean == 1: 15 | session = arg 16 | boolean = 0 17 | if arg == "-i": 18 | boolean = 1 19 | if boolean1 == 1: 20 | scontext = arg 21 | boolean1 = 0 22 | if arg == "-s": 23 | boolean1 = 1 24 | if arg == "-all": 25 | boolean2= 1 26 | if boolean == 0: 27 | session = db2.newIdSession(1) 28 | if scontext != "" and session > 0 and boolean2 == 0: 29 | db2.LoadForContext(session, scontext) 30 | elif session > 0 and boolean2 == 1: 31 | db2.LoadAll(session) 32 | else: 33 | print "syntaxe : -i id -s scontext ou -all " 34 | -------------------------------------------------------------------------------- /printAnalyze/printres.py: -------------------------------------------------------------------------------- 1 | import sys 2 | /bin/bash: q: command not found 3 | 4 | 5 | if __name__ == "__main__": 6 | 7 | dbconfig=dbconfig() 8 | db2 = dbinterface(dbconfig) 9 | 10 | session = db2.newIdSession(1) 11 | db2.dumpIPSession(session) 12 | db2.dumpIPScontext(session, "system_u:system_r:firefox_t") 13 | print("OKKKKKK") 14 | -------------------------------------------------------------------------------- /printAnalyze/printreseau.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from db2interface import * 3 | 4 | 5 | if __name__ == "__main__": 6 | 7 | dbconfig=dbconfig() 8 | db2 = dbinterface(dbconfig) 9 | boolean = 0 10 | boolean1 = 0 11 | boolean2 = 0 12 | session = 0 13 | proto = "" 14 | scontext = "" 15 | for arg in sys.argv: 16 | if boolean2 == 1: 17 | scontext = arg 18 | boolean2 = 0 19 | if boolean == 1: 20 | session = arg 21 | boolean = 0 22 | if arg == "-i": 23 | boolean = 1 24 | if arg == "-s": 25 | boolean2 = 1 26 | if boolean1 == 1: 27 | proto = arg 28 | boolean1 = 0 29 | if arg == "-p": 30 | boolean1 = 1 31 | if boolean == 0: 32 | session = db2.newIdSession(1) 33 | 34 | if scontext == "" and proto == "" and session > 0: 35 | db2.dumpIPSession(session) 36 | elif scontext != "" and proto == "" and session > 0: 37 | db2.dumpIPScontext(session, scontext) 38 | elif scontext == "" and proto != "" and session > 0: 39 | db2.dumpIPProto(session, proto) 40 | elif scontext != "" and proto != "" and session > 0: 41 | db2.dumpIPAccess(session, scontext,proto) 42 | else: 43 | print "syntaxe : -i id -p protocol ou -i id -a access -s scontext ou -i id ou -i id -p protocol -s scontext" 44 | -------------------------------------------------------------------------------- /printAnalyze/printscontext.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from db2interface import * 3 | 4 | 5 | if __name__ == "__main__": 6 | 7 | dbconfig=dbconfig() 8 | db2 = dbinterface(dbconfig) 9 | boolean = 0 10 | for arg in sys.argv: 11 | if arg == "-i": 12 | boolean = 1 13 | if boolean == 1: 14 | session = arg 15 | 16 | if boolean == 0: 17 | session = db2.newIdSession(1) 18 | db2.dumpSContextSession(session) 19 | 20 | -------------------------------------------------------------------------------- /printAnalyze/printscontextassociated.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from db2interface import * 3 | 4 | 5 | if __name__ == "__main__": 6 | 7 | dbconfig=dbconfig() 8 | db2 = dbinterface(dbconfig) 9 | boolean = 0 10 | boolean1 = 0 11 | session = 0 12 | scontext = "" 13 | for arg in sys.argv: 14 | if boolean == 1: 15 | session = arg 16 | boolean = 0 17 | if arg == "-i": 18 | boolean = 1 19 | if boolean1 == 1: 20 | scontext = arg 21 | boolean1 = 0 22 | if arg == "-s": 23 | boolean1= 1 24 | if boolean == 0: 25 | session = db2.newIdSession(1) 26 | 27 | if scontext != "" and session > 0: 28 | db2.TContextForSContext(session, scontext) 29 | else: 30 | print "syntaxe : -i id -s scontext" 31 | -------------------------------------------------------------------------------- /printAnalyze/printtcontext.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from db2interface import * 3 | 4 | if __name__ == "__main__": 5 | 6 | dbconfig=dbconfig() 7 | db2 = dbinterface(dbconfig) 8 | boolean = 0 9 | for arg in sys.argv: 10 | if arg == "-i": 11 | boolean = 1 12 | if boolean == 1: 13 | session = arg 14 | 15 | if boolean == 0: 16 | session = db2.newIdSession(1) 17 | db2.dumpTContextSession(session) 18 | -------------------------------------------------------------------------------- /printAnalyze/printtcontextassociated.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from db2interface import * 3 | 4 | 5 | if __name__ == "__main__": 6 | 7 | dbconfig=dbconfig() 8 | db2 = dbinterface(dbconfig) 9 | boolean = 0 10 | boolean1 = 0 11 | session = 0 12 | tcontext = "" 13 | for arg in sys.argv: 14 | if boolean == 1: 15 | session = arg 16 | boolean = 0 17 | if arg == "-i": 18 | boolean = 1 19 | if boolean1 == 1: 20 | tcontext = arg 21 | boolean1 = 0 22 | if arg == "-t": 23 | boolean1= 1 24 | 25 | if boolean == 0: 26 | session = db2.newIdSession(1) 27 | if tcontext != "" and session > 0: 28 | db2.SContextForTContext(session, tcontext) 29 | else: 30 | print "syntaxe : -i id -t tcontext" 31 | -------------------------------------------------------------------------------- /printAnalyze/server.py: -------------------------------------------------------------------------------- 1 | import SocketServer 2 | from line import readTrace 3 | from lineThread import lineThread 4 | from Queue import * 5 | import threading 6 | import logging 7 | from db2interface import * 8 | import threading 9 | 10 | class dataChunk(): 11 | __data = "" 12 | __idsession = 0 13 | 14 | def __init__(self, data, idsession): 15 | self.__data = data 16 | self.__idsession = idsession 17 | 18 | def getData(self): 19 | return self.__data 20 | 21 | def getSession(self): 22 | return self.__idsession 23 | 24 | class traceServer(SocketServer.BaseRequestHandler): 25 | 26 | def settoRead(qu): 27 | self.__toRead = qu 28 | 29 | def setLog(log): 30 | self.__log = log 31 | 32 | def handle(self): 33 | rest = "" 34 | idsession = self.server.getDB().newIdSession() 35 | while 1: 36 | self.data = self.request.recv(5096).strip() 37 | if not self.data: 38 | print("Connexion Error !!!!!!!!!!!!!!") 39 | self.data = self.request.recv(5096).strip() 40 | if not self.data: 41 | print("Connexion CLOSED !!!!!!!!!!!!") 42 | break 43 | dc = dataChunk(self.data, idsession) 44 | self.server.getQueue().put(dc) 45 | 46 | class traceServerTCP(SocketServer.TCPServer): 47 | 48 | def setQueue(self,qu): 49 | self.toRead = qu 50 | 51 | def getQueue(self): 52 | return self.toRead 53 | 54 | def setDB(self, db): 55 | self.db2 = db 56 | 57 | def getDB(self): 58 | return self.db2 59 | 60 | class traceServerThread(threading.Thread): 61 | def __init__(self, toRead, logging, db2): 62 | threading.Thread.__init__(self) 63 | self.Terminated = False 64 | self.server = traceServerTCP((HOST, PORT), traceServer) 65 | self.server.setQueue(toRead) 66 | self.server.setDB(db2) 67 | self.__log = logging 68 | 69 | def run(self): 70 | self.__log.debug("traceServerThread: run") 71 | while not self.Terminated: 72 | self.server.serve_forever() 73 | 74 | def stop(self): 75 | self.Terminated = True 76 | 77 | if __name__ == "__main__": 78 | HOST, PORT = "172.30.3.57", 9998 79 | 80 | LOG_FILENAME = "/home/db2inst1/traceAnalyzer.log" 81 | logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) 82 | 83 | toRead = Queue() 84 | 85 | dbconfig = dbconfig() 86 | 87 | dblock = threading.Lock() 88 | 89 | db2 = dbinterface(dbconfig, logging, dblock) 90 | 91 | trThread = traceServerThread(toRead,logging, db2) 92 | trThread.daemon = True 93 | trThread.start() 94 | 95 | lineT = lineThread(toRead, logging,db2) 96 | lineT.daemon = True 97 | lineT.start() 98 | lineT.join() 99 | 100 | -------------------------------------------------------------------------------- /savePost/client_test.py: -------------------------------------------------------------------------------- 1 | from xml.dom.minidom import parse, parseString 2 | import re 3 | 4 | trace = u"\n" 5 | trace = trace +u"\n" 6 | trace = trace +u"\n" 7 | trace = trace +u"\n" 8 | #trace = trace +"\n" 9 | #trace = trace +"\n" 10 | # 11 | trace = trace +u"\n" 12 | 13 | #trace = trace.decode("latin1","replace") 14 | 15 | trace = trace.replace("&", "&") 16 | 17 | print(trace.decode("utf8")) 18 | #try: 19 | dom = parseString(trace.decode("utf8")) 20 | #except: 21 | # print("Error ??") 22 | 23 | for node in dom.getElementsByTagName("trace"): 24 | print("ID="+node.getAttribute("id")) 25 | 26 | -------------------------------------------------------------------------------- /savePost/db2interface.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import DB2 3 | from datetime import date, datetime, timedelta 4 | 5 | class dbconfig: 6 | database = 'framecea' # Database to connect to. Please use an empty database for best results. 7 | user = 'db2inst1' # User ID to connect with 8 | password = 'db2011' # Password for given User ID 9 | hostname = 'localhost' # Hostname 10 | port = 60000 # Port Number 11 | 12 | class dbinterface: 13 | 14 | __idalarm = 0 15 | __idurlnext = 0 16 | 17 | def __init__(self, dbconfig, logging, dblock): 18 | self.dbconfig = dbconfig 19 | self.log = logging 20 | self.dblock = dblock 21 | 22 | self.conn = DB2.connect (dsn = self.dbconfig.database, uid = self.dbconfig.user, pwd = self.dbconfig.password) 23 | 24 | self.create_table() 25 | 26 | self.cpt = 0 27 | 28 | 29 | def create_table(self): 30 | # try: 31 | cursor = self.conn.cursor() 32 | 33 | 34 | sessionExist = "SELECT NAME FROM SYSIBM.SYSTABLES WHERE NAME='SESSION'" 35 | sessionTable = "create table session (idsession integer GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) primary key, samplename varchar(256), ostype varchar(256))" 36 | traceExist = "SELECT NAME FROM SYSIBM.SYSTABLES WHERE NAME='TRACE'" 37 | #traceTable = "create table trace (id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return varchar(200), pid int, ppid int, scontext CLOB(10K), nameSubject CLOB(10K), nameObject CLOB(10K), tcontext CLOB(10K), perms varchar(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 38 | traceTable = "create table trace (id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return varchar(200), pid int, ppid int, scontext VARCHAR(4096), nameSubject VARCHAR(4096), nameObject VARCHAR(4096), tcontext VARCHAR(4096), perms varchar(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 39 | traceIndex_1 = "CREATE INDEX IDX_TRACE_SCONTEXT ON TRACE ( SCONTEXT )" 40 | traceIndex_2 = "CREATE INDEX IDX_TRACE_TCONTEXT ON TRACE ( TCONTEXT )" 41 | traceIndex_3 = "CREATE INDEX IDX_TRACE_TYPE ON TRACE ( TYPE )" 42 | traceIndex_4 = "CREATE INDEX IDX_TRACE_PERMS ON TRACE ( PERMS )" 43 | traceIndex_5 = "CREATE INDEX IDX_TRACE_IDSESSION ON TRACE ( IDSESSION )" 44 | 45 | traceNetExist = "SELECT NAME FROM SYSIBM.SYSTABLES WHERE NAME='TRACENET'" 46 | #traceNetTable = "create table tracenet (id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return varchar(200), pid int, ppid int, scontext CLOB(10K), nameSubject CLOB(10K), ipSource VARCHAR(256), PortSource INT, ipDest VARCHAR(256), PortDest INT, state VARCHAR(256), typeconnect VARCHAR(256), netsize INT, proto VARCHAR(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 47 | traceNetTable = "create table tracenet (id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return varchar(200), pid int, ppid int, scontext VARCHAR(4096), nameSubject VARCHAR(4096), ipSource VARCHAR(256), PortSource INT, ipDest VARCHAR(256), PortDest INT, state VARCHAR(256), typeconnect VARCHAR(256), netsize INT, proto VARCHAR(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 48 | traceNetIndex_1 = "CREATE INDEX IDX_TRACE_IDSESSION ON TRACENET ( IDSESSION )" 49 | traceNetIndex_2 = "CREATE INDEX IDX_TRACENET_SCONTEXT ON TRACENET ( SCONTEXT )" 50 | traceNetIndex_3 = "CREATE INDEX IDX_TRACENET_PROTO ON TRACENET ( PROTO )" 51 | 52 | cursor.execute(sessionExist) 53 | 54 | rows = cursor.fetchall() 55 | cpt = 0 56 | for row in rows: 57 | cpt = cpt + 1 58 | 59 | if cpt == 0: 60 | self.log.debug("create session table") 61 | cursor.execute(sessionTable) 62 | 63 | cursor.execute(traceExist) 64 | 65 | rows = cursor.fetchall() 66 | cpt = 0 67 | for row in rows: 68 | cpt = cpt + 1 69 | 70 | if cpt == 0: 71 | self.log.debug("create trace table") 72 | cursor.execute(traceTable) 73 | cursor.execute(traceIndex_1) 74 | cursor.execute(traceIndex_2) 75 | cursor.execute(traceIndex_3) 76 | cursor.execute(traceIndex_4) 77 | cursor.execute(traceIndex_5) 78 | 79 | 80 | cursor.execute(traceNetExist) 81 | 82 | rows = cursor.fetchall() 83 | cpt = 0 84 | for row in rows: 85 | cpt = cpt + 1 86 | 87 | if cpt == 0: 88 | self.log.debug("create tracenet table") 89 | cursor.execute(traceNetTable) 90 | cursor.execute(traceNetIndex_1) 91 | cursor.execute(traceNetIndex_2) 92 | cursor.execute(traceNetIndex_3) 93 | 94 | self.conn.commit() 95 | cursor.close() 96 | # except: 97 | # self.log.error("DBInterface: Something crash during createTable !") 98 | 99 | def newIdSession(self): 100 | request = "SELECT MAX(idsession) FROM session" 101 | insertLine = "INSERT INTO session(samplename,ostype) VALUES(' ',' ')" 102 | 103 | cursor = self.conn.cursor() 104 | 105 | self.dblock.acquire() 106 | 107 | cursor.execute(insertLine) 108 | 109 | cursor.execute(request.encode("utf-8","replace")) 110 | 111 | row = cursor.fetchone() 112 | sessionMax = row[0] 113 | 114 | #self.log.debug("Session Max ID: "+str(sessionMax)) 115 | 116 | self.conn.commit() 117 | 118 | self.dblock.release() 119 | 120 | cursor.close() 121 | 122 | return sessionMax 123 | 124 | 125 | #(id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return integer, pid int, ppid int, scontext varchar(256), nameSubject CLOB(10K), nameObject CLOB(10K), tcontext varchar(256), perms varchar(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 126 | def insert(self, id, idsession, ts, type, ret, pid, ppid, scontext, nameSubject, nameObject, tcontext, perms, data): 127 | try: 128 | tsp = datetime(1601, 1, 1) + timedelta(microseconds=int(ts)/10) 129 | request = "INSERT INTO trace(id,idsession,tstamp,type,return,pid,ppid,scontext,nameSubject,nameObject,tcontext,perms,data) VALUES("+str(id)+"," 130 | request = request+str(idsession)+",'" 131 | request = request+DB2.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second, tsp.microsecond).get_SQL_value()+"','" 132 | request = request+str(type)+"','"+str(ret)+"',"+str(pid)+","+str(ppid)+",'" 133 | request = request+scontext.replace("'","''")+"','" 134 | request = request+nameSubject.replace("'","''")+"','" 135 | request = request+nameObject.replace("'","''")+"','" 136 | request = request+tcontext.replace("'","''")+"','" 137 | request = request+perms+"','" 138 | request = request+data.replace("'","''")+"')" 139 | except: 140 | self.log.debug("db2interface:insertNet:"+request) 141 | return 142 | #self.log.debug("InsertLine: "+request) 143 | cursor = self.conn.cursor() 144 | try: 145 | request = request.decode("unicode","replace") 146 | except: 147 | try: 148 | request = request.encode('ascii', 'xmlcharrefreplace') 149 | #request.encode("utf8") 150 | except: 151 | request = "%s" % request 152 | try: 153 | try: 154 | request = request.encode("utf8") 155 | except: 156 | print("Error encoding UTF8") 157 | cursor.execute(request) 158 | except: 159 | print("Error DB2: "+request) 160 | request = request.encode('ascii', 'xmlcharrefreplace') 161 | try: 162 | cursor.execute(request) 163 | except: 164 | print("Error DB2 ASCII: "+request) 165 | 166 | if self.cpt == 1000: 167 | self.conn.commit() 168 | self.cpt = 0 169 | else: 170 | self.cpt = self.cpt + 1 171 | 172 | # self.conn.commit() 173 | cursor.close() 174 | return 1 175 | 176 | def insertNet(self, id, idsession, ts, type, ret, pid, ppid, scontext, nameSubject, ipsource, portsource, ipdest, portdest, state, typeconnect, netsize, proto, data): 177 | try: 178 | tsp = datetime(1601, 1, 1) + timedelta(microseconds=int(ts)/10) 179 | request = "INSERT INTO tracenet(id,idsession,tstamp,type,return,pid,ppid,scontext,nameSubject,ipSource,PortSource,ipDest,PortDest,state,typeconnect,netsize,proto,data) VALUES("+str(id)+"," 180 | request = request+str(idsession)+",'" 181 | request = request+DB2.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second, tsp.microsecond).get_SQL_value()+"','" 182 | request = request+str(type)+"','"+str(ret)+"',"+str(pid)+","+str(ppid)+",'" 183 | request = request+scontext.replace("'","''")+"','" 184 | request = request+nameSubject.replace("'","''")+"','" 185 | request = request+ipsource+"',"+portsource+",'" 186 | request = request+ipdest+"',"+portdest+",'" 187 | request = request+state+"','"+typeconnect+"',"+netsize+",'"+proto+"','" 188 | request = request+data.replace("'","''")+"')" 189 | except: 190 | self.log.debug("db2interface:insertNet:"+request) 191 | return 192 | #self.log.debug("InsertLine: "+request) 193 | cursor = self.conn.cursor() 194 | try: 195 | request = request.decode("unicode","replace") 196 | except: 197 | try: 198 | request = request.encode('ascii', 'xmlcharrefreplace') 199 | #request.encode("utf8") 200 | except: 201 | request = "%s" % request 202 | try: 203 | try: 204 | request = request.encode("utf8") 205 | except: 206 | print("Error encoding UTF8") 207 | cursor.execute(request) 208 | except: 209 | print("Error DB2: "+request) 210 | request = request.encode('ascii', 'xmlcharrefreplace') 211 | try: 212 | cursor.execute(request) 213 | except: 214 | print("Error DB2 ASCII: "+request) 215 | 216 | if self.cpt == 1000: 217 | self.conn.commit() 218 | self.cpt = 0 219 | else: 220 | self.cpt = self.cpt + 1 221 | 222 | # self.conn.commit() 223 | cursor.close() 224 | return 1 225 | -------------------------------------------------------------------------------- /savePost/line.py: -------------------------------------------------------------------------------- 1 | import re 2 | from xmlParser import parseTrace 3 | class readTrace: 4 | 5 | __file = "" 6 | __pattern_start="" 7 | __pattern_end="" 8 | __pattern_complete = ".*.*" 9 | 10 | def __init__(self, data, logging, dbinterface, rest): 11 | self.__log = logging 12 | if rest[-1:] == "\"": 13 | self.__log.debug("Found a missing space") 14 | rest = rest + " " 15 | if rest[-8:] == " 0: 26 | if i == 1000: 27 | self.__log.debug("Queue size: "+str(self.__toRead.qsize())) 28 | i=0 29 | else: 30 | i = i + 1 31 | rt = readTrace(self.__toRead.get(), self.__log, self.__dbinterface, rest) 32 | rest = rt.compute() 33 | #self.__log.debug("Rest: "+rest) 34 | #self.__log.debug("lineThread: sleep") 35 | time.sleep(2.0) 36 | 37 | def stop(self): 38 | self.Terminated = True -------------------------------------------------------------------------------- /savePost/lineThread.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/savePost/lineThread.pyc -------------------------------------------------------------------------------- /savePost/pginterface.py: -------------------------------------------------------------------------------- 1 | # PG Interface 2 | 3 | import logging 4 | import postgresql.driver.dbapi20 as pg 5 | 6 | from datetime import date, datetime, timedelta 7 | 8 | class dbconfig: 9 | database = 'framecea' # Database to connect to. Please use an empty database for best results. 10 | user = 'postgres' # User ID to connect with 11 | password = 'db2011' # Password for given User ID 12 | hostname = 'localhost' # Hostname 13 | port = 5432 # Port Number 14 | 15 | class dbinterface: 16 | 17 | __idalarm = 0 18 | __idurlnext = 0 19 | 20 | def __init__(self, dbconfig, logging, dblock): 21 | self.dbconfig = dbconfig 22 | self.log = logging 23 | self.dblock = dblock 24 | 25 | # self.conn = DB2.connect (dsn = self.dbconfig.database, uid = self.dbconfig.user, pwd = self.dbconfig.password) 26 | self.conn = pg.connect (database = self.dbconfig.database, user = self.dbconfig.user, password = self.dbconfig.password, host =self.dbconfig.hostname, port=self.dbconfig.port) 27 | 28 | #self.conn = pg.connect(database = 'framecea', user = 'postgres', password = 'db2011', host= '127.0.0.1', port = 5432) 29 | #self.create_table() 30 | 31 | self.cpt = 0 32 | 33 | 34 | def create_table(self): 35 | # try: 36 | cursor = self.conn.cursor() 37 | 38 | cursor.close() 39 | # except: 40 | # self.log.error("DBInterface: Something crash during createTable !") 41 | 42 | def newIdSession(self): 43 | request = "SELECT MAX(idsession) FROM session" 44 | insertLine = "INSERT INTO session(samplename,ostype) VALUES(' ',' ')" 45 | 46 | cursor = self.conn.cursor() 47 | 48 | self.dblock.acquire() 49 | 50 | cursor.execute(insertLine) 51 | 52 | cursor.execute(request) 53 | 54 | row = cursor.fetchone() 55 | sessionMax = row[0] 56 | 57 | #self.log.debug("Session Max ID: "+str(sessionMax)) 58 | 59 | self.conn.commit() 60 | 61 | self.dblock.release() 62 | 63 | cursor.close() 64 | 65 | return sessionMax 66 | 67 | 68 | #(id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return integer, pid int, ppid int, scontext varchar(256), nameSubject CLOB(10K), nameObject CLOB(10K), tcontext varchar(256), perms varchar(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 69 | def insert(self, id, idsession, ts, type, ret, pid, ppid, scontext, nameSubject, nameObject, tcontext, perms, data): 70 | try: 71 | tsp = datetime(1601, 1, 1) + timedelta(microseconds=int(ts)/10) 72 | request = "INSERT INTO trace(id,idsession,tstamp,type,return,pid,ppid,scontext,nameSubject,nameObject,tcontext,perms,data) VALUES("+str(id)+"," 73 | request = request+str(idsession)+",'" 74 | request = request+"0,0,0,0,0,0,0," #DB2.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second, tsp.microsecond).get_SQL_value()+"','" 75 | #request = request+pg.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second, tsp.microsecond).get_SQL_value()+"','" 76 | request = request+str(type)+"','"+str(ret)+"',"+str(pid)+","+str(ppid)+",'" 77 | request = request+scontext.replace("'","''")+"','" 78 | request = request+nameSubject.replace("'","''")+"','" 79 | request = request+nameObject.replace("'","''")+"','" 80 | request = request+tcontext.replace("'","''")+"','" 81 | request = request+perms+"','" 82 | request = request+data.replace("'","''")+"')" 83 | except: 84 | self.log.debug("db2interface:insertNet:"+request) 85 | return 86 | self.log.debug("InsertLine: "+request) 87 | cursor = self.conn.cursor() 88 | try: 89 | request = request.decode("unicode","replace") 90 | except: 91 | try: 92 | request = request.encode('ascii', 'xmlcharrefreplace') 93 | #request.encode("utf8") 94 | except: 95 | request = "%s" % request 96 | try: 97 | try: 98 | request = request.encode("utf8") 99 | except: 100 | print("Error encoding UTF8") 101 | cursor.execute(request) 102 | except: 103 | print("Error DB2: "+request) 104 | request = request.encode('ascii', 'xmlcharrefreplace') 105 | try: 106 | cursor.execute(request) 107 | except: 108 | print("Error DB2 ASCII: "+request) 109 | 110 | if self.cpt == 1: 111 | self.conn.commit() 112 | self.cpt = 0 113 | else: 114 | self.cpt = self.cpt + 1 115 | 116 | # self.conn.commit() 117 | cursor.close() 118 | return 1 119 | 120 | def insertNet(self, id, idsession, ts, type, ret, pid, ppid, scontext, nameSubject, ipsource, portsource, ipdest, portdest, state, typeconnect, netsize, proto, data): 121 | try: 122 | tsp = datetime(1601, 1, 1) + timedelta(microseconds=int(ts)/10) 123 | request = "INSERT INTO tracenet(id,idsession,tstamp,type,return,pid,ppid,scontext,nameSubject,ipSource,PortSource,ipDest,PortDest,state,typeconnect,netsize,proto,data) VALUES("+str(id)+"," 124 | request = request+str(idsession)+",'" 125 | request = request+"0,0,0,0,0,0,0," #DB2.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second, tsp.microsecond).get_SQL_value()+"','" 126 | request = request+str(type)+"','"+str(ret)+"',"+str(pid)+","+str(ppid)+",'" 127 | request = request+scontext.replace("'","''")+"','" 128 | request = request+nameSubject.replace("'","''")+"','" 129 | request = request+ipsource+"',"+portsource+",'" 130 | request = request+ipdest+"',"+portdest+",'" 131 | request = request+state+"','"+typeconnect+"',"+netsize+",'"+proto+"','" 132 | request = request+data.replace("'","''")+"')" 133 | except: 134 | self.log.debug("db2interface:insertNet:"+request) 135 | return 136 | #self.log.debug("InsertLine: "+request) 137 | cursor = self.conn.cursor() 138 | try: 139 | request = request.decode("unicode","replace") 140 | except: 141 | try: 142 | request = request.encode('ascii', 'xmlcharrefreplace') 143 | #request.encode("utf8") 144 | except: 145 | request = "%s" % request 146 | try: 147 | try: 148 | request = request.encode("utf8") 149 | except: 150 | print("Error encoding UTF8") 151 | cursor.execute(request) 152 | except: 153 | print("Error DB2: "+request) 154 | request = request.encode('ascii', 'xmlcharrefreplace') 155 | try: 156 | cursor.execute(request) 157 | except: 158 | print("Error DB2 ASCII: "+request) 159 | 160 | if self.cpt == 1000: 161 | self.conn.commit() 162 | self.cpt = 0 163 | else: 164 | self.cpt = self.cpt + 1 165 | 166 | # self.conn.commit() 167 | cursor.close() 168 | return 1 169 | 170 | -------------------------------------------------------------------------------- /savePost/pginterface.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/savePost/pginterface.pyc -------------------------------------------------------------------------------- /savePost/server.py: -------------------------------------------------------------------------------- 1 | import socketserver as SocketServer 2 | from line import readTrace 3 | from lineThread import lineThread 4 | from queue import * 5 | import threading 6 | import logging 7 | from pginterface import * 8 | import threading 9 | 10 | class dataChunk(): 11 | __data = "" 12 | __idsession = 0 13 | 14 | def __init__(self, data, idsession): 15 | self.__data = data 16 | self.__idsession = idsession 17 | 18 | def getData(self): 19 | return self.__data 20 | 21 | def getSession(self): 22 | return self.__idsession 23 | 24 | class traceServer(SocketServer.BaseRequestHandler): 25 | 26 | def settoRead(qu): 27 | self.__toRead = qu 28 | 29 | def setLog(log): 30 | self.__log = log 31 | 32 | def handle(self): 33 | rest = "" 34 | idsession = self.server.getDB().newIdSession() 35 | while 1: 36 | self.data = self.request.recv(5096).strip() 37 | if not self.data: 38 | print("Connexion Error !!!!!!!!!!!!!!") 39 | self.data = self.request.recv(5096).strip() 40 | if not self.data: 41 | print("Connexion CLOSED !!!!!!!!!!!!") 42 | break 43 | dc = dataChunk(self.data, idsession) 44 | self.server.getQueue().put(dc) 45 | 46 | class traceServerTCP(SocketServer.TCPServer): 47 | 48 | def setQueue(self,qu): 49 | self.toRead = qu 50 | 51 | def getQueue(self): 52 | return self.toRead 53 | 54 | def setDB(self, db): 55 | self.db2 = db 56 | 57 | def getDB(self): 58 | return self.db2 59 | 60 | class traceServerThread(threading.Thread): 61 | def __init__(self, toRead, logging, db2): 62 | threading.Thread.__init__(self) 63 | self.Terminated = False 64 | self.server = traceServerTCP((HOST, PORT), traceServer) 65 | self.server.setQueue(toRead) 66 | self.server.setDB(db2) 67 | self.__log = logging 68 | 69 | def run(self): 70 | self.__log.debug("traceServerThread: run") 71 | while not self.Terminated: 72 | self.server.serve_forever() 73 | 74 | def stop(self): 75 | self.Terminated = True 76 | 77 | if __name__ == "__main__": 78 | HOST, PORT = "192.168.99.50", 9998 79 | 80 | LOG_FILENAME = "/home/damien/traceAnalyzer.log" 81 | logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) 82 | 83 | toRead = Queue() 84 | 85 | dbconfig = dbconfig() 86 | 87 | dblock = threading.Lock() 88 | 89 | db2 = dbinterface(dbconfig, logging, dblock) 90 | 91 | trThread = traceServerThread(toRead,logging, db2) 92 | trThread.daemon = True 93 | trThread.start() 94 | 95 | lineT = lineThread(toRead, logging,db2) 96 | lineT.daemon = True 97 | lineT.start() 98 | lineT.join() 99 | 100 | -------------------------------------------------------------------------------- /savePost/xmlParser.py: -------------------------------------------------------------------------------- 1 | from xml.dom.minidom import parse, parseString 2 | 3 | class parseTrace(): 4 | 5 | __crash = False 6 | 7 | def __init__(self, trace, idsession, logging, dbinterface): 8 | self.__log = logging 9 | try: 10 | self.__dom = parseString(trace.encode( "utf-8" )) 11 | except: 12 | self.__log.error("parseTrace: Parsing Error") 13 | self.__log.error("parseTrace: Error "+trace) 14 | self.__crash = True 15 | pass 16 | self.__dbinterface = dbinterface 17 | self.__idsession = idsession 18 | 19 | 20 | def getID(self): 21 | for node in self.__dom.getElementsByTagName("trace"): 22 | return node.getAttribute("id") 23 | 24 | def getTS(self): 25 | for node in self.__dom.getElementsByTagName("trace"): 26 | return node.getAttribute("timestamp") 27 | 28 | def getType(self): 29 | for node in self.__dom.getElementsByTagName("trace"): 30 | for node2 in node.getElementsByTagName("class"): 31 | return node2.getAttribute("type") 32 | 33 | def getReturn(self): 34 | for node in self.__dom.getElementsByTagName("trace"): 35 | for node2 in node.getElementsByTagName("class"): 36 | return node2.getAttribute("return") 37 | 38 | def getPID(self): 39 | for node in self.__dom.getElementsByTagName("trace"): 40 | for node2 in node.getElementsByTagName("process"): 41 | return node2.getAttribute("pid") 42 | 43 | def getPPID(self): 44 | for node in self.__dom.getElementsByTagName("trace"): 45 | for node2 in node.getElementsByTagName("process"): 46 | return node2.getAttribute("ppid") 47 | 48 | def getSContext(self): 49 | for node in self.__dom.getElementsByTagName("trace"): 50 | for node2 in node.getElementsByTagName("process"): 51 | return node2.getAttribute("scontext") 52 | 53 | def getNameSubject(self): 54 | for node in self.__dom.getElementsByTagName("trace"): 55 | for node2 in node.getElementsByTagName("process"): 56 | return node2.getAttribute("name") 57 | 58 | def getNameObject(self): 59 | for node in self.__dom.getElementsByTagName("trace"): 60 | for node2 in node.getElementsByTagName("object"): 61 | return node2.getAttribute("name") 62 | 63 | def getTContext(self): 64 | for node in self.__dom.getElementsByTagName("trace"): 65 | for node2 in node.getElementsByTagName("object"): 66 | return node2.getAttribute("tcontext") 67 | 68 | def getPerms(self): 69 | for node in self.__dom.getElementsByTagName("trace"): 70 | for node2 in node.getElementsByTagName("object"): 71 | return node2.getAttribute("rights") 72 | 73 | def getIPSrc(self): 74 | for node in self.__dom.getElementsByTagName("trace"): 75 | for node2 in node.getElementsByTagName("ip"): 76 | return node2.getAttribute("ipsource") 77 | 78 | def getPortSrc(self): 79 | for node in self.__dom.getElementsByTagName("trace"): 80 | for node2 in node.getElementsByTagName("ip"): 81 | return node2.getAttribute("portsource") 82 | 83 | def getIPDest(self): 84 | for node in self.__dom.getElementsByTagName("trace"): 85 | for node2 in node.getElementsByTagName("ip"): 86 | return node2.getAttribute("ipdest") 87 | 88 | def getPortDest(self): 89 | for node in self.__dom.getElementsByTagName("trace"): 90 | for node2 in node.getElementsByTagName("ip"): 91 | return node2.getAttribute("portdest") 92 | 93 | def getState(self): 94 | for node in self.__dom.getElementsByTagName("trace"): 95 | for node2 in node.getElementsByTagName("ip"): 96 | return node2.getAttribute("state") 97 | 98 | def getTypeConnect(self): 99 | for node in self.__dom.getElementsByTagName("trace"): 100 | for node2 in node.getElementsByTagName("ip"): 101 | return node2.getAttribute("typeconnect") 102 | 103 | def getIPSize(self): 104 | for node in self.__dom.getElementsByTagName("trace"): 105 | for node2 in node.getElementsByTagName("ip"): 106 | return node2.getAttribute("size") 107 | 108 | def getIPProto(self): 109 | for node in self.__dom.getElementsByTagName("trace"): 110 | for node2 in node.getElementsByTagName("ip"): 111 | return node2.getAttribute("prot") 112 | 113 | 114 | def getData(self): 115 | for node in self.__dom.getElementsByTagName("trace"): 116 | if node.getElementsByTagName("data")[0]: 117 | return " " 118 | else: 119 | return node.getElementsByTagName("data")[0] 120 | 121 | def isNetWork(self): 122 | if self.getType() == "network": 123 | return True 124 | else: 125 | return False 126 | 127 | 128 | 129 | 130 | def generateSQL(self): 131 | return (self.getID(), self.__idsession, self.getTS(), self.getType(), self.getReturn(), self.getPID(), self.getPPID(), self.getSContext(), self.getNameSubject(), self.getNameObject(), self.getTContext(), self.getPerms(), self.getData()) 132 | 133 | def isCrash(self): 134 | return self.__crash 135 | 136 | def generateString(self): 137 | return str(self.getID())+" "+str(self.__idsession)+" "+str(self.getTS())+" "+str(self.getType())+" "+str(self.getReturn())+" "+str(self.getPID())+" "+str(self.getPPID())+" "+str(self.getSContext())+" "+str(self.getNameSubject())+" "+str(self.getNameObject())+" "+str(self.getTContext())+" "+str(self.getPerms())+" "+str(self.getData()) 138 | 139 | def insertTrace(self): 140 | if self.isNetWork(): 141 | self.__dbinterface.insertNet(self.getID(), self.__idsession, self.getTS(), self.getType(), self.getReturn(), self.getPID(), self.getPPID(), self.getSContext(), self.getNameSubject(), self.getIPSrc(), self.getPortSrc(), self.getIPDest(), self.getPortDest(), self.getState(), self.getTypeConnect(), self.getIPSize(), self.getIPProto(), self.getData()) 142 | else: 143 | self.__dbinterface.insert(self.getID(), self.__idsession, self.getTS(), self.getType(), self.getReturn(), self.getPID(), self.getPPID(), self.getSContext(), self.getNameSubject(), self.getNameObject(), self.getTContext(), self.getPerms(), self.getData()) 144 | return 1 145 | 146 | 147 | -------------------------------------------------------------------------------- /savePost/xmlParser.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/savePost/xmlParser.pyc -------------------------------------------------------------------------------- /script.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | rem Script pour recuperer les binaires sur le serveur ftp 3 | 4 | setlocal enabledelayedexpansion 5 | :loop 6 | ping 127.0.0.1 -n 2 -w 1000 > Nul 7 | ping 127.0.0.1 -n %1 -w 1000 > Nul 8 | dir /B \inetpub\ftproot\toto | find "exe" > Nul 9 | if !errorlevel! == 1 goto loop 10 | if !errorlevel! == 0 goto end 11 | 12 | endlocal 13 | 14 | 15 | :end 16 | sc stop ftpsvc 17 | pause 18 | FOR /F "tokens=*" %%i in ('dir /B "\inetpub\ftproot\toto"') do SET TOOLOUTPUT=%%i 19 | start \inetpub\ftproot\toto\%TOOLOUTPUT% 20 | -------------------------------------------------------------------------------- /sys/MAKEFILE: -------------------------------------------------------------------------------- 1 | # 2 | # DO NOT EDIT THIS FILE!!! Edit .\sources. if you want to add a new source 3 | # file to this component. This file merely indirects to the real make file 4 | # that is shared by all the driver components of the Windows NT DDK 5 | # 6 | 7 | !INCLUDE $(NTMAKEENV)\makefile.def 8 | -------------------------------------------------------------------------------- /sys/SOURCES: -------------------------------------------------------------------------------- 1 | TARGETNAME=dkf 2 | TARGETTYPE=DRIVER 3 | 4 | SOURCES= \ 5 | framework.c registry.c createprocess.c file.c network.c -------------------------------------------------------------------------------- /sys/createprocess.c: -------------------------------------------------------------------------------- 1 | #include "driver.h" 2 | 3 | VOID FonctionDeLaMortQuiTueQuiFaitDesBSODEtQueMemeLesLinuxiensNePeuventPasFaireParceQuIlsSontJaloux() 4 | { 5 | PVOID plop=NULL; 6 | 7 | ExFreePool(plop); 8 | 9 | } 10 | 11 | NTSTATUS NewNtCreateSection( 12 | OUT PHANDLE SectionHandle, 13 | IN ULONG DesiredAccess, 14 | IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, 15 | IN PLARGE_INTEGER MaximumSize OPTIONAL, 16 | IN ULONG PageAttributess, 17 | IN ULONG SectionAttributes, 18 | IN HANDLE FileHandle OPTIONAL ) 19 | { 20 | ProcessInformationFile process; 21 | NTSTATUS rc = 0, ntStatus; 22 | PFILE_OBJECT fileObject = NULL; 23 | ANSI_STRING ansi_cible ; 24 | ULONG retLen; 25 | UNICODE_STRING *path_str = NULL; 26 | PPUBLIC_OBJECT_TYPE_INFORMATION publicobj; 27 | int i, j,taille, bool=0; 28 | char temp[500]; 29 | char object_context[600]; 30 | char securitycontext[225]; 31 | 32 | rc = ( (NTCREATESECTION)(*OldNtCreateSection) ) ( 33 | SectionHandle, 34 | DesiredAccess, 35 | ObjectAttributes, 36 | MaximumSize, 37 | PageAttributess, 38 | SectionAttributes, 39 | FileHandle); 40 | 41 | process = GetProcessInfoFile(); 42 | RtlZeroMemory(&securitycontext, sizeof(securitycontext)); 43 | GetSecurityContextSubject(process, securitycontext); 44 | 45 | if((PageAttributess & PAGE_EXECUTE )) 46 | { 47 | if(FileHandle != NULL) 48 | { 49 | ObReferenceObjectByHandle(FileHandle, 0, 0, KernelMode, &fileObject, NULL); 50 | 51 | if (fileObject) 52 | { 53 | ntStatus = ObQueryNameString(fileObject, (POBJECT_NAME_INFORMATION)path_str, 0, &retLen); 54 | path_str = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, retLen, 0); 55 | if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) 56 | { 57 | if (path_str) 58 | { 59 | ntStatus = ObQueryNameString(fileObject, (POBJECT_NAME_INFORMATION)path_str, retLen, &retLen); 60 | 61 | if(!NT_SUCCESS(ntStatus)) 62 | return rc; 63 | } 64 | else 65 | return rc; 66 | } 67 | 68 | RtlUnicodeStringToAnsiString(&ansi_cible, path_str, TRUE); 69 | 70 | RtlZeroMemory(&temp, sizeof(temp)); 71 | RtlZeroMemory(&object_context, sizeof(object_context)); 72 | 73 | // Chargement d'un executable 74 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".exe")], ".exe") == 0 ) 75 | { 76 | TransformToContext(ansi_cible, temp); 77 | sprintf(object_context,"system_u:object_r:%s_exec_t", temp); 78 | bool=1; 79 | } 80 | 81 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".tmp")], ".tmp") == 0 ) 82 | { 83 | TransformToContext(ansi_cible, temp); 84 | sprintf(object_context,"system_u:object_r:%s_tmp_t", temp); 85 | bool=1; 86 | } 87 | 88 | // Chargement d'une DLL 89 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".dll")], ".dll") == 0 ) 90 | { 91 | 92 | TransformToContext(ansi_cible, temp); 93 | sprintf(object_context,"system_u:object_r:%s_lib_t", temp); 94 | bool=1; 95 | } 96 | 97 | 98 | // Chargement d'un driver 99 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".sys")], ".sys") == 0 ) 100 | { 101 | TransformToContext(ansi_cible, temp); 102 | sprintf(object_context,"system_u:object_r:%s_driver_t", temp); 103 | bool=1; 104 | } 105 | if( bool == 0 ) 106 | { 107 | TransformToContext(ansi_cible, temp); 108 | sprintf(object_context,"system_u:object_r:%s_execution_t", temp); 109 | bool=1; 110 | } 111 | if(bool ==1) 112 | { 113 | WriteInLog("execute ", process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "load", rc,0); 114 | } 115 | 116 | if(fileObject) 117 | ObDereferenceObject(fileObject); 118 | if (path_str) 119 | ExFreePoolWithTag(path_str, 0); 120 | RtlFreeAnsiString(&ansi_cible); 121 | 122 | } 123 | } 124 | } 125 | 126 | return rc; 127 | 128 | } 129 | 130 | void TransformToContext(ANSI_STRING ansi, char * context) 131 | { 132 | int taille, i=0, j=0; 133 | 134 | taille = strlen(ansi.Buffer); 135 | i=taille; 136 | 137 | while(i>0) 138 | { 139 | if(ansi.Buffer[i] == '\\') 140 | break; 141 | i--; 142 | } 143 | i++; 144 | j=0; 145 | while(iUniqueProcess == UserLandID) 166 | ntStatus = STATUS_ACCESS_DENIED; 167 | else 168 | { 169 | ntStatus = ((NTOPENPROCESS)(OldNtOpenProcess))( 170 | ProcessHandle, 171 | DesiredAccess, 172 | ObjectAttributes, 173 | ClientId); 174 | } 175 | 176 | return ntStatus; 177 | } 178 | 179 | NTSTATUS NewNtTerminateProcess( 180 | __in_opt HANDLE ProcessHandle, 181 | __in NTSTATUS ExitStatus 182 | ) 183 | { 184 | NTSTATUS ntStatus; 185 | if(ProcessHandle == UserLandID) 186 | ntStatus = STATUS_ACCESS_DENIED; 187 | else 188 | { 189 | ntStatus = ((NTTERMINATEPROCESS)(OldNtTerminateProcess))( 190 | ProcessHandle, 191 | ExitStatus); 192 | } 193 | return ntStatus; 194 | } -------------------------------------------------------------------------------- /sys/driver.h: -------------------------------------------------------------------------------- 1 | #ifndef _DRIVER_ 2 | #define _DRIVER_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "shared.h" 9 | 10 | #define DRIVER_NAME L"DKF" 11 | 12 | #define MUTEX_INIT(v) KeInitializeMutex( &v, 0 ) 13 | #define MUTEX_WAIT(v) KeWaitForMutexObject( &v, Executive, KernelMode, FALSE, NULL ) 14 | #define MUTEX_RELEASE(v) KeReleaseMutex( &v, FALSE ) 15 | 16 | #define FILE_DEVICE_DKF 0x12345678 17 | #define IOCTL_DKF_START (ULONG) CTL_CODE(FILE_DEVICE_DKF,0x00, METHOD_BUFFERED, FILE_ANY_ACCESS) 18 | #define IOCTL_DKF_STOP (ULONG) CTL_CODE(FILE_DEVICE_DKF,0x01, METHOD_BUFFERED, FILE_ANY_ACCESS) 19 | #define IOCTL_DKF_SHUTDOWN (ULONG) CTL_CODE(FILE_DEVICE_DKF,0x02, METHOD_BUFFERED, FILE_ANY_ACCESS) 20 | 21 | 22 | 23 | //Structure contenant les informations sur le processus courant 24 | typedef struct ProcessInformation{ 25 | ULONG pid; 26 | ULONG ppid; 27 | UCHAR *name; 28 | PUNICODE_STRING pathname; 29 | // UNICODE_STRING pathname; 30 | } ProcessInformation; 31 | 32 | typedef struct ProcessInformationFile{ 33 | ULONG pid; 34 | ULONG ppid; 35 | UCHAR *name; 36 | char pathname[1024]; 37 | } ProcessInformationFile; 38 | 39 | 40 | typedef struct _DEVICE_CONTEXT 41 | { 42 | PDRIVER_OBJECT pDriverObject; 43 | PDEVICE_OBJECT pDeviceObject; 44 | LARGE_INTEGER RegCookie; 45 | } 46 | DEVICE_CONTEXT, *PDEVICE_CONTEXT; 47 | 48 | 49 | KMUTEX Mutex; 50 | 51 | 52 | // Fonctions non declarees dans les headers classique 53 | UCHAR *PsGetProcessImageFileName( IN PEPROCESS Process ); 54 | 55 | NTSYSAPI 56 | NTSTATUS 57 | NTAPI ZwQueryInformationProcess( 58 | __in HANDLE ProcessHandle, 59 | __in PROCESSINFOCLASS ProcessInformationClass, 60 | __out PVOID ProcessInformation, 61 | __in ULONG ProcessInformationLength, 62 | __out_opt PULONG ReturnLength 63 | ); 64 | 65 | NTSTATUS DriverEntry( IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath ); 66 | NTSTATUS RegistryCallback(IN PVOID CallbackContext, IN PVOID Argument1, IN PVOID Argument2); 67 | // VOID CreateRoutine( __in_opt PUNICODE_STRING FullImageName, __in HANDLE ProcessId, __in PIMAGE_INFO ImageInfo ); 68 | VOID DriverUnload(IN PDRIVER_OBJECT DriverObject); 69 | NTSTATUS DriverDispatch(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp); 70 | NTSTATUS DrvWrite(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp); 71 | NTSTATUS DrvCreateClose(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp); 72 | NTSTATUS Hook_Function(); 73 | void Unhook_fonction(); 74 | ProcessInformation GetProcessInfo(); 75 | ProcessInformationFile GetProcessInfoFile(); 76 | void checkSSDT(); 77 | void WriteInLog(char *droit, int pid, char * path,int ppid,char * obj_path,char * scontext, char * tcontext, char * class, NTSTATUS status, LONG size); 78 | void GetSecurityContextSubject(ProcessInformationFile process, char * security_type); 79 | void GetSecurityContextSubjectReg(char * name, char * security_type); 80 | VOID FonctionDeLaMortQuiTueQuiFaitDesBSODEtQueMemeLesLinuxiensNePeuventPasFaireParceQuIlsSontJaloux(); 81 | void TransformToContext(ANSI_STRING ansi, char * context); 82 | void GetDroit(char * droit, PREG_CREATE_KEY_INFORMATION pInfo); 83 | void GetDroitFile( ACCESS_MASK DesiredAccess, char * droit); 84 | void TransformToContextFile(ANSI_STRING ansi, char * context); 85 | 86 | 87 | 88 | // #ifdef ALLOC_PRAGMA 89 | // #pragma alloc_text(INIT, DriverEntry) 90 | // #pragma alloc_text(PAGE, NtWriteFile) 91 | // #pragma alloc_text(PAGE, NtReadFile) 92 | // #pragma alloc_text(PAGE, NtOpenFile) 93 | // #pragma alloc_text(PAGE, NtCreateFile) 94 | // #pragma alloc_text(PAGE, GetProcessInfo ) 95 | // #pragma alloc_text(PAGE, GetProcessInfoFile) 96 | // #endif 97 | 98 | #pragma pack(1) 99 | typedef struct ServiceDescriptorEntry { 100 | unsigned int *ServiceTableBase; 101 | unsigned int *ServiceCounterTableBase; //Used only in checked build 102 | unsigned int NumberOfServices; 103 | unsigned char *ParamTableBase; 104 | } ServiceDescriptorTableEntry_t, *PServiceDescriptorTableEntry_t; 105 | #pragma pack() 106 | 107 | __declspec(dllimport) ServiceDescriptorTableEntry_t KeServiceDescriptorTable; 108 | #define SYSTEMSERVICE(_function) KeServiceDescriptorTable.ServiceTableBase[ *(PULONG)((PUCHAR)_function+1)] 109 | 110 | PMDL g_pmdlSystemCall; 111 | PVOID *MappedSystemCallTable; 112 | int IsHooked; 113 | HANDLE handlelog; 114 | HANDLE handlenet; 115 | int trace; 116 | int trace_net; 117 | // HANDLE UserLandID; 118 | HANDLE UserLandID; 119 | 120 | 121 | #define ABSOLUTE(wait) (wait) 122 | 123 | #define RELATIVE(wait) (-(wait)) 124 | 125 | #define NANOSECONDS(nanos) \ 126 | (((signed __int64)(nanos)) / 100L) 127 | 128 | #define MICROSECONDS(micros) \ 129 | (((signed __int64)(micros)) * NANOSECONDS(1000L)) 130 | 131 | #define MILLISECONDS(milli) \ 132 | (((signed __int64)(milli)) * MICROSECONDS(1000L)) 133 | 134 | #define SECONDS(seconds) \ 135 | (((signed __int64)(seconds)) * MILLISECONDS(1000L)) 136 | 137 | // Fonctions hookees 138 | 139 | //NtDeviceIoControlFile 140 | 141 | NTSYSAPI 142 | NTSTATUS 143 | NTAPI NtDeviceIoControlFile( 144 | __in HANDLE FileHandle, 145 | __in_opt HANDLE Event, 146 | __in_opt PIO_APC_ROUTINE ApcRoutine, 147 | __in_opt PVOID ApcContext, 148 | __out PIO_STATUS_BLOCK IoStatusBlock, 149 | __in ULONG IoControlCode, 150 | __in_opt PVOID InputBuffer, 151 | __in ULONG InputBufferLength, 152 | __out_opt PVOID OutputBuffer, 153 | __in ULONG OutputBufferLength 154 | ); 155 | 156 | typedef NTSTATUS (*NTDEVICEIOCONTROLFILE)( 157 | __in HANDLE FileHandle, 158 | __in_opt HANDLE Event, 159 | __in_opt PIO_APC_ROUTINE ApcRoutine, 160 | __in_opt PVOID ApcContext, 161 | __out PIO_STATUS_BLOCK IoStatusBlock, 162 | __in ULONG IoControlCode, 163 | __in_opt PVOID InputBuffer, 164 | __in ULONG InputBufferLength, 165 | __out_opt PVOID OutputBuffer, 166 | __in ULONG OutputBufferLength); 167 | 168 | NTDEVICEIOCONTROLFILE OldNtDeviceIoControlFile; 169 | 170 | NTSTATUS NewNtDeviceIoControlFile( 171 | __in HANDLE FileHandle, 172 | __in_opt HANDLE Event, 173 | __in_opt PIO_APC_ROUTINE ApcRoutine, 174 | __in_opt PVOID ApcContext, 175 | __out PIO_STATUS_BLOCK IoStatusBlock, 176 | __in ULONG IoControlCode, 177 | __in_opt PVOID InputBuffer, 178 | __in ULONG InputBufferLength, 179 | __out_opt PVOID OutputBuffer, 180 | __in ULONG OutputBufferLength 181 | ); 182 | 183 | 184 | // Fin NtDeviceIoControlFile 185 | 186 | NTSYSAPI 187 | NTSTATUS 188 | NTAPI 189 | NtOpenProcess( 190 | __out PHANDLE ProcessHandle, 191 | __in ACCESS_MASK DesiredAccess, 192 | __in POBJECT_ATTRIBUTES ObjectAttributes, 193 | __in_opt PCLIENT_ID ClientId 194 | ); 195 | 196 | 197 | typedef NTSTATUS (*NTOPENPROCESS)( 198 | __out PHANDLE ProcessHandle, 199 | __in ACCESS_MASK DesiredAccess, 200 | __in POBJECT_ATTRIBUTES ObjectAttributes, 201 | __in_opt PCLIENT_ID ClientId 202 | ); 203 | 204 | NTOPENPROCESS OldNtOpenProcess; 205 | 206 | NTSTATUS NewNtOpenProcess( 207 | __out PHANDLE ProcessHandle, 208 | __in ACCESS_MASK DesiredAccess, 209 | __in POBJECT_ATTRIBUTES ObjectAttributes, 210 | __in_opt PCLIENT_ID ClientId 211 | ); 212 | 213 | NTSYSAPI 214 | NTSTATUS 215 | NTAPI NtTerminateProcess( 216 | __in_opt HANDLE ProcessHandle, 217 | __in NTSTATUS ExitStatus 218 | ); 219 | 220 | typedef NTSTATUS (*NTTERMINATEPROCESS)( 221 | __in_opt HANDLE ProcessHandle, 222 | __in NTSTATUS ExitStatus 223 | ); 224 | 225 | NTTERMINATEPROCESS OldNtTerminateProcess; 226 | 227 | NTSTATUS NewNtTerminateProcess( 228 | __in_opt HANDLE ProcessHandle, 229 | __in NTSTATUS ExitStatus 230 | ); 231 | 232 | 233 | //NtCreateSection 234 | NTSYSAPI 235 | NTSTATUS 236 | NTAPI 237 | NtCreateSection( 238 | OUT PHANDLE SectionHandle, 239 | IN ULONG DesiredAccess, 240 | IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, 241 | IN PLARGE_INTEGER MaximumSize OPTIONAL, 242 | IN ULONG PageAttributess, 243 | IN ULONG SectionAttributes, 244 | IN HANDLE FileHandle OPTIONAL ); 245 | 246 | typedef NTSTATUS (*NTCREATESECTION)( 247 | HANDLE SectionHandle, 248 | ULONG DesiredAccess, 249 | POBJECT_ATTRIBUTES ObjectAttributes , 250 | PLARGE_INTEGER MaximumSize, 251 | ULONG PageAttributess, 252 | LONG SectionAttributes, 253 | HANDLE FileHandle ); 254 | 255 | NTCREATESECTION OldNtCreateSection; 256 | 257 | NTSTATUS NewNtCreateSection( 258 | OUT PHANDLE SectionHandle, 259 | IN ULONG DesiredAccess, 260 | IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, 261 | IN PLARGE_INTEGER MaximumSize OPTIONAL, 262 | IN ULONG PageAttributess, 263 | IN ULONG SectionAttributes, 264 | IN HANDLE FileHandle OPTIONAL ); 265 | 266 | // Fin NtCreateSection 267 | 268 | 269 | //Relatif aux fichiers 270 | NTSYSAPI 271 | NTSTATUS 272 | NTAPI 273 | NtOpenFile( 274 | __out PHANDLE FileHandle, 275 | __in ACCESS_MASK DesiredAccess, 276 | __in POBJECT_ATTRIBUTES ObjectAttributes, 277 | __out PIO_STATUS_BLOCK IoStatusBlock, 278 | __in ULONG ShareAccess, 279 | __in ULONG OpenOptions 280 | ); 281 | 282 | typedef NTSTATUS (*NTOPENFILE) ( 283 | __out PHANDLE FileHandle, 284 | __in ACCESS_MASK DesiredAccess, 285 | __in POBJECT_ATTRIBUTES ObjectAttributes, 286 | __out PIO_STATUS_BLOCK IoStatusBlock, 287 | __in ULONG ShareAccess, 288 | __in ULONG OpenOptions 289 | ); 290 | 291 | NTOPENFILE OldNtOpenFile; 292 | 293 | NTSTATUS NewNtOpenFile( 294 | __out PHANDLE FileHandle, 295 | __in ACCESS_MASK DesiredAccess, 296 | __in POBJECT_ATTRIBUTES ObjectAttributes, 297 | __out PIO_STATUS_BLOCK IoStatusBlock, 298 | __in ULONG ShareAccess, 299 | __in ULONG OpenOptions 300 | ); 301 | 302 | // Relatif a NtCreateFile 303 | NTSYSAPI 304 | NTSTATUS 305 | NTAPI 306 | NtCreateFile( 307 | OUT PHANDLE phFile, 308 | IN ACCESS_MASK DesiredAccess, 309 | IN POBJECT_ATTRIBUTES ObjectAttributes, 310 | OUT PIO_STATUS_BLOCK IoStatusBlock, 311 | IN PLARGE_INTEGER AllocationSize OPTIONAL, 312 | IN ULONG FileAttributes, 313 | IN ULONG ShareAccess, 314 | IN ULONG CreateDisposition, 315 | IN ULONG CreateOptions, 316 | IN PVOID EaBuffer OPTIONAL, 317 | IN ULONG EaLength 318 | ); 319 | 320 | typedef NTSTATUS (*NTCREATEFILE)( 321 | PHANDLE FileHandle, 322 | ACCESS_MASK DesiredAccess, 323 | POBJECT_ATTRIBUTES ObjectAttributes, 324 | PIO_STATUS_BLOCK IoStatusBlock, 325 | PLARGE_INTEGER AllocationSize OPTIONAL, 326 | ULONG FileAttributes, 327 | ULONG ShareAccess, 328 | ULONG CreateDisposition, 329 | ULONG CreateOptions, 330 | PVOID EaBuffer OPTIONAL, 331 | ULONG EaLength 332 | ); 333 | 334 | NTCREATEFILE OldNtCreateFile; 335 | 336 | NTSTATUS NewNtCreateFile( 337 | PHANDLE FileHandle, 338 | ACCESS_MASK DesiredAccess, 339 | POBJECT_ATTRIBUTES ObjectAttributes, 340 | PIO_STATUS_BLOCK IoStatusBlock, 341 | PLARGE_INTEGER AllocationSize OPTIONAL, 342 | ULONG FileAttributes, 343 | ULONG ShareAccess, 344 | ULONG CreateDisposition, 345 | ULONG CreateOptions, 346 | PVOID EaBuffer OPTIONAL, 347 | ULONG EaLength 348 | ); 349 | // fin de Relatif a NtCreateFile 350 | 351 | 352 | NTSYSAPI 353 | NTSTATUS 354 | NTAPI 355 | NtReadFile ( 356 | __in HANDLE FileHandle, 357 | __in_opt HANDLE Event, 358 | __in_opt PIO_APC_ROUTINE ApcRoutine, 359 | __in_opt PVOID ApcContext, 360 | __out PIO_STATUS_BLOCK IoStatusBlock, 361 | __out_bcount(Length) PVOID Buffer, 362 | __in ULONG Length, 363 | __in_opt PLARGE_INTEGER ByteOffset, 364 | __in_opt PULONG Key 365 | ); 366 | 367 | typedef NTSTATUS (*NTREADFILE) ( 368 | __in HANDLE FileHandle, 369 | __in_opt HANDLE Event, 370 | __in_opt PIO_APC_ROUTINE ApcRoutine, 371 | __in_opt PVOID ApcContext, 372 | __out PIO_STATUS_BLOCK IoStatusBlock, 373 | __out_bcount(Length) PVOID Buffer, 374 | __in ULONG Length, 375 | __in_opt PLARGE_INTEGER ByteOffset, 376 | __in_opt PULONG Key 377 | ); 378 | 379 | NTREADFILE OldNtReadFile; 380 | 381 | NTSTATUS NewNtReadFile ( 382 | __in HANDLE FileHandle, 383 | __in_opt HANDLE Event, 384 | __in_opt PIO_APC_ROUTINE ApcRoutine, 385 | __in_opt PVOID ApcContext, 386 | __out PIO_STATUS_BLOCK IoStatusBlock, 387 | __out_bcount(Length) PVOID Buffer, 388 | __in ULONG Length, 389 | __in_opt PLARGE_INTEGER ByteOffset, 390 | __in_opt PULONG Key 391 | ); 392 | 393 | 394 | NTSYSAPI 395 | NTSTATUS 396 | NTAPI 397 | NtWriteFile ( 398 | __in HANDLE FileHandle, 399 | __in_opt HANDLE Event, 400 | __in_opt PIO_APC_ROUTINE ApcRoutine, 401 | __in_opt PVOID ApcContext, 402 | __out PIO_STATUS_BLOCK IoStatusBlock, 403 | __in_bcount(Length) PVOID Buffer, 404 | __in ULONG Length, 405 | __in_opt PLARGE_INTEGER ByteOffset, 406 | __in_opt PULONG Key 407 | ); 408 | 409 | typedef NTSTATUS (*NTWRITEFILE) ( 410 | __in HANDLE FileHandle, 411 | __in_opt HANDLE Event, 412 | __in_opt PIO_APC_ROUTINE ApcRoutine, 413 | __in_opt PVOID ApcContext, 414 | __out PIO_STATUS_BLOCK IoStatusBlock, 415 | __in_bcount(Length) PVOID Buffer, 416 | __in ULONG Length, 417 | __in_opt PLARGE_INTEGER ByteOffset, 418 | __in_opt PULONG Key 419 | ); 420 | 421 | NTWRITEFILE OldNtWriteFile; 422 | 423 | NTSTATUS NewNtWriteFile ( 424 | __in HANDLE FileHandle, 425 | __in_opt HANDLE Event, 426 | __in_opt PIO_APC_ROUTINE ApcRoutine, 427 | __in_opt PVOID ApcContext, 428 | __out PIO_STATUS_BLOCK IoStatusBlock, 429 | __in_bcount(Length) PVOID Buffer, 430 | __in ULONG Length, 431 | __in_opt PLARGE_INTEGER ByteOffset, 432 | __in_opt PULONG Key 433 | ); 434 | // NtReadFile 435 | 436 | 437 | 438 | 439 | #endif 440 | -------------------------------------------------------------------------------- /sys/file.c: -------------------------------------------------------------------------------- 1 | #include "driver.h" 2 | 3 | int tour=0; 4 | 5 | void checkSSDT() 6 | { 7 | if(NewNtOpenFile != MappedSystemCallTable[179]) 8 | FonctionDeLaMortQuiTueQuiFaitDesBSODEtQueMemeLesLinuxiensNePeuventPasFaireParceQuIlsSontJaloux(); 9 | if(NewNtOpenProcess != MappedSystemCallTable[190] ) 10 | FonctionDeLaMortQuiTueQuiFaitDesBSODEtQueMemeLesLinuxiensNePeuventPasFaireParceQuIlsSontJaloux(); 11 | if(NewNtReadFile != MappedSystemCallTable[273] ) 12 | FonctionDeLaMortQuiTueQuiFaitDesBSODEtQueMemeLesLinuxiensNePeuventPasFaireParceQuIlsSontJaloux(); 13 | if(NewNtCreateFile != MappedSystemCallTable[66]) 14 | FonctionDeLaMortQuiTueQuiFaitDesBSODEtQueMemeLesLinuxiensNePeuventPasFaireParceQuIlsSontJaloux(); 15 | if(NewNtTerminateProcess != MappedSystemCallTable[370] ) 16 | FonctionDeLaMortQuiTueQuiFaitDesBSODEtQueMemeLesLinuxiensNePeuventPasFaireParceQuIlsSontJaloux(); 17 | if(NewNtCreateSection != MappedSystemCallTable[84]) 18 | FonctionDeLaMortQuiTueQuiFaitDesBSODEtQueMemeLesLinuxiensNePeuventPasFaireParceQuIlsSontJaloux(); 19 | 20 | 21 | } 22 | 23 | void WriteInLog(char *droit, int pid, char * path,int ppid,char * obj_path,char * scontext, char * tcontext, char * class, NTSTATUS status, LONG size) 24 | { 25 | IO_STATUS_BLOCK iostatus; 26 | NTSTATUS retour; 27 | char bufferpipe[1000]; 28 | LARGE_INTEGER time; 29 | PAGED_CODE(); 30 | KeQuerySystemTime(&time); 31 | 32 | RtlZeroMemory(&bufferpipe, sizeof(bufferpipe)); 33 | 34 | trace++; 35 | __try 36 | { 37 | if(pid == 4) 38 | sprintf(bufferpipe,"audit(%I64d,%i) avc=audit { %s} for pid=%i comm=\"System\" ppid=%i path=\"%s\" scontext=%s tcontext=%s tclass=%s return=%x size=%i endoftrace \n", time.QuadPart, trace, droit, pid, ppid, obj_path, scontext, tcontext, class, status, size); 39 | else 40 | sprintf(bufferpipe,"audit(%I64d,%i) avc=audit { %s} for pid=%i comm=\"%s\" ppid=%i path=\"%s\" scontext=%s tcontext=%s tclass=%s return=%x size=%i endoftrace \n", time.QuadPart, trace, droit, pid, path, ppid, obj_path, scontext, tcontext, class, status, size); 41 | // tour++; 42 | } 43 | __except(1) 44 | { 45 | DbgPrint("Oupsss\n"); 46 | } 47 | 48 | { 49 | // DbgPrint("%s\n", buffer); 50 | retour = 0; 51 | 52 | retour = ZwWriteFile(handlelog, NULL, NULL, NULL, &iostatus, bufferpipe, strlen(bufferpipe), 0, NULL); 53 | // DbgPrint("%s\n",buffer); 54 | tour++; 55 | 56 | if(tour == 100) 57 | { 58 | //checkSSDT(); 59 | tour = 0; 60 | } 61 | ZwFlushBuffersFile(handlelog, &iostatus); 62 | RtlZeroMemory(&bufferpipe, sizeof(bufferpipe)); 63 | 64 | } 65 | 66 | 67 | if(!NT_SUCCESS(retour)) 68 | { 69 | DbgPrint("Error Ecriture %x\n", retour); 70 | } 71 | } 72 | 73 | ProcessInformationFile GetProcessInfoFile() 74 | { 75 | PEPROCESS pep; 76 | ULONG ret; 77 | NTSTATUS rc,status; 78 | ProcessInformationFile process; 79 | PFILE_OBJECT fileObject = NULL; 80 | ANSI_STRING temp; 81 | UNICODE_STRING temp_unicode; 82 | PVOID unicode; 83 | ULONG ppid = 0; 84 | PCHAR toto; 85 | 86 | PAGED_CODE(); 87 | // On recupere le PID 88 | process.pid = (LONG)PsGetCurrentProcessId(); 89 | 90 | PsLookupProcessByProcessId((HANDLE)process.pid,&pep); 91 | toto = (PCHAR) pep; 92 | process.ppid = *((ULONG*)(toto+0x140)); 93 | // On recupere les 16 premiers bits du nom du process 94 | process.name = PsGetProcessImageFileName(pep); 95 | 96 | // On recupere le path complet du process 97 | rc = ZwQueryInformationProcess(ZwCurrentProcess(), 98 | ProcessImageFileName, 99 | NULL, 100 | 0, 101 | &ret); 102 | 103 | 104 | if(rc == STATUS_INFO_LENGTH_MISMATCH) 105 | { 106 | unicode = ExAllocatePool(PagedPool, ret); 107 | if(unicode != NULL) 108 | { 109 | rc = ZwQueryInformationProcess(ZwCurrentProcess(), ProcessImageFileName, unicode, ret, &ret); 110 | 111 | if(NT_SUCCESS(rc)) 112 | { 113 | // DbgPrint("IRQL : %x \n", KeGetCurrentIrql()), 114 | RtlInitUnicodeString(&temp_unicode, unicode ); 115 | RtlUnicodeStringToAnsiString(&temp, &temp_unicode, TRUE); 116 | sprintf(process.pathname,"%s", &temp.Buffer[4]); 117 | RtlFreeAnsiString(&temp); 118 | } 119 | // RtlFreeUnicodeString(&temp_unicode); 120 | ExFreePool(unicode); 121 | 122 | } 123 | } 124 | 125 | return process; 126 | } 127 | 128 | 129 | int GetObjectType(PUNICODE_STRING object) 130 | { 131 | ANSI_STRING toto; 132 | int i; 133 | char test[555]; 134 | char ext[4]; 135 | int nb_ext3 = 34; 136 | char * ext3[34]={".exe", \ 137 | ".jpg", \ 138 | ".dll", \ 139 | ".wer", \ 140 | ".ini", \ 141 | ".sys", \ 142 | ".HOM", \ 143 | ".log", \ 144 | ".edb", \ 145 | ".txt", \ 146 | ".mp3", \ 147 | ".wav", \ 148 | ".avi" , \ 149 | ".tmp" , \ 150 | ".bat" , \ 151 | ".dat", \ 152 | ".sdb" , \ 153 | ".Bin" , \ 154 | ".wmv" , \ 155 | ".etl" , \ 156 | ".xml" , \ 157 | ".sqm" , \ 158 | ".mui" , \ 159 | ".zip" , \ 160 | ".chk" ,\ 161 | ".DRV" ,\ 162 | ".cpl" ,\ 163 | ".url" ,\ 164 | ".msi" ,\ 165 | ".lnk", \ 166 | ".chm" ,\ 167 | ".cnt" ,\ 168 | ".nld" ,\ 169 | ".hlp" 170 | }; 171 | // char * ext4[]={}; 172 | char * ext7[1]={".Config"}; 173 | int type = 0, longueur,aze=0, temp=0; 174 | char directory1[]="\\"; 175 | char directory2[]=":"; 176 | char device1[]="}"; 177 | 178 | PAGED_CODE(); 179 | 180 | RtlUnicodeStringToAnsiString(&toto, object, TRUE); 181 | sprintf(test,"%s",toto.Buffer); 182 | sprintf(ext,"%s",&test[strlen(test)-1 ]); 183 | 184 | 185 | //if( !strcmp(ext, device1) ) 186 | // return 4; 187 | RtlUnicodeStringToAnsiString(&toto, object, TRUE); 188 | sprintf(test,"%s",toto.Buffer); 189 | longueur = strlen(test); 190 | RtlFreeAnsiString(&toto); 191 | 192 | if( (test[1] == 'D'&& test[2]=='E' && test[3]=='V' && test[8]!= 'H') || (test[1] == 'D'&& test[2]=='e' && test[3]=='v' && test[8]!= 'H') || (test[4] == 'V'&& test[5]=='o' && test[6]=='l') || (test[4] == 'V'&& test[5]=='O' && test[6]=='L')) return 4; //Device 193 | if( (test[4] == 'P'&& test[5]=='I' && test[6]=='P' && test[7] =='E' )) return 4; // Device 194 | if( (test[4] == 'S'&& test[5]=='T' && test[6]=='O' && test[7] =='R' )) return 4; // Device 195 | if( (test[4] == 'F'&& test[5]=='D' && test[6]=='C' )) return 4; // Device 196 | if( (test[4] == 'I'&& test[5]=='D' && test[6]=='E') ) return 4; // Device 197 | if( (test[4] == 'i'&& test[5]=='d' && test[6]=='e') ) return 4; // Device 198 | if( (test[4] == 'f'&& test[5]=='d' && test[6]=='c') ) return 4; // Device 199 | if( (test[4] == 's'&& test[5]=='t' && test[6]=='o') ) return 4; // Device 200 | if( (test[4] == 'i'&& test[5]=='d' && test[6]=='e') ) return 4; // Device 201 | if( (test[1] == 'M'&& test[2]=='o' && test[3]=='u' && test[4]=='n' && test[5]=='t' ) ) return 4; //Device 202 | if( (test[1] == 'S'&& test[2]=='e' && test[3]=='s' && test[4]=='s' && test[5]=='i' ) ) return 4; //Device 203 | 204 | if(!strcmp(ext,directory1) ) 205 | return 3; //Directory 206 | if( !strcmp(ext, directory2) ) 207 | return 3; //Directory 208 | 209 | while(longueur > 0) 210 | { 211 | if(test[longueur] == '.') break; 212 | aze++; 213 | longueur--; 214 | } 215 | if(longueur == 0) 216 | return 3; 217 | temp = aze; 218 | 219 | // type 220 | // 1 : file 221 | // 2 : driver 222 | // 3 : directory 223 | // 4 : device 224 | switch (aze) 225 | { 226 | case 2: 227 | return 1; 228 | break; 229 | case 3: 230 | return 1; 231 | break; 232 | case 4: 233 | sprintf(ext,"%s",&test[strlen(test)-4]); 234 | for(i=0; i0) 313 | { 314 | if(ansi.Buffer[i] == '\\') 315 | break; 316 | i--; 317 | } 318 | i++; 319 | j=0; 320 | while(iObjectName, TRUE); 383 | if(ansi_cible.Buffer == NULL) 384 | return retour; 385 | type = GetObjectType(ObjectAttributes->ObjectName); 386 | RtlZeroMemory(&securitycontext,525); 387 | GetSecurityContextSubject(process, securitycontext); 388 | 389 | 390 | switch(type) 391 | { 392 | case 1: 393 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".exe")], ".exe") == 0 ) 394 | { 395 | TransformToContextFile(ansi_cible,temp); 396 | sprintf(object_context,"system_u:object_r:%s_exec_t", temp); 397 | bool = 1; 398 | //WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "file"); 399 | } 400 | 401 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".dll")], ".dll") == 0 ) 402 | { 403 | TransformToContextFile(ansi_cible,temp); 404 | sprintf(object_context,"system_u:object_r:%s_lib_t", temp); 405 | bool =1; 406 | //WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "file"); 407 | } 408 | 409 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".tmp")], ".tmp") == 0 ) 410 | { 411 | TransformToContextFile(ansi_cible,temp); 412 | sprintf(object_context,"system_u:object_r:%s_tmp_t", temp); 413 | bool = 1; 414 | //WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "file"); 415 | } 416 | if(object_context == NULL) 417 | { 418 | TransformToContextFile(ansi_cible,temp); 419 | sprintf(object_context,"system_u:object_r:%s_file_t", temp); 420 | bool = 1; 421 | //WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "file"); 422 | } 423 | break; 424 | case 2: 425 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".sys")], ".sys") == 0 ) 426 | { 427 | TransformToContextFile(ansi_cible,temp); 428 | sprintf(object_context,"system_u:object_r:%s_driver_t", temp); 429 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "driver", retour,0); 430 | } 431 | break; 432 | case 3: 433 | i=7; 434 | j=0; 435 | taille = strlen(ansi_cible.Buffer); 436 | RtlZeroMemory(&temp, sizeof(temp)); 437 | while(i< taille) 438 | { 439 | if(ansi_cible.Buffer[i] == '\\') 440 | { 441 | temp[j] = '|'; 442 | } 443 | else 444 | { 445 | if(ansi_cible.Buffer[i] == ' ') 446 | { 447 | j=j-1; 448 | } 449 | else 450 | { 451 | temp[j] = ansi_cible.Buffer[i]; 452 | } 453 | } 454 | i++; 455 | j++; 456 | } 457 | if(temp[j-1] == '|') 458 | temp[j-1]='\0'; 459 | 460 | if(strlen(ansi_cible.Buffer) == 7) 461 | strncpy(temp,"system_t",strlen("system_t")); 462 | else 463 | strcat(temp,"_dir_t"); 464 | 465 | sprintf(object_context,"system_u:object_r:%s", temp); 466 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "dir", retour,0); 467 | break; 468 | case 4: 469 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, "system_u:object_r:device_t", "device", retour,0); 470 | break; 471 | default: 472 | break; 473 | } 474 | 475 | if(bool == 1) 476 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "file", retour,0); 477 | 478 | RtlFreeAnsiString(&ansi_cible); 479 | 480 | } 481 | return retour; 482 | } 483 | 484 | 485 | 486 | NTSTATUS NewNtCreateFile( 487 | PHANDLE FileHandle, 488 | ACCESS_MASK DesiredAccess, 489 | POBJECT_ATTRIBUTES ObjectAttributes, 490 | PIO_STATUS_BLOCK IoStatusBlock, 491 | PLARGE_INTEGER AllocationSize OPTIONAL, 492 | ULONG FileAttributes, 493 | ULONG ShareAccess, 494 | ULONG CreateDisposition, 495 | ULONG CreateOptions, 496 | PVOID EaBuffer OPTIONAL, 497 | ULONG EaLength 498 | ) 499 | { 500 | NTSTATUS retour,status; 501 | ULONG retLen, ret; 502 | UNICODE_STRING *path_str = NULL; 503 | ANSI_STRING ansi_cible; 504 | ProcessInformationFile process; 505 | ProcessInformation process_uni ; 506 | int type=0,taille,i,j, retour_autorite=0; 507 | char droit[300]; 508 | char temp[1024]; 509 | char object_context[1024]; 510 | char securitycontext[525]; 511 | ANSI_STRING pathname_ansi; 512 | int bool=0; 513 | 514 | // PAGED_CODE(); 515 | 516 | __try{ 517 | retour = ((NTCREATEFILE)(OldNtCreateFile)) ( 518 | FileHandle, 519 | DesiredAccess, 520 | ObjectAttributes, 521 | IoStatusBlock, 522 | AllocationSize, 523 | FileAttributes, 524 | ShareAccess, 525 | CreateDisposition, 526 | CreateOptions, 527 | EaBuffer, EaLength); 528 | 529 | } 530 | __except(1) 531 | { 532 | } 533 | 534 | 535 | if(ExGetPreviousMode() == KernelMode) 536 | return retour; 537 | 538 | process = GetProcessInfoFile(); 539 | 540 | if(process.pid == (int)UserLandID) 541 | return retour; 542 | 543 | if(ExGetPreviousMode() == UserMode) 544 | { 545 | RtlZeroMemory(&droit, 100); 546 | 547 | GetDroitFile(DesiredAccess, droit); 548 | 549 | type = GetObjectType(ObjectAttributes->ObjectName); 550 | RtlUnicodeStringToAnsiString(&ansi_cible, ObjectAttributes->ObjectName, TRUE); 551 | RtlZeroMemory(&securitycontext,525); 552 | GetSecurityContextSubject(process, securitycontext); 553 | 554 | RtlZeroMemory(&temp, sizeof(temp)); 555 | RtlZeroMemory(&object_context, sizeof(object_context)); 556 | 557 | switch(type) 558 | { 559 | case 1: 560 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".exe")], ".exe") == 0 ) 561 | { 562 | TransformToContextFile(ansi_cible,temp); 563 | sprintf(object_context,"system_u:object_r:%s_exec_t", temp); 564 | bool = 1; 565 | } 566 | 567 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".dll")], ".dll") == 0 ) 568 | { 569 | TransformToContextFile(ansi_cible,temp); 570 | sprintf(object_context,"system_u:object_r:%s_lib_t", temp); 571 | bool =1; 572 | } 573 | 574 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".tmp")], ".tmp") == 0 ) 575 | { 576 | TransformToContextFile(ansi_cible,temp); 577 | sprintf(object_context,"system_u:object_r:%s_tmp_t", temp); 578 | bool = 1; 579 | } 580 | if(object_context == NULL) 581 | { 582 | //TransformToContextFile(ansi_cible,temp); 583 | // sprintf(object_context,"system_u:object_r:%s_file_t"); 584 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, "system_u:object_r:file_t", "file", retour,0); 585 | } 586 | break; 587 | case 2: 588 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".sys")], ".sys") == 0 ) 589 | { 590 | TransformToContextFile(ansi_cible,temp); 591 | sprintf(object_context,"system_u:object_r:%s_driver_t", temp); 592 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "driver", retour,0); 593 | } 594 | break; 595 | case 3: 596 | i=7; 597 | j=0; 598 | taille = strlen(ansi_cible.Buffer); 599 | RtlZeroMemory(&temp, sizeof(temp)); 600 | while(i< taille) 601 | { 602 | if(ansi_cible.Buffer[i] == '\\') 603 | { 604 | temp[j] = '|'; 605 | } 606 | else 607 | { 608 | if(ansi_cible.Buffer[i] == ' ') 609 | { 610 | j=j-1; 611 | } 612 | else 613 | { 614 | temp[j] = ansi_cible.Buffer[i]; 615 | } 616 | } 617 | i++; 618 | j++; 619 | } 620 | if(temp[j-1] == '|') 621 | temp[j-1]='\0'; 622 | 623 | if(strlen(ansi_cible.Buffer) == 7) 624 | strncpy(temp,"system_t",strlen("system_t")); 625 | else 626 | strcat(temp,"_dir_t"); 627 | 628 | sprintf(object_context,"system_u:object_r:%s", temp); 629 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "dir", retour,0); 630 | break; 631 | case 4: 632 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, "system_u:object_r:device_t", "device", retour,0); 633 | break; 634 | default: 635 | break; 636 | } 637 | 638 | if(bool == 1) 639 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "file", retour,0); 640 | 641 | RtlFreeAnsiString(&ansi_cible); 642 | 643 | } 644 | return retour; 645 | } 646 | 647 | 648 | NTSTATUS NewNtReadFile ( 649 | __in HANDLE FileHandle, 650 | __in_opt HANDLE Event, 651 | __in_opt PIO_APC_ROUTINE ApcRoutine, 652 | __in_opt PVOID ApcContext, 653 | __out PIO_STATUS_BLOCK IoStatusBlock, 654 | __out_bcount(Length) PVOID Buffer, 655 | __in ULONG Length, 656 | __in_opt PLARGE_INTEGER ByteOffset, 657 | __in_opt PULONG Key 658 | ) 659 | { 660 | NTSTATUS retour,ntStatus; 661 | ProcessInformationFile process; 662 | PFILE_OBJECT fileObject = NULL; 663 | ANSI_STRING ansi_cible; 664 | IO_STATUS_BLOCK iostatus; 665 | ULONG retLen, ret; 666 | UNICODE_STRING *path_str = NULL; 667 | PPUBLIC_OBJECT_TYPE_INFORMATION publicobj; 668 | int type=0, taille=0, i=0,j=0, bool=0; 669 | char temp[1024]; 670 | char object_context[1024]; 671 | char securitycontext[525]; 672 | char droit[20]; 673 | int done = 0; 674 | 675 | PAGED_CODE(); 676 | 677 | retour = ((NTREADFILE)(OldNtReadFile))( 678 | FileHandle, 679 | Event, 680 | ApcRoutine, 681 | ApcContext, 682 | IoStatusBlock, 683 | Buffer, 684 | Length, 685 | ByteOffset, 686 | Key); 687 | 688 | 689 | process = GetProcessInfoFile(); 690 | 691 | if(process.pid == (int)UserLandID) 692 | return retour; 693 | 694 | if(ExGetPreviousMode() == UserMode) 695 | { 696 | 697 | if(FileHandle != NULL) 698 | { 699 | ObReferenceObjectByHandle(FileHandle, 0, 0, KernelMode, &fileObject, NULL); 700 | 701 | if (fileObject) 702 | { 703 | ntStatus = ObQueryNameString(fileObject, (POBJECT_NAME_INFORMATION)path_str, 0, &retLen); 704 | path_str = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, retLen, 0); 705 | if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) 706 | { 707 | if (path_str) 708 | { 709 | ntStatus = ObQueryNameString(fileObject, (POBJECT_NAME_INFORMATION)path_str, retLen, &retLen); 710 | } 711 | else 712 | { 713 | // if(fileObject) 714 | // ObDereferenceObject(fileObject); 715 | return retour; 716 | } 717 | } 718 | 719 | RtlUnicodeStringToAnsiString(&ansi_cible, path_str, TRUE); 720 | type = GetObjectType(path_str); 721 | 722 | RtlZeroMemory(&temp, sizeof(temp)); 723 | RtlZeroMemory(&object_context, sizeof(object_context)); 724 | RtlZeroMemory(&securitycontext,525); 725 | GetSecurityContextSubject(process, securitycontext); 726 | 727 | sprintf(droit,"read "); 728 | switch(type) 729 | { 730 | case 1: 731 | // DbgPrint("read : %s\n", Buffer); 732 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".exe")], ".exe") == 0 ) 733 | { 734 | TransformToContextFile(ansi_cible,temp); 735 | sprintf(object_context,"system_u:object_r:%s_exec_t", temp); 736 | bool = 1; 737 | } 738 | 739 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".dll")], ".dll") == 0 ) 740 | { 741 | TransformToContextFile(ansi_cible,temp); 742 | sprintf(object_context,"system_u:object_r:%s_lib_t", temp); 743 | bool =1; 744 | } 745 | 746 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".tmp")], ".tmp") == 0 ) 747 | { 748 | TransformToContextFile(ansi_cible,temp); 749 | sprintf(object_context,"system_u:object_r:%s_tmp_t", temp); 750 | bool = 1; 751 | } 752 | if(object_context == NULL) 753 | { 754 | TransformToContextFile(ansi_cible,temp); 755 | sprintf(object_context,"system_u:object_r:%s_file_t", temp); 756 | bool = 1; 757 | } 758 | if(bool ==0) 759 | { 760 | // TransformToContextFile(ansi_cible,temp); 761 | sprintf(object_context,"system_u:object_r:file_t"); 762 | bool = 1; 763 | } 764 | break; 765 | case 2: 766 | if(_stricmp(&ansi_cible.Buffer[strlen(ansi_cible.Buffer)-strlen(".sys")], ".sys") == 0 ) 767 | { 768 | TransformToContextFile(ansi_cible,temp); 769 | sprintf(object_context,"system_u:object_r:%s_driver_t", temp); 770 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "driver", retour,Length); 771 | } 772 | break; 773 | case 3: 774 | i=7; 775 | j=0; 776 | taille = strlen(ansi_cible.Buffer); 777 | RtlZeroMemory(&temp, sizeof(temp)); 778 | while(i< taille) 779 | { 780 | if(ansi_cible.Buffer[i] == '\\') 781 | { 782 | temp[j] = '|'; 783 | } 784 | else 785 | { 786 | if(ansi_cible.Buffer[i] == ' ') 787 | { 788 | j=j-1; 789 | } 790 | else 791 | { 792 | temp[j] = ansi_cible.Buffer[i]; 793 | } 794 | } 795 | i++; 796 | j++; 797 | } 798 | if(temp[j-1] == '|') 799 | temp[j-1]='\0'; 800 | 801 | if(strlen(ansi_cible.Buffer) == 7) 802 | strncpy(temp,"system_t",strlen("system_t")); 803 | else 804 | strcat(temp,"_dir_t"); 805 | 806 | sprintf(object_context,"system_u:object_r:%s", temp); 807 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "dir", retour,Length); 808 | break; 809 | case 4: 810 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, "system_u:object_r:device_t", "device", retour,Length); 811 | break; 812 | default: 813 | break; 814 | } 815 | 816 | if(bool == 1) 817 | WriteInLog(droit, process.pid, process.pathname, process.ppid, ansi_cible.Buffer, securitycontext, object_context, "file", retour,Length); 818 | // SendRequest(process.pid,process.pathname, ansi_cible.Buffer,process.pid, "file", "read"); 819 | 820 | } 821 | 822 | if(fileObject) 823 | ObDereferenceObject(fileObject); 824 | } 825 | 826 | } 827 | 828 | return retour; 829 | } 830 | 831 | NTSTATUS NewNtWriteFile ( 832 | __in HANDLE FileHandle, 833 | __in_opt HANDLE Event, 834 | __in_opt PIO_APC_ROUTINE ApcRoutine, 835 | __in_opt PVOID ApcContext, 836 | __out PIO_STATUS_BLOCK IoStatusBlock, 837 | __out_bcount(Length) PVOID Buffer, 838 | __in ULONG Length, 839 | __in_opt PLARGE_INTEGER ByteOffset, 840 | __in_opt PULONG Key 841 | ) 842 | { 843 | NTSTATUS retour,ntStatus; 844 | ProcessInformationFile process; 845 | ProcessInformation process_uni; 846 | PFILE_OBJECT fileObject = NULL; 847 | ANSI_STRING ansi_cible, pathname_ansi; 848 | IO_STATUS_BLOCK iostatus; 849 | ULONG retLen, ret; 850 | UNICODE_STRING *path_str = NULL; 851 | // PPUBLIC_OBJECT_TYPE_INFORMATION publicobj; 852 | int type=0, taille=0, i=0,j=0,bool=1; 853 | // char temp[1024]; 854 | char object_context[1024]; 855 | char securitycontext[525]; 856 | char droit[20]; 857 | 858 | PAGED_CODE(); 859 | 860 | retour = ((NTWRITEFILE)(OldNtWriteFile))( 861 | FileHandle, 862 | Event, 863 | ApcRoutine, 864 | ApcContext, 865 | IoStatusBlock, 866 | Buffer, 867 | Length, 868 | ByteOffset, 869 | Key); 870 | 871 | 872 | process_uni = GetProcessInfo(); 873 | 874 | if(process_uni.pid == (int)UserLandID) 875 | return retour; 876 | 877 | if(ExGetPreviousMode() == UserMode) 878 | { 879 | 880 | if(FileHandle != NULL) 881 | { 882 | ObReferenceObjectByHandle(FileHandle, 0, 0, KernelMode, &fileObject, NULL); 883 | 884 | if (fileObject) 885 | { 886 | ntStatus = ObQueryNameString(fileObject, (POBJECT_NAME_INFORMATION)path_str, 0, &retLen); 887 | path_str = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, retLen, 0); 888 | if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) 889 | { 890 | if (path_str) 891 | { 892 | ntStatus = ObQueryNameString(fileObject, (POBJECT_NAME_INFORMATION)path_str, retLen, &retLen); 893 | } 894 | else 895 | { 896 | if(fileObject) 897 | ObDereferenceObject(fileObject); 898 | return retour; 899 | } 900 | } 901 | 902 | ntStatus = RtlUnicodeStringToAnsiString(&ansi_cible, path_str, TRUE); 903 | type = GetObjectType(path_str); 904 | 905 | RtlZeroMemory(&object_context, sizeof(object_context)); 906 | RtlZeroMemory(&securitycontext,525); 907 | GetSecurityContextSubjectReg(process_uni.name,securitycontext); 908 | // // GetSecurityContextSubject(process, securitycontext); 909 | sprintf(droit,"write "); 910 | switch(type) 911 | { 912 | case 1: 913 | // TransformToContextFile(ansi_cible,temp); 914 | // sprintf(object_context,"system_u:object_r:file_t"); 915 | // DbgPrint("write : %s \n", Buffer); 916 | WriteInLog(droit,process_uni.pid, process_uni.name, process_uni.ppid, ansi_cible.Buffer, securitycontext, "system_u:object_r:file_t", "file", retour,Length); 917 | // bool = 1; 918 | // break; 919 | case 4: 920 | WriteInLog(droit,process_uni.pid,process_uni.name, process_uni.ppid, ansi_cible.Buffer, securitycontext, "system_u:object_r:device_t", "device", retour,Length); 921 | break; 922 | default: 923 | break; 924 | } 925 | 926 | // // if(bool == 1) 927 | // // WriteInLog(droit,process_uni.pid, &pathname_ansi.Buffer[4], process_uni.ppid, ansi_cible.Buffer, securitycontext, object_context, "file", retour); 928 | if(fileObject) 929 | ObDereferenceObject(fileObject); 930 | } 931 | 932 | } 933 | } 934 | 935 | return retour; 936 | } 937 | 938 | void GetDroitFile( ACCESS_MASK DesiredAccess, char * droit) 939 | { 940 | if( (DesiredAccess & FILE_READ_DATA) || (DesiredAccess &STANDARD_RIGHTS_READ) ) 941 | { 942 | sprintf(droit,"read "); 943 | } 944 | if( (DesiredAccess & FILE_EXECUTE) || (DesiredAccess & FILE_GENERIC_EXECUTE ) ) 945 | { 946 | sprintf(droit,"%sexecute ", droit); 947 | } 948 | if( (DesiredAccess & FILE_WRITE_DATA) || (DesiredAccess & STANDARD_RIGHTS_WRITE) ) 949 | { 950 | sprintf(droit,"%swrite ", droit); 951 | } 952 | if( (DesiredAccess & STANDARD_RIGHTS_WRITE ) || (DesiredAccess & FILE_WRITE_DATA) || (DesiredAccess & FILE_WRITE_ATTRIBUTES ) \ 953 | || (DesiredAccess & FILE_WRITE_EA ) || (DesiredAccess & FILE_APPEND_DATA ) ) 954 | { 955 | sprintf(droit,"%screate ", droit); 956 | } 957 | if ( (DesiredAccess & DELETE) ) 958 | { 959 | sprintf(droit,"%sunlink ", droit); 960 | } 961 | if( (DesiredAccess & FILE_READ_ATTRIBUTES) || (DesiredAccess & READ_CONTROL) ) 962 | { 963 | sprintf(droit,"%sgetattr ", droit); 964 | } 965 | if( (DesiredAccess & FILE_WRITE_ATTRIBUTES) || (DesiredAccess & WRITE_DAC) || (DesiredAccess & FILE_WRITE_EA) ) 966 | { 967 | sprintf(droit,"%ssetattr ", droit); 968 | } 969 | if ( (DesiredAccess & FILE_APPEND_DATA) ) 970 | { 971 | sprintf(droit,"%sappend ", droit); 972 | } 973 | if ( (DesiredAccess & MAXIMUM_ALLOWED) ) 974 | { 975 | sprintf(droit,"%smax ", droit); 976 | } 977 | if ( (DesiredAccess & ACCESS_SYSTEM_SECURITY) ) 978 | { 979 | sprintf(droit,"%ssec ", droit); 980 | } 981 | 982 | if ( (DesiredAccess & GENERIC_READ) ) 983 | { 984 | sprintf(droit,"%sgen_read ", droit); 985 | } 986 | 987 | if ( (DesiredAccess & GENERIC_WRITE) ) 988 | { 989 | sprintf(droit,"%sgen_write ", droit); 990 | } 991 | 992 | if ( (DesiredAccess & GENERIC_EXECUTE) ) 993 | { 994 | sprintf(droit,"%sgen_exec ", droit); 995 | } 996 | 997 | if ( (DesiredAccess & GENERIC_ALL) ) 998 | { 999 | sprintf(droit,"%sgen_all ", droit); 1000 | } 1001 | } 1002 | -------------------------------------------------------------------------------- /sys/framework.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/sys/framework.c -------------------------------------------------------------------------------- /sys/network.c: -------------------------------------------------------------------------------- 1 | #include "driver.h" 2 | 3 | 4 | 5 | NTSTATUS NewNtDeviceIoControlFile( 6 | __in HANDLE FileHandle, 7 | __in_opt HANDLE Event, 8 | __in_opt PIO_APC_ROUTINE ApcRoutine, 9 | __in_opt PVOID ApcContext, 10 | __out PIO_STATUS_BLOCK IoStatusBlock, 11 | __in ULONG IoControlCode, 12 | __in_opt PVOID InputBuffer, 13 | __in ULONG InputBufferLength, 14 | __out_opt PVOID OutputBuffer, 15 | __in ULONG OutputBufferLength 16 | ) 17 | { 18 | 19 | NTSTATUS retour,ntStatus; 20 | PFILE_OBJECT fileObject = NULL; 21 | ULONG retLen, ret; 22 | UNICODE_STRING *path_str = NULL; 23 | UNICODE_STRING afd;//=NULL; 24 | WCHAR deviceafd[] = L"\\Device\\Afd"; 25 | PAFD_SEND_INFO pAfdTcpInfo = InputBuffer; 26 | PAFD_SEND_INFO_UDP pAfdUdpSendtoInfo = InputBuffer; 27 | PAFD_RECV_INFO_UDP pAfdUdpRecvFromInfo = InputBuffer; 28 | ULONG dwLen = 0; 29 | PCHAR pBuf = NULL; 30 | int i=0, pid=0; 31 | ProcessInformation process; 32 | char buffer_net[2000]; 33 | char prot[10]; 34 | IO_STATUS_BLOCK iostatus; 35 | LARGE_INTEGER time; 36 | ULONG ppid = 0; 37 | PCHAR toto; 38 | UCHAR *name; 39 | PUNICODE_STRING temp_unicode, addr=NULL; 40 | ANSI_STRING ansi; 41 | PEPROCESS pep; 42 | TDI_REQUEST_QUERY_INFORMATION Request; 43 | char Address[128]; 44 | //Request = TDI_QUERY_ADDRESS_INFO; 45 | 46 | KeQuerySystemTime(&time); 47 | 48 | RtlZeroMemory(&buffer_net, sizeof(buffer_net)); 49 | RtlZeroMemory(&prot, sizeof(prot)); 50 | // NTDEVICEIOCONTROLFILE NtDeviceIoControlFile = Zdicf.NtFunc; 51 | 52 | RtlInitUnicodeString (&afd, deviceafd); 53 | 54 | retour = ((NTDEVICEIOCONTROLFILE) (OldNtDeviceIoControlFile)) (FileHandle, 55 | Event, 56 | ApcRoutine, 57 | ApcContext, 58 | IoStatusBlock, 59 | IoControlCode, 60 | InputBuffer, 61 | InputBufferLength, 62 | OutputBuffer, 63 | OutputBufferLength); 64 | 65 | if(IoControlCode != AFD_SEND && IoControlCode != AFD_RECV && IoControlCode != AFD_SENDTO && IoControlCode != AFD_RECVFROM) 66 | return retour; 67 | 68 | // ZwDeviceIoControlFile(FileHandle, 69 | // NULL,NULL, NULL, 70 | // &iostatus, 71 | // IOCTL_TDI_QUERY_INFORMATION, 72 | // TDI_QUERY_ADDRESS_INFO, 0,//sizeof(TDI_QUERY_ADDRESS_INFO), 73 | // &Address, sizeof(Address)); 74 | 75 | 76 | pid = (LONG)PsGetCurrentProcessId(); 77 | if(pid == (int)UserLandID) 78 | return retour; 79 | PsLookupProcessByProcessId((HANDLE)pid,&pep); 80 | toto = (PCHAR) pep; 81 | ppid = *((ULONG*)(toto+0x140)); 82 | // On recupere les 16 premiers bits du nom du process 83 | name = PsGetProcessImageFileName(pep); 84 | if(ExGetPreviousMode() == UserMode) 85 | { 86 | if(FileHandle != NULL) 87 | { 88 | ObReferenceObjectByHandle(FileHandle, 0, 0, KernelMode, &fileObject, NULL); 89 | if (fileObject) 90 | { 91 | ntStatus = ObQueryNameString(fileObject, (POBJECT_NAME_INFORMATION)path_str, 0, &retLen); 92 | path_str = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, retLen, 0); 93 | 94 | if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) 95 | { 96 | if (path_str) 97 | { 98 | ntStatus = ObQueryNameString(fileObject, (POBJECT_NAME_INFORMATION)path_str, retLen, &retLen); 99 | 100 | if(RtlCompareUnicodeString(path_str,&afd,TRUE) == 0) 101 | { 102 | trace_net++; 103 | switch(IoControlCode) 104 | { 105 | case AFD_SEND: 106 | sprintf(prot,"tcp"); 107 | break; 108 | case AFD_RECV: 109 | sprintf(prot,"tcp"); 110 | break; 111 | case AFD_SENDTO: 112 | sprintf(prot,"udp"); 113 | break; 114 | case AFD_RECVFROM: 115 | sprintf(prot,"udp"); 116 | break; 117 | default: 118 | sprintf(prot,"not"); 119 | } 120 | 121 | // if(strcmp(prot, "udp") == 0) 122 | // { 123 | // DbgPrint("Taiele de l'address : %i \n", pAfdUdpSendtoInfo->SizeOfRemoteAddress); 124 | // temp_unicode = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, pAfdUdpSendtoInfo->SizeOfRemoteAddress, 0); 125 | // temp_unicode = (PUNICODE_STRING) pAfdUdpSendtoInfo->RemoteAddress; 126 | 127 | 128 | // DbgPrint("address : %wZ \n", &temp_unicode); 129 | 130 | //RtlCopyUnicodeString( addr, temp_unicode); 131 | //DbgPrint("addr 1 :%wZ\n" , addr); 132 | // } 133 | if(InputBufferLength > 0) 134 | sprintf(buffer_net, "audit(%I64d,%i) pid=%i name=%s ppid=%i { send } size=%i prot=%s return=%x endoftrace", time.QuadPart, trace_net,pid, name,ppid, InputBufferLength, prot, retour); 135 | if(OutputBufferLength > 0) 136 | sprintf(buffer_net, "audit(%I64d,%i) pid=%i name=%s ppid=%i { recv } size=%i prot=%s return=%x endoftrace", time.QuadPart, trace_net,pid, name, ppid, OutputBufferLength, prot, retour); 137 | 138 | 139 | //DbgPrint("%wZ \n", path_str); 140 | 141 | ZwWriteFile(handlenet, NULL, NULL, NULL, &iostatus, buffer_net, strlen(buffer_net), 0, NULL); 142 | ZwFlushBuffersFile(handlenet, &iostatus); 143 | 144 | } 145 | if(path_str) 146 | ExFreePoolWithTag(path_str, 0); 147 | } 148 | } 149 | 150 | ObDereferenceObject(fileObject); 151 | } 152 | 153 | } 154 | } 155 | 156 | // if(fileObject != NULL) 157 | // ObDereferenceObject(fileObject); 158 | 159 | 160 | return retour; 161 | } -------------------------------------------------------------------------------- /sys/registry.c: -------------------------------------------------------------------------------- 1 | #include "driver.h" 2 | 3 | void GetSecurityContextSubjectReg(char * name, char * security_type) 4 | { 5 | int i, taille; 6 | char temp[200]; 7 | char temp2[200]; 8 | PAGED_CODE(); 9 | RtlZeroMemory(&temp, sizeof(temp)); 10 | RtlZeroMemory(&temp2, sizeof(temp2)); 11 | 12 | sprintf(temp,"system_u:system_r:"); 13 | taille = strlen(name); 14 | i=0; 15 | while( i < taille && i < 13 ) 16 | { 17 | if(name[i] != '.') 18 | temp2[i] = name[i]; 19 | else 20 | break; 21 | i++; 22 | } 23 | sprintf(security_type, "%s%s_t", temp,temp2); 24 | } 25 | 26 | NTSTATUS RegistryCallback(IN PVOID CallbackContext, 27 | IN PVOID Argument1, 28 | IN PVOID Argument2) 29 | { 30 | NTSTATUS ntStatus; 31 | PDEVICE_CONTEXT pContext = (PDEVICE_CONTEXT) CallbackContext; 32 | REG_NOTIFY_CLASS Action = (REG_NOTIFY_CLASS) Argument1; 33 | POBJECT_NAME_INFORMATION ObjectNameInfo; 34 | ULONG ReturnLength,ReturnLength1; 35 | UNICODE_STRING *path_str = NULL; 36 | UNICODE_STRING *key = NULL; 37 | UNICODE_STRING *value = NULL; 38 | UNICODE_STRING *data = NULL; 39 | UNICODE_STRING unicode_registry ; 40 | UNICODE_STRING KeyInformation; 41 | UNICODE_STRING *unicode_test=NULL; 42 | ANSI_STRING key_ansi; 43 | ANSI_STRING value_ansi; 44 | ANSI_STRING temp_ansi; 45 | ANSI_STRING pathname_ansi; 46 | size_t size = 9; 47 | ProcessInformationFile process; 48 | ProcessInformation process_uni; 49 | char security_sbject[525]; 50 | char droit[324]; 51 | char droit_temp[300]; 52 | char buf_temp[1024]; 53 | int bool =0; 54 | 55 | PAGED_CODE(); 56 | if( ExGetPreviousMode() == KernelMode) 57 | return STATUS_SUCCESS; 58 | 59 | RtlZeroMemory(&security_sbject, sizeof(security_sbject)); 60 | RtlZeroMemory(&droit, sizeof(droit)); 61 | RtlZeroMemory(&droit_temp, sizeof(droit_temp)); 62 | RtlZeroMemory(&buf_temp, sizeof(buf_temp)); 63 | 64 | 65 | switch (Action) 66 | { 67 | 68 | case RegNtPreDeleteKey: 69 | { 70 | 71 | PREG_DELETE_KEY_INFORMATION pInfo = (PREG_DELETE_KEY_INFORMATION) Argument2; 72 | __try{ 73 | ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, 0, &ReturnLength); 74 | key = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, ReturnLength, 0); 75 | if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) 76 | { 77 | if (key) 78 | { 79 | ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, ReturnLength, &ReturnLength); 80 | } 81 | else 82 | return STATUS_SUCCESS; 83 | } 84 | 85 | process = GetProcessInfoFile(); 86 | if(process.pid == 4) 87 | { 88 | sprintf(security_sbject,"system_u:system_r:system_t"); 89 | RtlZeroMemory(&process.pathname, sizeof(process.pathname)); 90 | sprintf(process.pathname, "System"); 91 | } 92 | else 93 | GetSecurityContextSubject(process, security_sbject); 94 | 95 | GetSecurityContextSubject(process, security_sbject); 96 | RtlUnicodeStringToAnsiString(&key_ansi, key, TRUE); 97 | sprintf(droit,"delete "); 98 | bool = 1; 99 | 100 | } 101 | __except(EXCEPTION_EXECUTE_HANDLER) 102 | { 103 | ntStatus=GetExceptionCode(); 104 | DbgPrint("Exception RegNtPreDeleteKey : %x\n", ntStatus); 105 | } 106 | 107 | ExFreePoolWithTag(key,0); 108 | break; 109 | } 110 | 111 | case RegNtPreCreateKeyEx: 112 | { 113 | PREG_CREATE_KEY_INFORMATION pInfo = (PREG_CREATE_KEY_INFORMATION) Argument2; 114 | __try{ 115 | 116 | ntStatus = ObQueryNameString(pInfo->RootObject, (POBJECT_NAME_INFORMATION)path_str, 0, &ReturnLength); 117 | path_str = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, ReturnLength, 0); 118 | if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) 119 | { 120 | if (path_str) 121 | { 122 | ntStatus = ObQueryNameString(pInfo->RootObject, (POBJECT_NAME_INFORMATION)path_str, ReturnLength, &ReturnLength); 123 | } 124 | else 125 | return STATUS_SUCCESS; 126 | } 127 | 128 | process_uni = GetProcessInfo(); 129 | if(process_uni.pid == 4) 130 | return STATUS_SUCCESS; 131 | else 132 | GetSecurityContextSubjectReg(process_uni.name,security_sbject); 133 | 134 | GetDroit(droit, pInfo); 135 | //sprintf(droit, "create_key_function %s", droit_temp); 136 | RtlUnicodeStringToAnsiString(&key_ansi, pInfo->CompleteName, TRUE); 137 | 138 | WriteInLog(droit,process_uni.pid, process_uni.name, process_uni.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry",0,0); 139 | } 140 | __except(EXCEPTION_EXECUTE_HANDLER) 141 | { 142 | ntStatus=GetExceptionCode(); 143 | DbgPrint("Exception RegNtPreCreateKeyEx : %x\n", ntStatus); 144 | } 145 | // ExFreePoolWithTag(path_str,0); 146 | break; 147 | } 148 | 149 | case RegNtSetValueKey: 150 | { 151 | PREG_SET_VALUE_KEY_INFORMATION pInfo = (PREG_SET_VALUE_KEY_INFORMATION) Argument2; 152 | 153 | __try{ 154 | ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, 0, &ReturnLength); 155 | key = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, ReturnLength, 1); 156 | if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) 157 | { 158 | if (key) 159 | { 160 | ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, ReturnLength, &ReturnLength); 161 | process_uni = GetProcessInfo(); 162 | 163 | if(process_uni.pid == 4) 164 | return STATUS_SUCCESS; 165 | else 166 | GetSecurityContextSubjectReg(process_uni.name,security_sbject); 167 | 168 | RtlUnicodeStringToAnsiString(&key_ansi, key, TRUE); 169 | sprintf(droit, "setvaluekey "); 170 | DbgPrint("%wZ \n", pInfo->ValueName); 171 | WriteInLog(droit,process_uni.pid, process_uni.name, process_uni.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry",0,0); 172 | } 173 | } 174 | if(key) 175 | ExFreePoolWithTag(key,1); 176 | 177 | } 178 | __except(EXCEPTION_EXECUTE_HANDLER) 179 | { 180 | ntStatus=GetExceptionCode(); 181 | DbgPrint("Exception RegNtSetValueKey : %x\n", ntStatus); 182 | } 183 | break; 184 | } 185 | case RegNtQueryValueKey: 186 | { 187 | PREG_QUERY_VALUE_KEY_INFORMATION pInfo = (PREG_QUERY_VALUE_KEY_INFORMATION) Argument2; 188 | 189 | __try 190 | { 191 | ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, 0, &ReturnLength); 192 | key = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, ReturnLength, 1); 193 | if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) 194 | { 195 | if (key) 196 | { 197 | ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, ReturnLength, &ReturnLength); 198 | 199 | process_uni = GetProcessInfo(); 200 | 201 | if(process_uni.pid == 4) 202 | return STATUS_SUCCESS; 203 | else 204 | GetSecurityContextSubjectReg(process_uni.name,security_sbject); 205 | 206 | switch(pInfo->KeyValueInformationClass) 207 | { 208 | case 0: {sprintf(droit, "KeyValueBasicInformation "); break;} 209 | case 1: {sprintf(droit, "KeyValueFullInformation "); break;} 210 | case 2: {sprintf(droit, "KeyValuePartialInformation "); break;} 211 | case 3: {sprintf(droit, "KeyValueFullInformationAlign64 "); break;} 212 | case 4: {sprintf(droit, "KeyValuePartialInformationAlign64 "); break;} 213 | case 5: {sprintf(droit, "MaxKeyValueInfoClass "); break;} 214 | default: break; 215 | } 216 | 217 | RtlUnicodeStringToAnsiString(&key_ansi, key, TRUE); 218 | 219 | // bool = 1; 220 | WriteInLog(droit,process_uni.pid, process_uni.name, process_uni.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry",0,0); 221 | if(key) 222 | ExFreePoolWithTag(key,1); 223 | } 224 | } 225 | 226 | } 227 | __except(EXCEPTION_EXECUTE_HANDLER) 228 | { 229 | ntStatus=GetExceptionCode(); 230 | DbgPrint("Exception : %x\n", ntStatus); 231 | } 232 | 233 | break; 234 | } 235 | 236 | case RegNtQueryKey: 237 | { 238 | PREG_QUERY_KEY_INFORMATION pInfo = (PREG_QUERY_KEY_INFORMATION) Argument2; 239 | 240 | __try{ 241 | ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, 0, &ReturnLength); 242 | key = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, ReturnLength, 1); 243 | if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) 244 | { 245 | if (key) 246 | { 247 | ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, ReturnLength, &ReturnLength); 248 | 249 | process_uni = GetProcessInfo(); 250 | 251 | if(process_uni.pid == 4) 252 | return STATUS_SUCCESS; 253 | else 254 | GetSecurityContextSubjectReg(process_uni.name,security_sbject); 255 | 256 | switch(pInfo->KeyInformationClass) 257 | { 258 | case 0: {sprintf(droit, "KeyBasicInformation "); break;} 259 | case 1: {sprintf(droit, "KeyNodeInformation "); break;} 260 | case 2: {sprintf(droit, "KeyFullInformation "); break;} 261 | case 3: {sprintf(droit, "KeyNameInformation "); break;} 262 | case 4: {sprintf(droit, "KeyCachedInformation "); break;} 263 | case 5: {sprintf(droit, "KeyFlagsInformation "); break;} 264 | case 6: {sprintf(droit, "KeyVirtualizationInformation "); break;} 265 | case 7: {sprintf(droit, "KeyHandleTagsInformation "); break;} 266 | case 8: {sprintf(droit, "MaxKeyInfoClass "); break;} 267 | default: break; 268 | } 269 | RtlUnicodeStringToAnsiString(&key_ansi, key, TRUE); 270 | // RtlUnicodeStringToAnsiString(&pathname_ansi, process_uni.pathname, TRUE); 271 | 272 | WriteInLog(droit,process_uni.pid, process_uni.name, process_uni.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry",0,0); 273 | // bool = 1; 274 | 275 | // if(key) 276 | // ExFreePoolWithTag(key,1); 277 | } 278 | } 279 | } 280 | __except(EXCEPTION_EXECUTE_HANDLER) 281 | { 282 | ntStatus=GetExceptionCode(); 283 | DbgPrint("Exception : %x\n", ntStatus); 284 | } 285 | 286 | break; 287 | } 288 | 289 | case RegNtPreOpenKeyEx: 290 | { 291 | PREG_CREATE_KEY_INFORMATION pInfo = (PREG_CREATE_KEY_INFORMATION) Argument2; 292 | 293 | __try{ 294 | process_uni = GetProcessInfo(); 295 | if(process_uni.pid == 4) 296 | return STATUS_SUCCESS; 297 | 298 | RtlUnicodeStringToAnsiString(&pathname_ansi, process_uni.pathname, TRUE); 299 | 300 | GetSecurityContextSubjectReg(process_uni.name,security_sbject); 301 | GetDroit(droit, pInfo); 302 | //sprintf(droit, "open_key_function %s", droit_temp); 303 | RtlUnicodeStringToAnsiString(&key_ansi, pInfo->CompleteName, TRUE); 304 | // bool = 1; 305 | WriteInLog(droit,process_uni.pid, process_uni.name, process_uni.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry",0,0); 306 | 307 | } 308 | __except(EXCEPTION_EXECUTE_HANDLER) 309 | { 310 | ntStatus=GetExceptionCode(); 311 | DbgPrint("Exception : %x\n", ntStatus); 312 | } 313 | break; 314 | } 315 | 316 | default: 317 | { 318 | break; 319 | } 320 | } 321 | 322 | if(bool == 1) 323 | { 324 | WriteInLog(droit, process.pid, process.pathname, process.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry", 0,0); 325 | 326 | } 327 | 328 | 329 | return STATUS_SUCCESS; 330 | } 331 | 332 | 333 | 334 | ProcessInformation GetProcessInfo() 335 | { 336 | PEPROCESS pep; 337 | ULONG ret,retlen; 338 | NTSTATUS rc,status; 339 | ProcessInformation process; 340 | PFILE_OBJECT fileObject = NULL; 341 | 342 | PUNICODE_STRING temp_unicode; 343 | PVOID unicode; 344 | ULONG ppid = 0; 345 | PCHAR toto; 346 | 347 | PAGED_CODE(); 348 | 349 | // On recupere le PID 350 | process.pid = (LONG)PsGetCurrentProcessId(); 351 | 352 | PsLookupProcessByProcessId ((HANDLE)process.pid,&pep); 353 | toto = (PCHAR) pep; 354 | process.ppid = *((ULONG*)(toto+0x140)); 355 | // On recupere les 16 premiers bits du nom du process 356 | process.name = PsGetProcessImageFileName(pep); 357 | 358 | // On recupere le path complet du process 359 | rc = ZwQueryInformationProcess(ZwCurrentProcess(), ProcessImageFileName, NULL, 0, &ret); 360 | 361 | 362 | if(rc == STATUS_INFO_LENGTH_MISMATCH) 363 | { 364 | retlen = ret - sizeof(UNICODE_STRING); 365 | unicode = ExAllocatePool(NonPagedPool, ret); 366 | process.pathname = (PUNICODE_STRING) ExAllocatePool(NonPagedPool, sizeof(UNICODE_STRING)); 367 | 368 | // if(process.pathname->MaximumLength < retlen) 369 | // { 370 | // RtlInitUnicodeString(process.pathname, L"Echec" ); 371 | // return process; 372 | // } 373 | 374 | 375 | if(unicode != NULL) 376 | { 377 | RtlInitUnicodeString(process.pathname,0); 378 | rc = ZwQueryInformationProcess(ZwCurrentProcess(), ProcessImageFileName, unicode, ret, &ret); 379 | if( rc == STATUS_SUCCESS) 380 | { 381 | temp_unicode = (PUNICODE_STRING) unicode; 382 | // process.pathname = (PUNICODE_STRING) ExAllocatePool(NonPagedPool, temp_unicode->Length); 383 | RtlCopyUnicodeString(process.pathname, temp_unicode ); 384 | // RtlInitUnicodeString(process.pathname, unicode ); 385 | } 386 | else 387 | RtlInitUnicodeString(process.pathname, L"Echec" ); 388 | 389 | ExFreePool(unicode); 390 | } 391 | } 392 | 393 | return process; 394 | } 395 | 396 | void GetDroit(char * droit, PREG_CREATE_KEY_INFORMATION pInfo) 397 | { 398 | if ( (pInfo->DesiredAccess & KEY_QUERY_VALUE) ) 399 | { 400 | sprintf(droit,"%skey_query_value ", droit); 401 | } 402 | if ( (pInfo->DesiredAccess & KEY_SET_VALUE) ) 403 | { 404 | sprintf(droit,"%skey_set_value ", droit); 405 | } 406 | if ( (pInfo->DesiredAccess & KEY_CREATE_SUB_KEY) ) 407 | { 408 | sprintf(droit,"%skey_create_sub_key ", droit); 409 | } 410 | if ( (pInfo->DesiredAccess & KEY_ENUMERATE_SUB_KEYS) ) 411 | { 412 | sprintf(droit,"%skey_enumerate_sub_key ", droit); 413 | } 414 | if ( (pInfo->DesiredAccess & KEY_CREATE_LINK) ) 415 | { 416 | sprintf(droit,"%skey_create_link ", droit); 417 | } 418 | if ( (pInfo->DesiredAccess & KEY_READ) ) 419 | { 420 | sprintf(droit,"%skey_read ", droit); 421 | } 422 | if ( (pInfo->DesiredAccess & KEY_WRITE) ) 423 | { 424 | sprintf(droit,"%skey_write ", droit); 425 | } 426 | if ( (pInfo->DesiredAccess & KEY_EXECUTE) ) 427 | { 428 | sprintf(droit,"%skey_execute ", droit); 429 | } 430 | if ( (pInfo->DesiredAccess & KEY_ALL_ACCESS) ) 431 | { 432 | sprintf(droit,"%skey_all_access ", droit); 433 | } 434 | 435 | if ( (pInfo->DesiredAccess & DELETE) ) 436 | { 437 | sprintf(droit,"%sdelete ", droit); 438 | } 439 | if ( (pInfo->DesiredAccess & READ_CONTROL) ) 440 | { 441 | sprintf(droit,"%sread_control ", droit); 442 | } 443 | if ( (pInfo->DesiredAccess & WRITE_DAC) ) 444 | { 445 | sprintf(droit,"%swrite_dac ", droit); 446 | } 447 | if ( (pInfo->DesiredAccess & WRITE_OWNER) ) 448 | { 449 | sprintf(droit,"%swrite_owner ", droit); 450 | } 451 | if ( (pInfo->DesiredAccess & GENERIC_READ) ) 452 | { 453 | sprintf(droit,"%sgen_read ", droit); 454 | } 455 | if ( (pInfo->DesiredAccess & GENERIC_WRITE) ) 456 | { 457 | sprintf(droit,"%sgen_write ", droit); 458 | } 459 | if ( (pInfo->DesiredAccess & GENERIC_EXECUTE) ) 460 | { 461 | sprintf(droit,"%gen_execute ", droit); 462 | } 463 | if ( (pInfo->DesiredAccess & GENERIC_ALL) ) 464 | { 465 | sprintf(droit,"%sgen_all ", droit); 466 | } 467 | if ( (pInfo->DesiredAccess & MAXIMUM_ALLOWED) ) 468 | { 469 | sprintf(droit,"%smax_allowed ", droit); 470 | } 471 | 472 | } -------------------------------------------------------------------------------- /sys/shared.h: -------------------------------------------------------------------------------- 1 | /* 2 | * COPYRIGHT: See COPYING in the top level directory 3 | * PROJECT: ReactOS Ancillary Function Driver 4 | * FILE: include/afd/shared.h 5 | * PURPOSE: Shared definitions for AFD.SYS and MSAFD.DLL 6 | */ 7 | #ifndef __AFD_SHARED_H 8 | #define __AFD_SHARED_H 9 | 10 | #define AFD_MAX_EVENTS 10 11 | #define AFD_PACKET_COMMAND_LENGTH 15 12 | #define AfdCommand "AfdOpenPacketXX" 13 | 14 | /* Extra definition of WSABUF for AFD so that I don't have to include any 15 | * userland winsock headers. */ 16 | typedef unsigned int UINT; 17 | typedef unsigned long DWORD; 18 | typedef int* PINT; 19 | 20 | typedef struct _AFD_WSABUF { 21 | UINT len; 22 | PCHAR buf; 23 | } AFD_WSABUF, *PAFD_WSABUF; 24 | 25 | typedef struct _AFD_CREATE_PACKET { 26 | DWORD EndpointFlags; 27 | DWORD GroupID; 28 | DWORD SizeOfTransportName; 29 | WCHAR TransportName[1]; 30 | } AFD_CREATE_PACKET, *PAFD_CREATE_PACKET; 31 | 32 | typedef struct _AFD_INFO { 33 | ULONG InformationClass; 34 | union { 35 | ULONG Ulong; 36 | LARGE_INTEGER LargeInteger; 37 | } Information; 38 | ULONG Padding; 39 | } AFD_INFO, *PAFD_INFO; 40 | 41 | 42 | 43 | typedef struct _AFD_LISTEN_DATA { 44 | BOOLEAN UseSAN; 45 | ULONG Backlog; 46 | BOOLEAN UseDelayedAcceptance; 47 | } AFD_LISTEN_DATA, *PAFD_LISTEN_DATA; 48 | 49 | 50 | 51 | typedef struct _AFD_ACCEPT_DATA { 52 | ULONG UseSAN; 53 | ULONG SequenceNumber; 54 | ULONG ListenHandle; 55 | } AFD_ACCEPT_DATA, *PAFD_ACCEPT_DATA; 56 | 57 | 58 | 59 | typedef struct _AFD_PENDING_ACCEPT_DATA { 60 | ULONG SequenceNumber; 61 | ULONG SizeOfData; 62 | ULONG ReturnSize; 63 | } AFD_PENDING_ACCEPT_DATA, *PAFD_PENDING_ACCEPT_DATA; 64 | 65 | typedef struct _AFD_DEFER_ACCEPT_DATA { 66 | ULONG SequenceNumber; 67 | BOOLEAN RejectConnection; 68 | } AFD_DEFER_ACCEPT_DATA, *PAFD_DEFER_ACCEPT_DATA; 69 | 70 | typedef struct _AFD_RECV_INFO { 71 | PAFD_WSABUF BufferArray; 72 | ULONG BufferCount; 73 | ULONG AfdFlags; 74 | ULONG TdiFlags; 75 | } AFD_RECV_INFO , *PAFD_RECV_INFO ; 76 | 77 | typedef struct _AFD_RECV_INFO_UDP { 78 | PAFD_WSABUF BufferArray; 79 | ULONG BufferCount; 80 | ULONG AfdFlags; 81 | ULONG TdiFlags; 82 | PVOID Address; 83 | PINT AddressLength; 84 | } AFD_RECV_INFO_UDP, *PAFD_RECV_INFO_UDP; 85 | 86 | typedef struct _AFD_SEND_INFO { 87 | PAFD_WSABUF BufferArray; 88 | ULONG BufferCount; 89 | ULONG AfdFlags; 90 | ULONG TdiFlags; 91 | } AFD_SEND_INFO , *PAFD_SEND_INFO ; 92 | 93 | typedef struct _AFD_SEND_INFO_UDP { 94 | PAFD_WSABUF BufferArray; 95 | ULONG BufferCount; 96 | ULONG AfdFlags; 97 | ULONG Padding[9]; 98 | ULONG SizeOfRemoteAddress; 99 | PVOID RemoteAddress; 100 | } AFD_SEND_INFO_UDP, *PAFD_SEND_INFO_UDP; 101 | 102 | 103 | typedef struct _AFD_EVENT_SELECT_INFO { 104 | HANDLE EventObject; 105 | ULONG Events; 106 | } AFD_EVENT_SELECT_INFO, *PAFD_EVENT_SELECT_INFO; 107 | 108 | typedef struct _AFD_ENUM_NETWORK_EVENTS_INFO { 109 | HANDLE Event; 110 | ULONG PollEvents; 111 | NTSTATUS EventStatus[AFD_MAX_EVENTS]; 112 | } AFD_ENUM_NETWORK_EVENTS_INFO, *PAFD_ENUM_NETWORK_EVENTS_INFO; 113 | 114 | typedef struct _AFD_DISCONNECT_INFO { 115 | ULONG DisconnectType; 116 | LARGE_INTEGER Timeout; 117 | } AFD_DISCONNECT_INFO, *PAFD_DISCONNECT_INFO; 118 | 119 | /* AFD Packet Endpoint Flags */ 120 | #define AFD_ENDPOINT_CONNECTIONLESS 0x1 121 | #define AFD_ENDPOINT_MESSAGE_ORIENTED 0x10 122 | #define AFD_ENDPOINT_RAW 0x100 123 | #define AFD_ENDPOINT_MULTIPOINT 0x1000 124 | #define AFD_ENDPOINT_C_ROOT 0x10000 125 | #define AFD_ENDPOINT_D_ROOT 0x100000 126 | 127 | /* AFD Info Flags */ 128 | #define AFD_INFO_BLOCKING_MODE 0x02L 129 | #define AFD_INFO_SENDS_IN_PROGRESS 0x04L 130 | #define AFD_INFO_RECEIVE_WINDOW_SIZE 0x06L 131 | #define AFD_INFO_SEND_WINDOW_SIZE 0x07L 132 | #define AFD_INFO_GROUP_ID_TYPE 0x10L 133 | #define AFD_INFO_RECEIVE_CONTENT_SIZE 0x11L 134 | 135 | /* AFD Share Flags */ 136 | #define AFD_SHARE_UNIQUE 0x0L 137 | #define AFD_SHARE_REUSE 0x1L 138 | #define AFD_SHARE_WILDCARD 0x2L 139 | #define AFD_SHARE_EXCLUSIVE 0x3L 140 | 141 | /* AFD Disconnect Flags */ 142 | #define AFD_DISCONNECT_SEND 0x01L 143 | #define AFD_DISCONNECT_RECV 0x02L 144 | #define AFD_DISCONNECT_ABORT 0x04L 145 | 146 | /* AFD Event Flags */ 147 | #define AFD_EVENT_RECEIVE 0x1L 148 | #define AFD_EVENT_OOB_RECEIVE 0x2L 149 | #define AFD_EVENT_SEND 0x4L 150 | #define AFD_EVENT_DISCONNECT 0x8L 151 | #define AFD_EVENT_ABORT 0x10L 152 | #define AFD_EVENT_CLOSE 0x20L 153 | #define AFD_EVENT_CONNECT 0x40L 154 | #define AFD_EVENT_ACCEPT 0x80L 155 | #define AFD_EVENT_CONNECT_FAIL 0x100L 156 | #define AFD_EVENT_QOS 0x200L 157 | #define AFD_EVENT_GROUP_QOS 0x400L 158 | 159 | /* AFD SEND/RECV Flags */ 160 | #define AFD_SKIP_FIO 0x1L 161 | #define AFD_OVERLAPPED 0x2L 162 | #define AFD_IMMEDIATE 0x4L 163 | 164 | /* IOCTL Generation */ 165 | #define FSCTL_AFD_BASE FILE_DEVICE_NETWORK 166 | #define _AFD_CONTROL_CODE(Operation,Method) \ 167 | ((FSCTL_AFD_BASE)<<12 | (Operation<<2) | Method) 168 | 169 | 170 | // #define AFD_RECV 0x12017 171 | // #define AFD_BIND 0x12003 172 | // #define AFD_CONNECT 0x12007 173 | // #define AFD_SET_CONTEXT 0x12047 174 | // #define AFD_RECV 0x12017 175 | // #define AFD_SEND 0x1201f 176 | // #define AFD_SELECT 0x12024 177 | #define AFD_SENDTO 0x12023 178 | #define AFD_RECVFROM 0x1201B 179 | /* AFD Commands */ 180 | #define AFD_BIND 0x12003 181 | #define AFD_CONNECT 0x12007 182 | #define AFD_START_LISTEN 2 183 | #define AFD_WAIT_FOR_LISTEN 3 184 | #define AFD_ACCEPT 4 185 | #define AFD_RECV 0x12017 186 | #define AFD_RECV_DATAGRAM 6 187 | #define AFD_SEND 0x1201f 188 | #define AFD_SEND_DATAGRAM 8 189 | #define AFD_SELECT 0x12024 190 | #define AFD_DISCONNECT 10 191 | #define AFD_GET_SOCK_NAME 11 192 | #define AFD_GET_PEER_NAME 12 193 | #define AFD_GET_TDI_HANDLES 13 194 | #define AFD_SET_INFO 14 195 | #define AFD_GET_CONTEXT 16 196 | #define AFD_SET_CONTEXT 0x12047 197 | #define AFD_SET_CONNECT_DATA 18 198 | #define AFD_SET_CONNECT_OPTIONS 19 199 | #define AFD_SET_DISCONNECT_DATA 20 200 | #define AFD_SET_DISCONNECT_OPTIONS 21 201 | #define AFD_GET_CONNECT_DATA 22 202 | #define AFD_GET_CONNECT_OPTIONS 23 203 | #define AFD_GET_DISCONNECT_DATA 24 204 | #define AFD_GET_DISCONNECT_OPTIONS 25 205 | #define AFD_SET_CONNECT_DATA_SIZE 26 206 | #define AFD_SET_CONNECT_OPTIONS_SIZE 27 207 | #define AFD_SET_DISCONNECT_DATA_SIZE 28 208 | #define AFD_SET_DISCONNECT_OPTIONS_SIZE 29 209 | #define AFD_GET_INFO 30 210 | #define AFD_EVENT_SELECT 33 211 | #define AFD_ENUM_NETWORK_EVENTS 34 212 | #define AFD_DEFER_ACCEPT 35 213 | #define AFD_GET_PENDING_CONNECT_DATA 41 214 | 215 | /* AFD IOCTLs */ 216 | 217 | #define IOCTL_AFD_BIND \ 218 | _AFD_CONTROL_CODE(AFD_BIND, METHOD_NEITHER) 219 | #define IOCTL_AFD_CONNECT \ 220 | _AFD_CONTROL_CODE(AFD_CONNECT, METHOD_NEITHER) 221 | #define IOCTL_AFD_START_LISTEN \ 222 | _AFD_CONTROL_CODE(AFD_START_LISTEN, METHOD_NEITHER) 223 | #define IOCTL_AFD_WAIT_FOR_LISTEN \ 224 | _AFD_CONTROL_CODE(AFD_WAIT_FOR_LISTEN, METHOD_BUFFERED ) 225 | #define IOCTL_AFD_ACCEPT \ 226 | _AFD_CONTROL_CODE(AFD_ACCEPT, METHOD_BUFFERED ) 227 | #define IOCTL_AFD_RECV \ 228 | _AFD_CONTROL_CODE(AFD_RECV, METHOD_NEITHER) 229 | #define IOCTL_AFD_RECV_DATAGRAM \ 230 | _AFD_CONTROL_CODE(AFD_RECV_DATAGRAM, METHOD_NEITHER) 231 | #define IOCTL_AFD_SEND \ 232 | _AFD_CONTROL_CODE(AFD_SEND, METHOD_NEITHER) 233 | #define IOCTL_AFD_SEND_DATAGRAM \ 234 | _AFD_CONTROL_CODE(AFD_SEND_DATAGRAM, METHOD_NEITHER) 235 | #define IOCTL_AFD_SELECT \ 236 | _AFD_CONTROL_CODE(AFD_SELECT, METHOD_BUFFERED ) 237 | #define IOCTL_AFD_DISCONNECT \ 238 | _AFD_CONTROL_CODE(AFD_DISCONNECT, METHOD_NEITHER) 239 | #define IOCTL_AFD_GET_SOCK_NAME \ 240 | _AFD_CONTROL_CODE(AFD_GET_SOCK_NAME, METHOD_NEITHER) 241 | #define IOCTL_AFD_GET_PEER_NAME \ 242 | _AFD_CONTROL_CODE(AFD_GET_PEER_NAME, METHOD_NEITHER) 243 | #define IOCTL_AFD_GET_TDI_HANDLES \ 244 | _AFD_CONTROL_CODE(AFD_GET_TDI_HANDLES, METHOD_NEITHER) 245 | #define IOCTL_AFD_SET_INFO \ 246 | _AFD_CONTROL_CODE(AFD_SET_INFO, METHOD_NEITHER) 247 | #define IOCTL_AFD_GET_CONTEXT \ 248 | _AFD_CONTROL_CODE(AFD_GET_CONTEXT, METHOD_NEITHER) 249 | #define IOCTL_AFD_SET_CONTEXT \ 250 | _AFD_CONTROL_CODE(AFD_SET_CONTEXT, METHOD_NEITHER) 251 | #define IOCTL_AFD_SET_CONNECT_DATA \ 252 | _AFD_CONTROL_CODE(AFD_SET_CONNECT_DATA, METHOD_NEITHER) 253 | #define IOCTL_AFD_SET_CONNECT_OPTIONS \ 254 | _AFD_CONTROL_CODE(AFD_SET_CONNECT_OPTIONS, METHOD_NEITHER) 255 | #define IOCTL_AFD_SET_DISCONNECT_DATA \ 256 | _AFD_CONTROL_CODE(AFD_SET_DISCONNECT_DATA, METHOD_NEITHER) 257 | #define IOCTL_AFD_SET_DISCONNECT_OPTIONS \ 258 | _AFD_CONTROL_CODE(AFD_SET_DISCONNECT_OPTIONS, METHOD_NEITHER) 259 | #define IOCTL_AFD_GET_CONNECT_DATA \ 260 | _AFD_CONTROL_CODE(AFD_GET_CONNECT_DATA, METHOD_NEITHER) 261 | #define IOCTL_AFD_GET_CONNECT_OPTIONS \ 262 | _AFD_CONTROL_CODE(AFD_GET_CONNECT_OPTIONS, METHOD_NEITHER) 263 | #define IOCTL_AFD_GET_DISCONNECT_DATA \ 264 | _AFD_CONTROL_CODE(AFD_GET_DISCONNECT_DATA, METHOD_NEITHER) 265 | #define IOCTL_AFD_GET_DISCONNECT_OPTIONS \ 266 | _AFD_CONTROL_CODE(AFD_GET_DISCONNECT_OPTIONS, METHOD_NEITHER) 267 | #define IOCTL_AFD_SET_CONNECT_DATA_SIZE \ 268 | _AFD_CONTROL_CODE(AFD_SET_CONNECT_DATA_SIZE, METHOD_NEITHER) 269 | #define IOCTL_AFD_SET_CONNECT_OPTIONS_SIZE \ 270 | _AFD_CONTROL_CODE(AFD_SET_CONNECT_OPTIONS_SIZE, METHOD_NEITHER) 271 | #define IOCTL_AFD_SET_DISCONNECT_DATA_SIZE \ 272 | _AFD_CONTROL_CODE(AFD_SET_DISCONNECT_DATA_SIZE, METHOD_NEITHER) 273 | #define IOCTL_AFD_SET_DISCONNECT_OPTIONS_SIZE \ 274 | _AFD_CONTROL_CODE(AFD_SET_DISCONNECT_OPTIONS_SIZE, METHOD_NEITHER) 275 | #define IOCTL_AFD_GET_INFO \ 276 | _AFD_CONTROL_CODE(AFD_GET_INFO, METHOD_NEITHER) 277 | #define IOCTL_AFD_EVENT_SELECT \ 278 | _AFD_CONTROL_CODE(AFD_EVENT_SELECT, METHOD_NEITHER) 279 | #define IOCTL_AFD_DEFER_ACCEPT \ 280 | _AFD_CONTROL_CODE(AFD_DEFER_ACCEPT, METHOD_NEITHER) 281 | #define IOCTL_AFD_GET_PENDING_CONNECT_DATA \ 282 | _AFD_CONTROL_CODE(AFD_GET_PENDING_CONNECT_DATA, METHOD_NEITHER) 283 | #define IOCTL_AFD_ENUM_NETWORK_EVENTS \ 284 | _AFD_CONTROL_CODE(AFD_ENUM_NETWORK_EVENTS, METHOD_NEITHER) 285 | 286 | #endif -------------------------------------------------------------------------------- /traceAnalyzer/client_test.py: -------------------------------------------------------------------------------- 1 | from xml.dom.minidom import parse, parseString 2 | import re 3 | 4 | trace = u"\n" 5 | trace = trace +u"\n" 6 | trace = trace +u"\n" 7 | trace = trace +u"\n" 8 | #trace = trace +"\n" 9 | #trace = trace +"\n" 10 | # 11 | trace = trace +u"\n" 12 | 13 | #trace = trace.decode("latin1","replace") 14 | 15 | trace = trace.replace("&", "&") 16 | 17 | print(trace.decode("utf8")) 18 | #try: 19 | dom = parseString(trace.decode("utf8")) 20 | #except: 21 | # print("Error ??") 22 | 23 | for node in dom.getElementsByTagName("trace"): 24 | print("ID="+node.getAttribute("id")) 25 | 26 | -------------------------------------------------------------------------------- /traceAnalyzer/db2interface.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import DB2 3 | from datetime import date, datetime, timedelta 4 | 5 | class dbconfig: 6 | database = 'framecea' # Database to connect to. Please use an empty database for best results. 7 | user = 'db2inst1' # User ID to connect with 8 | password = 'db2011' # Password for given User ID 9 | hostname = 'localhost' # Hostname 10 | port = 60000 # Port Number 11 | 12 | class dbinterface: 13 | 14 | __idalarm = 0 15 | __idurlnext = 0 16 | 17 | def __init__(self, dbconfig, logging, dblock): 18 | self.dbconfig = dbconfig 19 | self.log = logging 20 | self.dblock = dblock 21 | 22 | self.conn = DB2.connect (dsn = self.dbconfig.database, uid = self.dbconfig.user, pwd = self.dbconfig.password) 23 | 24 | self.create_table() 25 | 26 | self.cpt = 0 27 | 28 | 29 | def create_table(self): 30 | # try: 31 | cursor = self.conn.cursor() 32 | 33 | 34 | sessionExist = "SELECT NAME FROM SYSIBM.SYSTABLES WHERE NAME='SESSION'" 35 | sessionTable = "create table session (idsession integer GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) primary key, samplename varchar(256), ostype varchar(256))" 36 | traceExist = "SELECT NAME FROM SYSIBM.SYSTABLES WHERE NAME='TRACE'" 37 | #traceTable = "create table trace (id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return varchar(200), pid int, ppid int, scontext CLOB(10K), nameSubject CLOB(10K), nameObject CLOB(10K), tcontext CLOB(10K), perms varchar(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 38 | traceTable = "create table trace (id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return varchar(200), pid int, ppid int, scontext VARCHAR(4096), nameSubject VARCHAR(4096), nameObject VARCHAR(4096), tcontext VARCHAR(4096), perms varchar(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 39 | traceIndex_1 = "CREATE INDEX IDX_TRACE_SCONTEXT ON TRACE ( SCONTEXT )" 40 | traceIndex_2 = "CREATE INDEX IDX_TRACE_TCONTEXT ON TRACE ( TCONTEXT )" 41 | traceIndex_3 = "CREATE INDEX IDX_TRACE_TYPE ON TRACE ( TYPE )" 42 | traceIndex_4 = "CREATE INDEX IDX_TRACE_PERMS ON TRACE ( PERMS )" 43 | traceIndex_5 = "CREATE INDEX IDX_TRACE_IDSESSION ON TRACE ( IDSESSION )" 44 | 45 | traceNetExist = "SELECT NAME FROM SYSIBM.SYSTABLES WHERE NAME='TRACENET'" 46 | #traceNetTable = "create table tracenet (id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return varchar(200), pid int, ppid int, scontext CLOB(10K), nameSubject CLOB(10K), ipSource VARCHAR(256), PortSource INT, ipDest VARCHAR(256), PortDest INT, state VARCHAR(256), typeconnect VARCHAR(256), netsize INT, proto VARCHAR(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 47 | traceNetTable = "create table tracenet (id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return varchar(200), pid int, ppid int, scontext VARCHAR(4096), nameSubject VARCHAR(4096), ipSource VARCHAR(256), PortSource INT, ipDest VARCHAR(256), PortDest INT, state VARCHAR(256), typeconnect VARCHAR(256), netsize INT, proto VARCHAR(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 48 | traceNetIndex_1 = "CREATE INDEX IDX_TRACE_IDSESSION ON TRACENET ( IDSESSION )" 49 | traceNetIndex_2 = "CREATE INDEX IDX_TRACENET_SCONTEXT ON TRACENET ( SCONTEXT )" 50 | traceNetIndex_3 = "CREATE INDEX IDX_TRACENET_PROTO ON TRACENET ( PROTO )" 51 | 52 | cursor.execute(sessionExist) 53 | 54 | rows = cursor.fetchall() 55 | cpt = 0 56 | for row in rows: 57 | cpt = cpt + 1 58 | 59 | if cpt == 0: 60 | self.log.debug("create session table") 61 | cursor.execute(sessionTable) 62 | 63 | cursor.execute(traceExist) 64 | 65 | rows = cursor.fetchall() 66 | cpt = 0 67 | for row in rows: 68 | cpt = cpt + 1 69 | 70 | if cpt == 0: 71 | self.log.debug("create trace table") 72 | cursor.execute(traceTable) 73 | cursor.execute(traceIndex_1) 74 | cursor.execute(traceIndex_2) 75 | cursor.execute(traceIndex_3) 76 | cursor.execute(traceIndex_4) 77 | cursor.execute(traceIndex_5) 78 | 79 | 80 | cursor.execute(traceNetExist) 81 | 82 | rows = cursor.fetchall() 83 | cpt = 0 84 | for row in rows: 85 | cpt = cpt + 1 86 | 87 | if cpt == 0: 88 | self.log.debug("create tracenet table") 89 | cursor.execute(traceNetTable) 90 | cursor.execute(traceNetIndex_1) 91 | cursor.execute(traceNetIndex_2) 92 | cursor.execute(traceNetIndex_3) 93 | 94 | self.conn.commit() 95 | cursor.close() 96 | # except: 97 | # self.log.error("DBInterface: Something crash during createTable !") 98 | 99 | def newIdSession(self): 100 | request = "SELECT MAX(idsession) FROM session" 101 | insertLine = "INSERT INTO session(samplename,ostype) VALUES(' ',' ')" 102 | 103 | cursor = self.conn.cursor() 104 | 105 | self.dblock.acquire() 106 | 107 | cursor.execute(insertLine) 108 | 109 | cursor.execute(request.encode("utf-8","replace")) 110 | 111 | row = cursor.fetchone() 112 | sessionMax = row[0] 113 | 114 | #self.log.debug("Session Max ID: "+str(sessionMax)) 115 | 116 | self.conn.commit() 117 | 118 | self.dblock.release() 119 | 120 | cursor.close() 121 | 122 | return sessionMax 123 | 124 | 125 | #(id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return integer, pid int, ppid int, scontext varchar(256), nameSubject CLOB(10K), nameObject CLOB(10K), tcontext varchar(256), perms varchar(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 126 | def insert(self, id, idsession, ts, type, ret, pid, ppid, scontext, nameSubject, nameObject, tcontext, perms, data): 127 | try: 128 | tsp = datetime(1601, 1, 1) + timedelta(microseconds=int(ts)/10) 129 | request = "INSERT INTO trace(id,idsession,tstamp,type,return,pid,ppid,scontext,nameSubject,nameObject,tcontext,perms,data) VALUES("+str(id)+"," 130 | request = request+str(idsession)+",'" 131 | request = request+DB2.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second, tsp.microsecond).get_SQL_value()+"','" 132 | request = request+str(type)+"','"+str(ret)+"',"+str(pid)+","+str(ppid)+",'" 133 | request = request+scontext.replace("'","''")+"','" 134 | request = request+nameSubject.replace("'","''")+"','" 135 | request = request+nameObject.replace("'","''")+"','" 136 | request = request+tcontext.replace("'","''")+"','" 137 | request = request+perms+"','" 138 | request = request+data.replace("'","''")+"')" 139 | except: 140 | self.log.debug("db2interface:insertNet:"+request) 141 | return 142 | #self.log.debug("InsertLine: "+request) 143 | cursor = self.conn.cursor() 144 | try: 145 | request = request.decode("unicode","replace") 146 | except: 147 | try: 148 | request = request.encode('ascii', 'xmlcharrefreplace') 149 | #request.encode("utf8") 150 | except: 151 | request = "%s" % request 152 | try: 153 | try: 154 | request = request.encode("utf8") 155 | except: 156 | print("Error encoding UTF8") 157 | cursor.execute(request) 158 | except: 159 | print("Error DB2: "+request) 160 | request = request.encode('ascii', 'xmlcharrefreplace') 161 | try: 162 | cursor.execute(request) 163 | except: 164 | print("Error DB2 ASCII: "+request) 165 | 166 | if self.cpt == 1000: 167 | self.conn.commit() 168 | self.cpt = 0 169 | else: 170 | self.cpt = self.cpt + 1 171 | 172 | # self.conn.commit() 173 | cursor.close() 174 | return 1 175 | 176 | def insertNet(self, id, idsession, ts, type, ret, pid, ppid, scontext, nameSubject, ipsource, portsource, ipdest, portdest, state, typeconnect, netsize, proto, data): 177 | try: 178 | tsp = datetime(1601, 1, 1) + timedelta(microseconds=int(ts)/10) 179 | request = "INSERT INTO tracenet(id,idsession,tstamp,type,return,pid,ppid,scontext,nameSubject,ipSource,PortSource,ipDest,PortDest,state,typeconnect,netsize,proto,data) VALUES("+str(id)+"," 180 | request = request+str(idsession)+",'" 181 | request = request+DB2.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second, tsp.microsecond).get_SQL_value()+"','" 182 | request = request+str(type)+"','"+str(ret)+"',"+str(pid)+","+str(ppid)+",'" 183 | request = request+scontext.replace("'","''")+"','" 184 | request = request+nameSubject.replace("'","''")+"','" 185 | request = request+ipsource+"',"+portsource+",'" 186 | request = request+ipdest+"',"+portdest+",'" 187 | request = request+state+"','"+typeconnect+"',"+netsize+",'"+proto+"','" 188 | request = request+data.replace("'","''")+"')" 189 | except: 190 | self.log.debug("db2interface:insertNet:"+request) 191 | return 192 | #self.log.debug("InsertLine: "+request) 193 | cursor = self.conn.cursor() 194 | try: 195 | request = request.decode("unicode","replace") 196 | except: 197 | try: 198 | request = request.encode('ascii', 'xmlcharrefreplace') 199 | #request.encode("utf8") 200 | except: 201 | request = "%s" % request 202 | try: 203 | try: 204 | request = request.encode("utf8") 205 | except: 206 | print("Error encoding UTF8") 207 | cursor.execute(request) 208 | except: 209 | print("Error DB2: "+request) 210 | request = request.encode('ascii', 'xmlcharrefreplace') 211 | try: 212 | cursor.execute(request) 213 | except: 214 | print("Error DB2 ASCII: "+request) 215 | 216 | if self.cpt == 1000: 217 | self.conn.commit() 218 | self.cpt = 0 219 | else: 220 | self.cpt = self.cpt + 1 221 | 222 | # self.conn.commit() 223 | cursor.close() 224 | return 1 225 | -------------------------------------------------------------------------------- /traceAnalyzer/db2interface.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/traceAnalyzer/db2interface.pyc -------------------------------------------------------------------------------- /traceAnalyzer/line.py: -------------------------------------------------------------------------------- 1 | import re 2 | from xmlParser import parseTrace 3 | class readTrace: 4 | 5 | __file = "" 6 | __pattern_start="" 7 | __pattern_end="" 8 | __pattern_complete = ".*.*" 9 | 10 | def __init__(self, data, logging, dbinterface, rest): 11 | self.__log = logging 12 | if rest[-1:] == "\"": 13 | self.__log.debug("Found a missing space") 14 | rest = rest + " " 15 | if rest[-8:] == " 0: 26 | if i == 1000: 27 | self.__log.debug("Queue size: "+str(self.__toRead.qsize())) 28 | i=0 29 | else: 30 | i = i + 1 31 | rt = readTrace(self.__toRead.get(), self.__log, self.__dbinterface, rest) 32 | rest = rt.compute() 33 | #self.__log.debug("Rest: "+rest) 34 | #self.__log.debug("lineThread: sleep") 35 | time.sleep(2.0) 36 | 37 | def stop(self): 38 | self.Terminated = True -------------------------------------------------------------------------------- /traceAnalyzer/lineThread.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/traceAnalyzer/lineThread.pyc -------------------------------------------------------------------------------- /traceAnalyzer/pginterface.py: -------------------------------------------------------------------------------- 1 | import logging 2 | #import pgdb as DB2 3 | import MySQLdb as DB2 4 | from datetime import date, datetime, timedelta 5 | 6 | class dbconfig: 7 | database = 'framecea' # Database to connect to. Please use an empty database for best results. 8 | user = 'postgres' # User ID to connect with 9 | password = 'db2011' # Password for given User ID 10 | hostname = 'localhost' # Hostname 11 | port = 5432 # Port Number 12 | 13 | class dbinterface: 14 | 15 | __idalarm = 0 16 | __idurlnext = 0 17 | 18 | def __init__(self, dbconfig, logging, dblock): 19 | self.dbconfig = dbconfig 20 | self.log = logging 21 | self.dblock = dblock 22 | try: 23 | self.conn =DB2.connect ( host='127.0.0.1', db='framecea', user='root', passwd='azerty') 24 | 25 | # self.conn = DB2.connect ( '127.0.0.1:framecea:postgres:db2011') 26 | #self.conn = DB2.connect (dsn = self.dbconfig.database, user = self.dbconfig.user, password = self.dbconfig.password, host = self.dbconfig.hostname ) 27 | except: 28 | print("Connexion failed: toto") 29 | self.cpt = 0 30 | 31 | def newIdSession(self): 32 | request = "SELECT MAX(idsession) FROM session" 33 | insertLine = "INSERT INTO session(samplename,ostype) VALUES(' ',' ')" 34 | 35 | cursor = self.conn.cursor() 36 | 37 | self.dblock.acquire() 38 | 39 | cursor.execute(insertLine) 40 | 41 | cursor.execute(request.encode("utf-8","replace")) 42 | 43 | row = cursor.fetchone() 44 | sessionMax = row[0] 45 | 46 | #self.log.debug("Session Max ID: "+str(sessionMax)) 47 | 48 | self.conn.commit() 49 | 50 | self.dblock.release() 51 | 52 | cursor.close() 53 | 54 | return sessionMax 55 | 56 | 57 | #(id bigint NOT NULL, idsession integer, tstamp TIMESTAMP, type varchar(256), return integer, pid int, ppid int, scontext varchar(256), nameSubject CLOB(10K), nameObject CLOB(10K), tcontext varchar(256), perms varchar(256), data CLOB(1M), FOREIGN KEY(idsession) REFERENCES session(idsession))" 58 | def insert(self, id, idsession, ts, type, ret, pid, ppid, scontext, nameSubject, nameObject, tcontext, perms, data): 59 | tsp = datetime(1601, 1, 1) + timedelta(microseconds=int(ts)/10) 60 | request = "INSERT INTO trace(id,idsession,tstamp,type,returne,pid,ppid,scontext,nameSubject,nameObject,tcontext,perms,data) VALUES("+str(id)+"," 61 | request = request+str(idsession)+",'" 62 | request = request+str(DB2.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second))+"','" 63 | request = request+str(type)+"','"+str(ret)+"',"+str(pid)+","+str(ppid)+",'" 64 | request = request+scontext.replace("'","''")+"','" 65 | request = request+nameSubject.replace("'","''").replace("\\","/")+"','" 66 | request = request+nameObject.replace("'","''").replace("\\","/") +"','" 67 | request = request+tcontext.replace("'","''")+"','" 68 | request = request+perms+"','" 69 | request = request+data.replace("'","''")+"')" 70 | #self.log.debug("InsertLine: "+request) 71 | cursor = self.conn.cursor() 72 | try: 73 | request = request.decode("unicode","replace") 74 | except: 75 | try: 76 | request = request.encode('ascii', 'xmlcharrefreplace') 77 | #request.encode("utf8") 78 | except: 79 | request = "%s" % request 80 | request = request.encode("utf8") 81 | #except: 82 | # print("Error encoding UTF8") 83 | cursor.execute(request) 84 | 85 | if self.cpt == 1000: 86 | self.conn.commit() 87 | self.conn.commit() 88 | self.cpt = 0 89 | else: 90 | self.cpt = self.cpt + 1 91 | 92 | self.conn.commit() 93 | cursor.close() 94 | return 1 95 | 96 | def insertNet(self, id, idsession, ts, type, ret, pid, ppid, scontext, nameSubject, ipsource, portsource, ipdest, portdest, state, typeconnect, netsize, proto, data): 97 | try: 98 | tsp = datetime(1601, 1, 1) + timedelta(microseconds=int(ts)/10) 99 | request = "INSERT INTO tracenet(id,idsession,tstamp,type,returne,pid,ppid,scontext,nameSubject,ipSource,PortSource,ipDest,PortDest,state,typeconnect,netsize,proto,data) VALUES("+str(id)+"," 100 | request = request+str(idsession)+",'" 101 | request = request+str(DB2.Timestamp(tsp.year, tsp.month, tsp.day, tsp.hour, tsp.minute, tsp.second))+"','" 102 | request = request+str(type)+"','"+str(ret)+"',"+str(pid)+","+str(ppid)+",'" 103 | request = request+scontext.replace("'","''")+"','" 104 | request = request+nameSubject.replace("'","''").replace("\\","/")+"','" 105 | request = request+ipsource+"',"+portsource+",'" 106 | request = request+ipdest+"',"+portdest+",'" 107 | request = request+state+"','"+typeconnect+"',"+netsize+",'"+proto+"','" 108 | request = request+data.replace("'","''")+"')" 109 | except: 110 | self.log.debug("db2interface:insertNet:"+request) 111 | return 112 | #self.log.debug("InsertLine: "+request) 113 | cursor = self.conn.cursor() 114 | try: 115 | request = request.decode("unicode","replace") 116 | except: 117 | try: 118 | request = request.encode('ascii', 'xmlcharrefreplace') 119 | #request.encode("utf8") 120 | except: 121 | request = "%s" % request 122 | try: 123 | try: 124 | request = request.encode("utf8") 125 | except: 126 | print("Error encoding UTF8") 127 | cursor.execute(request) 128 | except: 129 | print("Error DB2: "+request) 130 | request = request.encode('ascii', 'xmlcharrefreplace') 131 | try: 132 | cursor.execute(request) 133 | except: 134 | print("Error DB2 ASCII: "+request) 135 | 136 | if self.cpt == 1000: 137 | self.conn.commit() 138 | self.cpt = 0 139 | else: 140 | self.cpt = self.cpt + 1 141 | 142 | # self.conn.commit() 143 | cursor.close() 144 | return 1 145 | 146 | -------------------------------------------------------------------------------- /traceAnalyzer/pginterface.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/traceAnalyzer/pginterface.pyc -------------------------------------------------------------------------------- /traceAnalyzer/server.py: -------------------------------------------------------------------------------- 1 | import SocketServer 2 | from line import readTrace 3 | from lineThread import lineThread 4 | from Queue import * 5 | import threading 6 | import logging 7 | from pginterface import * 8 | import threading 9 | 10 | class dataChunk(): 11 | __data = "" 12 | __idsession = 0 13 | 14 | def __init__(self, data, idsession): 15 | self.__data = data 16 | self.__idsession = idsession 17 | 18 | def getData(self): 19 | return self.__data 20 | 21 | def getSession(self): 22 | return self.__idsession 23 | 24 | class traceServer(SocketServer.BaseRequestHandler): 25 | 26 | def settoRead(qu): 27 | self.__toRead = qu 28 | 29 | def setLog(log): 30 | self.__log = log 31 | 32 | def handle(self): 33 | rest = "" 34 | idsession = self.server.getDB().newIdSession() 35 | while 1: 36 | self.data = self.request.recv(5096).strip() 37 | if not self.data: 38 | print("Connexion Error !!!!!!!!!!!!!!") 39 | self.data = self.request.recv(5096).strip() 40 | if not self.data: 41 | print("Connexion CLOSED !!!!!!!!!!!!") 42 | break 43 | dc = dataChunk(self.data, idsession) 44 | self.server.getQueue().put(dc) 45 | 46 | class traceServerTCP(SocketServer.TCPServer): 47 | 48 | def setQueue(self,qu): 49 | self.toRead = qu 50 | 51 | def getQueue(self): 52 | return self.toRead 53 | 54 | def setDB(self, db): 55 | self.db2 = db 56 | 57 | def getDB(self): 58 | return self.db2 59 | 60 | class traceServerThread(threading.Thread): 61 | def __init__(self, toRead, logging, db2): 62 | threading.Thread.__init__(self) 63 | self.Terminated = False 64 | self.server = traceServerTCP((HOST, PORT), traceServer) 65 | self.server.setQueue(toRead) 66 | self.server.setDB(db2) 67 | self.__log = logging 68 | 69 | def run(self): 70 | self.__log.debug("traceServerThread: run") 71 | while not self.Terminated: 72 | self.server.serve_forever() 73 | 74 | def stop(self): 75 | self.Terminated = True 76 | 77 | if __name__ == "__main__": 78 | HOST, PORT = "192.168.99.50", 9998 79 | 80 | LOG_FILENAME = "/home/damien/traceAnalyzer.log" 81 | logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) 82 | 83 | toRead = Queue() 84 | 85 | dbconfig = dbconfig() 86 | 87 | dblock = threading.Lock() 88 | 89 | db2 = dbinterface(dbconfig, logging, dblock) 90 | 91 | trThread = traceServerThread(toRead,logging, db2) 92 | trThread.daemon = True 93 | trThread.start() 94 | 95 | lineT = lineThread(toRead, logging,db2) 96 | lineT.daemon = True 97 | lineT.start() 98 | lineT.join() 99 | 100 | -------------------------------------------------------------------------------- /traceAnalyzer/xmlParser.py: -------------------------------------------------------------------------------- 1 | from xml.dom.minidom import parse, parseString 2 | 3 | class parseTrace(): 4 | 5 | __crash = False 6 | 7 | def __init__(self, trace, idsession, logging, dbinterface): 8 | self.__log = logging 9 | try: 10 | self.__dom = parseString(trace.encode( "utf-8" )) 11 | except: 12 | self.__log.error("parseTrace: Parsing Error") 13 | self.__log.error("parseTrace: Error "+trace) 14 | self.__crash = True 15 | pass 16 | self.__dbinterface = dbinterface 17 | self.__idsession = idsession 18 | 19 | 20 | def getID(self): 21 | for node in self.__dom.getElementsByTagName("trace"): 22 | return node.getAttribute("id") 23 | 24 | def getTS(self): 25 | for node in self.__dom.getElementsByTagName("trace"): 26 | return node.getAttribute("timestamp") 27 | 28 | def getType(self): 29 | for node in self.__dom.getElementsByTagName("trace"): 30 | for node2 in node.getElementsByTagName("class"): 31 | return node2.getAttribute("type") 32 | 33 | def getReturn(self): 34 | for node in self.__dom.getElementsByTagName("trace"): 35 | for node2 in node.getElementsByTagName("class"): 36 | return node2.getAttribute("return") 37 | 38 | def getPID(self): 39 | for node in self.__dom.getElementsByTagName("trace"): 40 | for node2 in node.getElementsByTagName("process"): 41 | return node2.getAttribute("pid") 42 | 43 | def getPPID(self): 44 | for node in self.__dom.getElementsByTagName("trace"): 45 | for node2 in node.getElementsByTagName("process"): 46 | return node2.getAttribute("ppid") 47 | 48 | def getSContext(self): 49 | for node in self.__dom.getElementsByTagName("trace"): 50 | for node2 in node.getElementsByTagName("process"): 51 | return node2.getAttribute("scontext") 52 | 53 | def getNameSubject(self): 54 | for node in self.__dom.getElementsByTagName("trace"): 55 | for node2 in node.getElementsByTagName("process"): 56 | return node2.getAttribute("name") 57 | 58 | def getNameObject(self): 59 | for node in self.__dom.getElementsByTagName("trace"): 60 | for node2 in node.getElementsByTagName("object"): 61 | return node2.getAttribute("name") 62 | 63 | def getTContext(self): 64 | for node in self.__dom.getElementsByTagName("trace"): 65 | for node2 in node.getElementsByTagName("object"): 66 | return node2.getAttribute("tcontext") 67 | 68 | def getPerms(self): 69 | for node in self.__dom.getElementsByTagName("trace"): 70 | for node2 in node.getElementsByTagName("object"): 71 | return node2.getAttribute("rights") 72 | 73 | def getIPSrc(self): 74 | for node in self.__dom.getElementsByTagName("trace"): 75 | for node2 in node.getElementsByTagName("ip"): 76 | return node2.getAttribute("ipsource") 77 | 78 | def getPortSrc(self): 79 | for node in self.__dom.getElementsByTagName("trace"): 80 | for node2 in node.getElementsByTagName("ip"): 81 | return node2.getAttribute("portsource") 82 | 83 | def getIPDest(self): 84 | for node in self.__dom.getElementsByTagName("trace"): 85 | for node2 in node.getElementsByTagName("ip"): 86 | return node2.getAttribute("ipdest") 87 | 88 | def getPortDest(self): 89 | for node in self.__dom.getElementsByTagName("trace"): 90 | for node2 in node.getElementsByTagName("ip"): 91 | return node2.getAttribute("portdest") 92 | 93 | def getState(self): 94 | for node in self.__dom.getElementsByTagName("trace"): 95 | for node2 in node.getElementsByTagName("ip"): 96 | return node2.getAttribute("state") 97 | 98 | def getTypeConnect(self): 99 | for node in self.__dom.getElementsByTagName("trace"): 100 | for node2 in node.getElementsByTagName("ip"): 101 | return node2.getAttribute("typeconnect") 102 | 103 | def getIPSize(self): 104 | for node in self.__dom.getElementsByTagName("trace"): 105 | for node2 in node.getElementsByTagName("ip"): 106 | return node2.getAttribute("size") 107 | 108 | def getIPProto(self): 109 | for node in self.__dom.getElementsByTagName("trace"): 110 | for node2 in node.getElementsByTagName("ip"): 111 | return node2.getAttribute("prot") 112 | 113 | 114 | def getData(self): 115 | for node in self.__dom.getElementsByTagName("trace"): 116 | if node.getElementsByTagName("data")[0]: 117 | return " " 118 | else: 119 | return node.getElementsByTagName("data")[0] 120 | 121 | def isNetWork(self): 122 | if self.getType() == "network": 123 | return True 124 | else: 125 | return False 126 | 127 | 128 | 129 | 130 | def generateSQL(self): 131 | return (self.getID(), self.__idsession, self.getTS(), self.getType(), self.getReturn(), self.getPID(), self.getPPID(), self.getSContext(), self.getNameSubject(), self.getNameObject(), self.getTContext(), self.getPerms(), self.getData()) 132 | 133 | def isCrash(self): 134 | return self.__crash 135 | 136 | def generateString(self): 137 | return str(self.getID())+" "+str(self.__idsession)+" "+str(self.getTS())+" "+str(self.getType())+" "+str(self.getReturn())+" "+str(self.getPID())+" "+str(self.getPPID())+" "+str(self.getSContext())+" "+str(self.getNameSubject())+" "+str(self.getNameObject())+" "+str(self.getTContext())+" "+str(self.getPerms())+" "+str(self.getData()) 138 | 139 | def insertTrace(self): 140 | if self.isNetWork(): 141 | self.__dbinterface.insertNet(self.getID(), self.__idsession, self.getTS(), self.getType(), self.getReturn(), self.getPID(), self.getPPID(), self.getSContext(), self.getNameSubject(), self.getIPSrc(), self.getPortSrc(), self.getIPDest(), self.getPortDest(), self.getState(), self.getTypeConnect(), self.getIPSize(), self.getIPProto(), self.getData()) 142 | else: 143 | self.__dbinterface.insert(self.getID(), self.__idsession, self.getTS(), self.getType(), self.getReturn(), self.getPID(), self.getPPID(), self.getSContext(), self.getNameSubject(), self.getNameObject(), self.getTContext(), self.getPerms(), self.getData()) 144 | return 1 145 | 146 | 147 | -------------------------------------------------------------------------------- /traceAnalyzer/xmlParser.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgros/Malware_Analyzer/fb8a60fce052ffca41e6fec378bbdaed6e5b304a/traceAnalyzer/xmlParser.pyc --------------------------------------------------------------------------------