What is a firewall & how does it work

Tips & tricks 20 mins
Laptop with a brick wall.

Imagine leaving your front door unlocked. Anyone—or anything—could wander in without warning. The same goes for your digital life. A firewall is the invisible guard that checks everything trying to enter (or leave) your devices or network, letting only the safe stuff through. It’s a shield against unknown intruders, malicious sites, and would-be data thieves.

In this article, you’ll learn the basics of how firewalls work, the different types available, and why they’re vital to a complete cybersecurity strategy. We’ll also explore the common pitfalls of relying on a firewall alone and show you how they can coexist with other tools like antivirus software and VPNs.

Firewalls are not foolproof and should be used together with other security measures for comprehensive protection. Want extra peace of mind when you browse, stream, or work online? ExpressVPN protects your connection by encrypting traffic, hiding your real IP address, and helping you dodge eavesdroppers. 

Get ExpressVPN

What is a firewall?

A firewall is a barrier that monitors, filters, and controls traffic moving into or out of a device or network. It allows trusted data while stopping unauthorized access and malicious activity. Think of it as a gatekeeper for your entire online setup.

Firewalls come in many forms—hardware appliances, software running on a computer, cloud-based solutions, or virtual machines—and they work by following specific rules. These rules define what kind of data is allowed or denied based on factors like IP addresses, port numbers, and communication protocols. A firewall can be as basic as simple packet filtering or as advanced as a next-generation solution that scans deeper into each data packet, uses machine learning to spot unusual activity, and intercepts emerging threats in real time.

Let’s look at why firewalls matter to network security, how they function, and where they fit within a full cybersecurity strategy.

The role of firewalls in network security

Firewalls act as a checkpoint between a trusted internal network and an external one that might pose risk, such as the internet. By examining each data packet, firewalls sort acceptable traffic from harmful or unapproved data. Firewalls use a set of rules to differentiate between benign and malicious traffic: If a packet matches the criteria of a permitted rule, it goes forward; if it looks suspect, the firewall blocks it.

Because of this screening, users don’t have to worry as much about unauthorized access or malicious programs that try to slip in from outside. Organizations also rely on firewalls to regulate network traffic internally, which helps them separate different departments, isolate critical resources, and watch for irregular inward or outgoing communication. With remote and hybrid work, companies often need firewalls that can manage connections across data centers, satellite branches, cloud environments, and remote endpoints.

Modern firewalls have included new capabilities to keep pace with ever-evolving exploits:

  • Deep packet inspection (DPI): Goes beyond a packet’s header to look at the contents, making it easier to catch hidden malicious code.
  • Intrusion prevention systems (IPS): Actively blocks or disables threats spotted in network traffic.
  • Application awareness: Identifies and filters applications rather than just ports or protocols.
  • Machine learning: Spots behavior that strays from normal patterns, helping to detect zero-day threats.

That extra intelligence makes firewalls a big part of layered security, where multiple protection methods back each other up.

Why firewalls are essential for cybersecurity

Firewalls aren’t just digital “walls.” They keep an eye on who and what can communicate on your network. Controlling these interactions drastically reduces the risk of attacks like malware infiltration, unauthorized remote access, and data exfiltration. A firewall logs attempts at entry too. Those logs help IT teams see patterns of malicious activity, which can inform future rule updates or quarantines.

A firewall is also handy for meeting regulatory obligations. Many industries must prove they guard private information. A well-managed firewall is a standard measure demonstrating a strong data and infrastructure protection approach.

Key reasons you might rely on a firewall:

  • Raising the barrier to entry: Unwanted or unsafe data can’t simply stroll in.
  • Tracking session states: A firewall can remember your ongoing sessions, ensuring only recognized connections continue sending data.
  • Protecting against known malicious domains: Some solutions integrate with threat intelligence, blocking traffic to recognized unsafe websites.
  • Supporting compliance audits: The firewall’s logs offer a record of suspicious activity for compliance or forensic review.

