Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux kernel hook that knows the destination process of a socket

I'm looking for a specific place to add some kind of hook to the linux kernel that will allow me to do the following:

  • Detect just the case of a TCP connection going to loopback (127.0.0.1)
  • Detect if the source process of the packet is the same as the destination process
  • If this is the case, allow the connection, deny any other loopback connection (one process to another process)

I've been looking at netfilter hooks but they don't seem to fit the need. bpf filters only look at the packet itself.

I was also looking at the LSM hook of socket-connect. I can try to achieve this from the socket-connect hook by looking at what process has the requested port current bound to predict where the connection is going to connect that this sounds quite hackish.

like image 427
shoosh Avatar asked Dec 05 '18 22:12

shoosh


1 Answers

A simple approach could be the use of Linux network namespaces.

Linux Network Namespaces

As the name would imply, network namespaces partition the use of the network—devices, addresses, ports, routes, firewall rules, etc.—into separate boxes, essentially virtualizing the network within a single running kernel instance. Network namespaces entered the kernel in 2.6.24,...

see https://lwn.net/Articles/580893/

Unshare

unshare() allows a process (or thread) to disassociate parts of its execution context that are currently being shared with other processes (or threads).

see http://man7.org/linux/man-pages/man2/unshare.2.html

Testcase

Since a program should be able to comunicate with itself we need a program that communicates with itself via sockes. There is a cool SO answer that shows a simple Java program that transfers the text 'Hello World!' via socket to itself, see here https://stackoverflow.com/a/8119708.

/usr/bin/java SendReceive

works as expected and gives the output 'Hello World!'

With the -n option one can unshare network namespace.

unshare -n -- sh -c '/usr/bin/java SendReceive'

gives a SocketException: Network is unreachable because there is no access to the loopback device.

unshare -n -- sh -c 'ip link set dev lo up; /usr/bin/java SendReceive'

finally transfers 'Hello World!' again via a loopback interface. BTW: this is a private loopback device. You cannot access open ports on the standard loopback device.

See also this cool Unix Stackexchange answer: https://unix.stackexchange.com/a/83348: Block network access of a process?

Screenshot

Here a screenshot of the test case mentioned above executed on Ubuntu 18.10:

screenshot

like image 134
Stephan Schlecht Avatar answered Oct 10 '22 16:10

Stephan Schlecht