For the aspect of just extracting information, it's possible to do that with iptables using AUDIT matches (or possibly LOG matches if you don't need huge amounts of info).
For the case of actually allowing or disallowing connections in real-time based on some complex rules, I'm not sure you can do that on reliably on Linux. Options include:
- Seccomp-BPF, but I'm not certain it can do this (and the filter would be static once instantiated in a given process).
- Overriding various socket calls using LD_PRELOAD or some other method. This is unreliable because it's easy to bypass (making direct syscalls is trivial, and you can also
dlopen() whatever libc and make calls that way).
net_cls control group. This requires firewall setup, may impact active connections, and may not work exactly as you want (it will require a daemon that moves processes into the appropriate control group as they are started).
- If you can tolerate some data getting onto the network, you can use the iptables NFLOG target and watch for interesting connections (if you want real-time evaluation, you'll need to log all new connections and parse things in userspace), and then reactively close the connections that you don't want.
- You can run each application in it's own network namespace and force outbound traffic through the host system, then use policy routing based on the source to control what gets out to the actual network.
That said, you may want to reevaluate why you need this. Unless you're feeding your decision making from a neural network or some other heuristic approach (both of which are problematic options for multiple reasons), you're almost always going to be better off either coding things directly into the firewall (iptables can do some seriously complex stuff, like matching only connections using a specific IP protocol to a specific port initiated by a particular UID at a uniformly distributed random rate and sending the unmatched packets to a different destination), or using scheduling tools or other hooks to update firewall rules dynamically (for example, changing firewall rules when the system is supposed to be unused, or only allowing new connections originating from a given UID when that user is logged in).