I can easily log new tcp connections with iptables like this:
iptables -A INPUT -p tcp --dport XYZ -m state --state NEW -j LOG
Is there a way to log when a connection is closed?
There might be something better, but the tcp protocol ends connections with the FIN or RST packets. You could match on these.
iptables -I INPUT -p tcp --dport XYZ --tcp-flags FIN FIN -j LOG
iptables -I INPUT -p tcp --dport XYZ --tcp-flags RST RST -j LOG
The FIN is repeated as --tcp-flags takes 2 arguments, a mask of what flags to look at, and what combination to accept.
conntrack is also useful for this.
-dportto--dport