What do input and output chains in NAT table do?

INPUT and OUTPUT chains are traversed for packets delivered to and sent from applications running on the local machine.

If an application sends out a packet, it traverses

app -> OUTPUT -> POSTROUTING -> interface

Conversely, a packet delivered to an application traverses

interface -> PREROUTING -> INPUT -> app

While a forwarded packet traverses

interface -> PREROUTING -> FORWARD -> POSTROUTING -> interface

Note that MASQUERADE is just a special case of SNAT, where the source address is taken from the interface.

Also see this picture or many similar ones you can find in iptables tutorials.

Edit

If you want to do DNAT for packets sent from an application, you must use OUTPUT, because DNAT only works in PREROUTING, and outgoing packets from an application never traverse PREROUTING.

Similarly for SNAT, INPUT and POSTROUTING in case of applications sent to an applications, though I'm not sure about the current status of SNAT in INPUT, it may be broken and not actually work.

As most masquerading happens in a router forwarding packets, you don't see these kind of applications often.


NAT table in the INPUT/OUTPUT chains allow for NAT actions for locally generated traffic inside a Linux router.

If you use NAT in POSTROUTING/PREROUTING, that means both traffic to be forwarded/was forwarded and traffic destinated to the local machine will be NATed

If you only want to NAT traffic for the local machine and keep forwarded traffic intact, you use NAT in INPUT/OUTPUT.

eg: You have a Linux router that also serves as DNS server, for a special reason, you need to change the destination port for your local DNS traffic but don't want to alter routed traffic, then you use NAT INPUT/OUTPUT.