How does a firewall work?

Firewalls all share the same core function: Comparing traffic against a set of security rules, then taking an action—allow, block, or log—based on what those rules dictate. This behavior can run on network devices (like a router) or local software (on your device). More advanced setups might rely on multiple firewalls in a screened subnet approach, placing an extra layer between an outer and inner network.

When data travels through a firewall, the device or software looks at the packet’s source, destination IP, port, and protocol. With deeper inspection, it may examine the data payload to catch hidden malware, suspicious scripts, or irregular requests. If a packet doesn’t meet the rules, the firewall rejects it.

How firewalls monitor and filter traffic

Each firewall uses a different inspection style:

  • Packet filtering: The simplest method, scanning basic packet info (IP, port) before allowing or denying it.
  • Stateful inspection: Maintains awareness of ongoing sessions. If a new data packet doesn’t match an existing or recognized session, the firewall blocks it.
  • Proxy (application-level) firewalls: Fully intercept connections at the application layer. They receive traffic, analyze it, then act as an intermediary for legitimate requests.
  • Deep packet inspection: Reads the internal content of data packets. Aids in detecting advanced malware or hidden exploits.
  • AI-powered firewalls: Use machine learning to identify abnormal traffic patterns, which might signal zero-day attacks or intrusions that static rules can’t detect.

A firewall might combine several methods. For example, it could rely on stateful inspection for normal traffic but switch to deep inspection if it spots something suspicious.

How firewalls prevent cyberattacks

When set up correctly, firewalls can short-circuit most early attack attempts. Criminals frequently scan networks for open ports or use repeated login attempts to gain entry. A firewall can spot and stop these scans, making it harder for intruders to discover weaknesses.

If malware tries to “call home” to a remote control server, outbound firewall rules can interrupt that traffic. This helps prevent data theft. Together with intrusion prevention systems or advanced endpoint tools, a well-tuned firewall shrinks a criminal’s available paths to compromise a device or network.

Why are firewalls important?

Firewalls regulate who can connect with your system. Without them, every port and service on your computer or network is potentially open to external probing. That’s risky, given how many automated bots roam the internet looking for easy targets. Below are some key ways firewalls improve digital security.

Blocking unauthorized access

Firewalls serve as guards who only let recognized visitors through. You set guidelines about what’s acceptable, which might be “only traffic from IP addresses used by your company” or “only connections using these specific protocols.” Everything else is turned away.

When done right, this approach helps ensure no outsider can directly contact a device unless it’s explicitly allowed. That lowers the odds of infiltration since criminals can’t freely poke around or exploit random services on your network.

Protecting sensitive data from hackers

Attackers aim to steal data (like passwords, personal information, or research) or disrupt services. Firewalls intercept these attempts by deciding whether a request or file transfer is legitimate. If the traffic or content looks suspicious, the firewall halts it. This approach is effective for everyday threats such as:

  • Malware-laden downloads: The firewall might detect malicious patterns or block known dangerous file types.
  • Command-and-control channels: A firewall can halt communication with attacker-controlled servers.
  • Phishing: Some solutions filter known phishing sites or block suspicious domains, preventing users from revealing sensitive details.

While a firewall isn’t a silver bullet—users might still click harmful links—an updated firewall drastically shrinks your exposure to widespread hacking tactics.

Ensuring compliance with security standards

Many rules and standards require an organization to keep data safe against outsiders. Finance, healthcare, and government regulations commonly list firewall deployment among their baseline measures.

By using a firewall, you build a record of your inbound and outbound network activity, which helps demonstrate you’re preventing unauthorized access. Should you face an audit, logs from your firewall make it easier to show that you restrict connections according to best practices.

Types of firewalls: Which one do you need?

