How xti9erOSSEC checks netstat rookit is: Use netstat to view the port and bind this port for comparison.
If the port cannot be bind, it indicates that the port is occupied. If netstat does not find this port, it indicates that netstat is replaced by rootkit.
The idea is good. However, the difference between the two causes false positives. For example, some temporary ports are enabled after run_netstat, And the return value of conn_port is turn, a false positive is reported.
Code reproduction:
# Include <glob. h>
# Include <netdb. h>
# Include <netinet/in. h>
# Include <arpa/inet. h>
# Include <sys/socket. h>
# Include <sys/un. h>
# Include <stdio. h>
# Include <stdlib. h>
# Include <sys/types. h>
# Define NETSTAT "netstat-an | grep" ^ % s "|"
"Grep" [^ 0-9] % d ">/dev/null 2> & 1"
Int cport = 0;
Int slp = 0;
Int proto = IPPROTO_TCP;
Int run_netstat (int proto, int port)
{
Printf ("[+] run_netstat frist! ");
Char nt [1024];
If (proto = IPPROTO_TCP)
Snprintf (nt, 1024, NETSTAT, "tcp", port );
Else if (proto = IPPROTO_UDP)
Snprintf (nt, 1024, NETSTAT, "udp", port );
Else
{
Printf ("% s: Netstat error (wrong protocol)", proto );
Return (0 );
}
If (system (nt) = 0)
Return (1 );
Return (0 );
}
Int conn_port (int proto, int port, int slp)
{
Printf ("[+] Sleep % d! ", Slp );
Sleep (slp );
Int rc = 0;
Int ossock;
Struct sockaddr_in server;
If (proto = IPPROTO_UDP)
{
If (ossock = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP) <0)
Return (0 );
}
Else if (proto = IPPROTO_TCP)
{
If (ossock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP) <0)
Return (0 );
}
Memset (& server, 0, sizeof (server ));
Server. sin_family = AF_INET;
Server. sin_port = htons (port );
Server. sin_addr.s_addr = htonl (INADDR_ANY );
/* If we cant bind, it means the port is open */
If (bind (ossock, (struct sockaddr *) & server, sizeof (server) <0)
{
Return (1 );
}
Return (0 );
Close (ossock );
}
Int main (int argc, char * argv [])
{
Cport = atoi (argv [1]);
Slp = atoi (argv [2]);
If (! Run_netstat (proto, cport) & conn_port (proto, cport, slp ))
{
Printf ("Port % d (% s) hidden. Kernel-level rootkit or trojaned version of netstat.", cport, (proto = IPPROTO_UDP )? "Udp": "tcp ");
}
Else
{
Printf ("No kernel-level rootkit hiding any port. Netstat is acting correctly Analyzed port % d", cport );
}
Return 0;
}
-------------------
[Root @ XT9 ~] # Gcc-o portck. c
[Root @ XT9 ~] #./Portck 8080 15
[+] Run_netstat frist!
[+] Sleep 15!
[1] + Stopped./portck 8080 15
[Root @ XT9 ~] # Nc-v-l-p 8080
Listening on [any] 8080...
[2] + Stopped nc-v-l-p 8080
[Root @ XT9 ~] # Fg 1
./Portck 8080 15
Port 8080 (tcp) hidden. Kernel-level rootkit or trojaned version of netstat.
----------------------------
Here we start run_netstat and then sleep for 15 seconds, and enable nc listening for 8080 at the same time. After 15 seconds, conn_port will report a false positive.