Recently I’ve been doing research on using C language to do network socket programming. I’m wondering if I write a program to listen for incoming data, is this “before” or “after” the firewall?
What I understand is a web server like nginx, lighttpd or cherokee uses socket programming to listen for data, and yet I can set up a firewall like (OpenBSD’s) “pf” to control the incoming data, so it seems like socket probgramming in C is “after” the firewall.
BUT, if that is true, then how are firewalls written? How do they listen to incoming data from specific ports?
Firewalls are implemented by the kernel, in a different part of the networking code. Essentially it amounts to a selection of “hooks” (which can be accessed either via kernel space or user space or both) that notify upon activity.
That activity can either be incoming (ingress) or outgoing (egress) depending upon who originated the packet. For each packet and usually each connection for stateful, connection oriented protocols the firewall is given an opportunity to re-write, veto (e.g. return an error) or simply silently drop a given packet or connection. (Implementations vary and the actions available can be more complex).
The key thing is that the interfaces is quite different to the normal sockets interface – you’re told that things are happening and asked what you’d like to do in relation to that, but you’re not given the same accept/listen/connect style interface that’s normally used for sockets programming.
On Linux for example the firewall is implemented as the input/output “filter” boxes in this packet flow diagram, whereas your sockets code happens in the red layer at the top labelled “protocol/application layer”