Say I have network A and network B. I wish to SSH from network A to network B. Hence, I would set a route from network A to B, and in the stateful firewall, I will allow a rule for Network A to B at port 22. In this case, do I still need to create a rule to allow Network B to Network A on all ports, since there is TCP handshake? I believe we do not have to, since it's "stateful"? But how does it work?
In this case, do I still need to create a rule to allow Network B to Network A on all ports, since there is TCP handshake? But how does it work?
No, you do not need to do so because the traffic already took place in both directions. It is based on the stateful inspection principle (called also dynamic packet filtering) in which the stateful firewall not only relies on the rules set for it to function but is able to memorize information within dynamic state tables about the incoming and outgoing of the network packets.
Such information is the one hold by the header of the packet such as the destination, the source the protocol used and the port number in use. These information is used by the firewall to decide whether to allow or not pass a packet. It monitors the exchange of packets in both direction (A and B), opening holes in the firewall for each communications session on an as-needed basis , and then close the holes as soon as they're no longer needed for authorized traffic.
Note that this philosophy used by such firewall to function is not totally safe. Some attacks are done by triggering an internal host to generate a TCP packet that (thanks to the dynamic inspection principle used by the firewall) will change the firewall's internal state and enable an attacker to establish a TCP connection to a filtered port through the firewall.