Course contentsShow
← Security
Lesson 1208 of 3,05225. Application Security - Secure CodingFree lesson

Principle of Least Privilege in Code

Run code with minimum necessary permissions and avoid elevated privileges unless absolutely required.

Principle of Least Privilege in Code

What you'll learn: How to minimize the permissions your code runs with to limit damage when things go wrong.

The Core Idea

The Principle of Least Privilege means your code should run with only the bare minimum permissions it needs to do its job—nothing more. This limits the blast radius if an attacker exploits a vulnerability or if your code has a bug.

Think of it like giving a delivery driver access only to your building's lobby, not keys to every apartment. If something goes wrong, the damage is contained.

Why This Matters

When code runs with excessive privileges (like root/admin access), a single exploit can compromise your entire system. An attacker who hijacks overprivileged code can:

  • Read sensitive files they shouldn't access
  • Modify system configurations
  • Install malware
  • Pivot to other systems

By running with minimal permissions, you create barriers. Even if one part fails, the attacker gains limited access.

Practical Application

Avoid elevated privileges by default:

  • Don't run web servers as root/Administrator
  • Use dedicated service accounts with restricted permissions
  • Drop privileges after startup if elevated access was needed briefly
  • Separate read-only operations from write operations

Apply least privilege to:

  • File system access (read/write/execute only what's necessary)
  • Database connections (use accounts with minimal grants)
  • Network access (restrict ports and destinations)
  • API access (scoped tokens, not admin keys)

The Security Boundary

This principle builds on trust boundaries you've learned: code crossing boundaries (like handling user input) should operate with even stricter limits, since that's where attacks enter.

Key Takeaway: Always run code with the minimum permissions required for its specific task. If compromised, restricted permissions dramatically limit an attacker's ability to cause harm.