Firewalls have grown from simple packet filters to advanced platforms that integrate threat intelligence, encrypted traffic inspection, and centralized policy management. Your choice depends on your network’s complexity, the types of threats you face, and your performance needs. Some organizations combine several for a layered approach. Below we look at some popular categories. 

Packet filtering firewalls

Packet filtering firewalls check each data packet individually. They look at headers (source/destination IP, port) and compare them to a list of rules. If the packet matches a permitted rule, it’s allowed; if not, it’s dropped.

ProsCons
Low overhead: Simple to deploy and manageCannot read packet contents
Useful for basic perimeter defenseFails to track established connections, so it’s less effective against complex threats

 

These are often the earliest type, historically used for straightforward filtering. They remain common in routers for small offices and home networks. But they’re generally insufficient for advanced threat prevention.

Read more: How to set up a home server and use it as a Bitcoin node

Proxy firewalls

Proxy firewalls sit between internal users and external resources, acting as an intermediary. When users request a webpage or resource, the firewall fetches it on their behalf, examines the data, and passes it along if it’s safe.

ProsCons
Conceals the internal network from outside serversCan introduce latency
Allows deeper application-layer inspectionMight not support all applications out of the box

 

A proxy firewall is helpful if you want to hide your network details and thoroughly scan data at higher layers (like HTTP requests). It’s also useful for content caching or restricting certain websites.

Stateful inspection firewalls

Stateful inspection firewalls track ongoing connections, letting them make decisions based on the context of a traffic stream, not just individual packets. They examine protocol states, ports, and rules while keeping track of whether a packet is part of a recognized session.

ProsCons
More effective at stopping random inbound scansLess visibility into application data if it only checks session state
Balances performance and security wellConsumes more resources than simple packet filters

 

These are the “traditional” enterprise approach. Many operating systems also integrate a basic stateful firewall for home users, and it usually runs by default.

Next-generation firewalls (NGFW)

Next-generation firewalls blend traditional packet filtering, stateful inspection, and advanced features such as:

  • Deep packet inspection
  • Intrusion prevention
  • Application-level controls
  • Reputation-based filtering
  • AI-powered analysis

They’re designed to catch modern threats like encrypted malware, advanced persistent threats, and zero-day exploits.

ProsCons
Comprehensive coverage of network layers and threat typesHigher cost and complexity
Centralized policy and advanced intelligence for large deploymentsHigher cost and complexity

 

NGFW solutions are standard in midsize-to-large organizations. They’re also increasingly available for smaller networks as cost and complexity go down.

Web application firewalls (WAFs)

A web application firewall shields web-based services or applications by examining HTTP or HTTPS traffic. It identifies injection attacks, cross-site scripting, and other web exploits.

ProsCons
Ideal for protecting customer-facing websites or appsLimited scope, only covering web protocols
Focuses on application-level threats, including malicious code in data fieldsRequires frequent tuning to avoid blocking normal site traffic

 

Organizations that run e-commerce sites, SaaS platforms, or public APIs often use WAFs to defend user data and transactions.

Unified threat management (UTM) firewalls

UTM appliances package multiple security tools—like antivirus, intrusion prevention, web filtering, and firewall rules—into one product. They’re popular with smaller or midrange businesses that want an all-in-one system.

ProsCons
Straightforward to deployNot as flexible or scalable as dedicated specialized products
Central interface for multiple security functionsPotential performance bottlenecks if all features are enabled at once

 

A UTM can help if you lack the staff or budget to manage multiple standalone solutions and need a simpler approach to defending a branch office or small enterprise.

AI-Powered firewalls

AI-driven firewalls analyze huge sets of network data for odd traffic patterns. By learning what “normal” looks like, they can spot new or stealthy intrusions that standard signatures might miss.

ProsCons
Dynamically adapts to fresh threatsNeeds enough data to train machine learning models accurately
Reduces false positives by refining its understanding of typical behaviorMight require more CPU/memory resources

 

Larger enterprises or data centers often adopt these for real-time anomaly detection. They may also help smaller environments if offered as a cloud service.

