Since a potential attacker will exploit the services that are already open to public by firewall rules, how will a firewall help to protect my server from attackers?
A firewall allows you to limit access to ports you specify, and you can specify sources as well. For example, you can prevent non-root users from creating services that accept connections, so an attacker can't create a new shell backdoor. You can even limit outbound connections to reduce the possibility of reverse shells. A not uncommon practice is to only allow SSH connections from "internal" IPs.
Security is about minimizing attack surface, and a firewall is a component in that. Like any tool, it can be almost useless or very useful, depending on how you use it.
There are different types firewall in place each have its own purpose we have
- Packet Filter Firewall: Packet-filtering firewalls are the simplest firewall that validate packets based on protocol, source and/or destination IP addresses, source and/or destination port numbers, time range. They have no visibility to the packet payload.
- Stateful Packet Filter: Stateful Packet Filter are more advanced than simple packet filters my maintaining state of network connections like TCP streams and UDP streams.
- Application / Reverse Proxy Firewall: These are the most advanced type of Firewall and as the name indicate they operate on application layer. In Simplest word these firewall proxy the client application request to the backend server and drops the request if they are malicious.
Obviously cannot block port 80 with a Packet Filter Firewall you to need deploy Application Layer Firewall to protect your web application to do so. An example of application layer firewall will be mod security.