Cloud firewalls & Firewall-as-a-Service (FWaaS)

Cloud and FWaaS solutions run firewall capabilities on remote infrastructure. Instead of installing hardware on-site, you point your traffic through a provider’s firewall service.

ProsCons
Quick to set up, with minimal hardware investmentRequires reliable internet connectivity
Scales up or down as your network growsHands some control over to the provider’s platform

 

Businesses embracing the cloud often pick FWaaS to unify policy enforcement across multiple locations without the hardware overhead. Some also deploy virtual firewalls within public or private clouds, bridging traditional data centers and cloud workloads.

How firewalls protect against cyber threats

Firewalls serve as digital gatekeepers, but the ways they handle malware, unauthorized access, and phishing differ depending on their capabilities.

Preventing malware and ransomware attacks

Malware typically arrives via infected attachments, compromised websites, or direct exploitation of network protocols. A firewall may block known malicious domains, break suspicious connections, or rely on integrated antivirus or threat intelligence to filter out harmful files.

With next-generation or UTM firewalls, traffic is inspected deeper so the system can detect unusual payloads or suspicious encryption. If a process or file acts strangely—like trying to reach an untrusted server—the firewall can suspend or terminate the session, halting the spread of threats such as ransomware.

Stopping unauthorized access attempts

Hackers often run automated scans to find open ports or guess weak credentials. A firewall, especially one using stateful inspection, lets you close off unnecessary ports and block repeated failed login attempts.

When suspicious activity repeats from a certain source, you can blacklist that IP or range. This containment strategy is crucial in preventing brute-force attacks and infiltration attempts aimed at your devices.

Blocking phishing and social engineering attempts

Phishing emails or links often trick you into visiting malicious sites or downloading harmful content. Some firewall setups integrate with URL filtering or real-time threat feeds. The firewall denies access if a user tries to load a known phishing page.

This approach adds another layer beyond email filters and antivirus. It doesn’t solve user-targeted trickery on its own, but it helps curb attempts that involve recognized phishing domains or suspicious traffic patterns.

Common firewall deployment use cases

Your reasons for installing or upgrading a firewall may vary based on environment size and the kinds of data you manage. Here are some scenarios that highlight a firewall’s value.

Firewalls for personal use

Home users usually rely on the firewall built into their operating system or router. This basic solution is enough for many households. It blocks unsolicited inbound connections and can prompt you to approve or deny outgoing connections from applications.

If you perform sensitive online tasks—banking, telehealth, investing—stronger personal solutions exist, such as advanced firewall software with content filtering or deeper network control. A VPN paired with the home firewall can protect your traffic from third parties.

Firewalls for businesses and enterprises

Companies protect vital data with a combination of hardware, software, and cloud-based firewalls. They also segment the internal network, so even if one department is compromised, it’s harder for attackers to jump to another.

Businesses often choose next-generation or UTM setups or run multiple specialized firewalls (like WAFs for online portals or AI-based intrusion detection for an R&D department). The typical enterprise environment also includes:

  • Remote access: The firewall can handle secure VPNs for traveling employees.
  • Application controls: Restrict who or what uses certain cloud services.
  • High availability clustering: Redundant firewall appliances, ensuring no single failure takes the entire network offline.

Many advanced solutions unify these capabilities into a “hybrid mesh” approach, where physical, virtual, and cloud-based firewalls share intelligence and policies.

Firewalls for cloud security

Organizations increasingly host data and applications in third-party clouds such as AWS, Azure, or Google Cloud. This shift leads to cloud-native and virtual firewalls that protect workloads in remote data centers.

With a cloud firewall, traffic from the internet or from other parts of the same cloud passes through scanning layers that block malicious requests. Some are offered directly by the cloud provider, while others are from third-party vendors who specialize in security.

Because cloud environments scale quickly, a cloud-based firewall can auto-scale in parallel, which helps handle traffic spikes without creating choke points.

Best practices for firewall security

Owning a firewall is only part of the solution. You also want to configure it properly, review logs, and make sure everything is updated. Below are suggestions for maintaining your firewall and keeping it relevant to your evolving needs.

Setting up the right firewall rules

A firewall rule is a condition that determines how traffic is handled. For instance, “Allow inbound traffic on port 443 if it originates from these trusted IP addresses.” Overly lax rules can let intruders in, while overly strict rules might disrupt normal business.

Read more: What is port 443?

When creating or editing policies, follow a “deny by default” philosophy. This approach ensures you only open the ports and protocols you truly need. Group similar policies together and document the reason behind each one. That helps you avoid confusion later about why a particular rule was introduced.

Keeping your firewall software up to date

Vendors release patches and updates to fix bugs and close security holes. Skipping these updates leaves you exposed. Plan to apply updates consistently, whether you have a hardware appliance, virtual instance, or software-based firewall.

  • Turn on automatic updates if possible.
  • Subscribe to vendor advisories about security vulnerabilities.
  • Follow standard change-control procedures if you’re in a corporate environment, testing critical patches before applying them to production.

Regularly auditing firewall logs and policies

A firewall generates logs of accepted and rejected traffic. By checking logs, you can see suspicious patterns like repeated attempts to access closed ports or big surges of blocked requests from a certain region.

Policies also need periodic audits. Perhaps you opened a port for a temporary test a year ago and forgot to remove it. That old rule might create an unexpected hole in your defenses. Routine reviews help clean out stale rules and keep your firewall lean and efficient.

Firewalls vs. other security solutions: What’s the difference?

Firewalls, antivirus software, VPNs, and intrusion detection systems address different layers of cybersecurity. They often work best in tandem, rather than one replacing the other. Below are some quick comparisons to clarify their roles.

Firewall vs. antivirus—what’s the difference?

  • Firewall: Monitors and filters network traffic. It blocks suspicious data before it reaches your system.
  • Antivirus: Looks for malicious files or processes on your system. It removes or quarantines harmful software once it’s downloaded or running.

They solve different but overlapping concerns. A firewall tries to prevent malicious data from arriving, while an antivirus cleans up anything that sneaks past or enters through alternative means (such as a USB drive or legitimate software that’s later hijacked).

Firewall vs. VPN—Do you need both?

  • Firewall: Decides whether to let connections proceed or block them, focusing on rules and threat detection.
  • VPN: Creates an encrypted tunnel to protect your data from third parties. By hiding your IP address and encrypting your traffic, it boosts your online privacy.

Because a VPN secures your data’s path, it doesn’t automatically stop malicious software from arriving. Meanwhile, a firewall doesn’t encrypt or disguise your connections. Pairing both can give you strong privacy (via VPN) and strong perimeter control (via firewall).

Firewall vs. intrusion detection system (IDS)

  • Firewall: Blocks or allows traffic based on pre-set or adaptive rules.
  • IDS: Monitors traffic passively. It sends alerts when it finds something suspicious, but it might not block that traffic automatically.

Some next-generation setups include an Intrusion Prevention System (IPS), which takes IDS data and uses it to stop malicious connections in real time. A firewall with IPS capabilities merges the strengths of both approaches.

How firewalls and VPNs work together for online security

A firewall decides which data enters or leaves your network, and a VPN encrypts your data so no one else can read it in transit. Together, they provide a strong shield for remote work, traveling employees, and public hotspots.

When employees use a VPN to connect to corporate resources, the firewall at the main office enforces rules on all inbound requests. This layering means an attacker trying to intercept the connection sees only encrypted data, and the firewall remains in control of the gateway to internal services.

Can a firewall block a VPN?

Yes, a firewall might stop VPN traffic if it’s configured to block the ports or protocols your VPN uses. Some organizations do this intentionally, so employees connect only through an approved corporate VPN service. In other scenarios, certain countries block known VPN protocols to enforce censorship.

If you run into blocks, switching to a different VPN protocol might help bypass these restrictions. 

How a VPN bypasses firewall restrictions

A VPN can evade standard blocking by wrapping your connection in encryption that disguises the nature of your data. The firewall sees encrypted packets but can’t read their content. In places where strong censorship is active, stealth VPN features or custom ports help the traffic blend with regular HTTPS streams, making it tougher for the firewall to single them out.

Do you need a firewall if you use a VPN?

Firewalls and VPNs address different security needs. A VPN hides and encrypts your traffic, but it won’t examine or block malicious data by itself. Firewalls filter out unwanted connections but don’t encode your data or mask your IP. Running both is ideal for many users.

Firewall limitations: What they can’t protect you from

Though firewalls are an essential layer of security, they aren’t a catch-all. You can still fall victim to certain ploys if you rely on a firewall alone.

Can firewalls be bypassed?

Advanced attackers sometimes tunnel malicious data through allowed ports or disguise it within protocols your firewall trusts. Social engineering can also lead users to open a channel themselves, letting intruders piggyback on permitted traffic. If criminals get hold of valid login credentials, a firewall might treat them as an authorized user.

Common firewall misconfigurations

Misconfigurations remain a top reason for breaches:

  • Unrestricted outbound rules: You trust all outbound traffic, so a compromised system can freely send stolen data away.
  • Forgotten open ports: Temporary test rules remain open long after they’re needed.
  • Poorly managed firmware: Out-of-date software or default credentials create easy exploitation paths.

Routine reviews and consistent management guard against these errors.

Why firewalls alone are not enough for cybersecurity

A firewall can’t stop physical access attacks or remove malware already on a device. It also doesn’t inherently prevent users from falling for phishing or handing out passwords. A strong cybersecurity plan includes:

  • Endpoint protection: Antivirus, anti-ransomware, and patch management.
  • Regular backups: To restore files if they become compromised.
  • Network segmentation: Additional internal firewalls that isolate sections of your environment.
  • Security awareness training: Helps users recognize suspicious links or attachments.

How to strengthen your firewall against attacks

You can boost firewall effectiveness in several ways:

  1. Enable intrusion prevention: Let the firewall block threats proactively if it spots known attack patterns.
  2. Deploy sandboxing: Suspicious files are opened in a closed environment to see if they behave maliciously.
  3. Use segmented zones: Restrict high-value servers behind specialized firewall layers.
  4. Adopt zero-trust principles: Verify and authenticate every user or device trying to access resources.

Combine these technical measures with user training and regular policy reviews.

Wrapping up

Firewalls have developed significantly from simple packet filters to advanced AI-driven guardians that handle multi-vector intrusions. While they’re still a core pillar of network security, they’re not a one-stop fix.

Even the best-configured firewall can’t solve every security challenge on its own. Attackers may bypass it through social engineering, weak passwords, or overlooked configuration gaps. Regular reviews, firmware updates, and a zero-trust mindset help strengthen your defenses. With the right blend of tools, policies, and vigilance, a firewall can go a long way in keeping your digital environment safer.

FAQs about firewalls

What is the purpose of a firewall?

How does a firewall protect a computer?

What are the main types of firewalls?

Do I need a firewall if I already have an antivirus?

Can a firewall block hackers completely?

What’s the best firewall for home use?

How do cloud firewalls work?

How do I set up a firewall for my business?

How do I choose the right firewall for my needs?

Phone protected by ExpressVPN.
Protect your online privacy and security

30-day money-back guarantee

A phone with a padlock.
We take your privacy seriously. Try ExpressVPN risk-free.What is a VPN?
Chantelle writes about technology, cybersecurity, law and SaaS. Having spent a decade in corporate law and five years teaching at University, she now enjoys a freelance life doing what she loves—working with words and learning something new every day.