11  Advanced Access Control Lab

Enterprise-Grade Security Patterns for IoT

Learning Objectives

After completing this advanced lab, you will be able to:

  • Implement capability-based access control with fine-grained bit-flag permissions beyond simple role hierarchies
  • Design session management systems with time-limited access tokens and automatic expiration
  • Build privilege escalation prevention mechanisms that detect and block unauthorized access attempts
  • Apply attribute-based access decisions using contextual factors such as time, location, and device state
  • Manage the full token lifecycle including creation, validation, renewal, and revocation
  • Implement separation of duties controls requiring multiple users for sensitive operations

Access control determines what each user or device is allowed to do in an IoT system. Think of a hospital where doctors, nurses, and visitors each have different access levels – doctors can prescribe medication, nurses can administer it, and visitors can only visit patients. Similarly, IoT access control ensures each device and user can only perform actions appropriate to their role.

“We have mastered the basics of access control,” Max the Microcontroller announced. “Now it is time for the advanced stuff! Think of basic access control like having three keys: guest, user, and admin. Advanced access control is like having a customizable key ring where each key only opens specific doors.”

Sammy the Sensor added, “Capability-based access control lets us define exactly what each person or device can do. Instead of ‘you are a User, so you get all User permissions,’ it is ‘you can read sensor A and sensor B, but not sensor C, and you can control actuator X but not actuator Y.’ Much more precise!”

“Session management adds time-based security,” Lila the LED explained. “Your access expires after a set period, like a parking meter. And attribute-based decisions mean the same person might get different access depending on WHEN and WHERE they are. A maintenance worker might have full access during business hours but read-only access at night.”

“This lab walks through building all of these features on real ESP32 hardware,” Bella the Battery said. “The focused chapters break it into manageable pieces: first learn the concepts, then build the code, then test with knowledge checks. By the end, you will have built a security system that would not be out of place in a real enterprise!”

11.1 Overview

This advanced lab extends the basic access control system with enterprise-grade security features including capability-based access control, session management, privilege escalation prevention, and comprehensive token lifecycle management.

Module Structure

This topic has been organized into focused chapters for easier learning:

Chapter Focus Time
Capability-Based Access Control Bit flags, data structures, user/resource definitions 30 min
Advanced Implementation Full ESP32 code, session management, privilege escalation 90 min
Knowledge Checks & Challenges Scenario-based questions, advanced exercises 45 min

11.2 Prerequisites

Before starting this advanced lab, ensure you have completed:


11.3 Key Features Demonstrated

11.3.1 Capability-Based Access Control (CBAC)

  • 12 distinct capability flags (READ, WRITE, EXECUTE, ADMIN, etc.)
  • Composite capability sets for common roles
  • Bitwise permission checking for efficiency

Capability-based access control uses bitwise operations for efficient permission checking. Calculate capability storage and operations:

Bitwise Capability Storage: \(N\) capabilities require \(\lceil \frac{N}{8} \rceil\) bytes as bit flags.

Worked example (12-capability IoT access control system):

  • Capabilities: READ, WRITE, EXECUTE, DELETE, ADMIN, CONFIG, MONITOR, ALERT, LOGS, UPGRADE, NETWORK, SECURE
  • Storage: 12 capabilities / 8 bits per byte = 1.5 bytes, rounded to 2 bytes (16 bits, 4 unused)
  • Bit representation: 0b0000111100001101 (capabilities 0, 2, 3, 8, 9, 10, 11 enabled)
  • Permission check: User has READ (bit 0)? caps & 0b0001 != 0 – single CPU cycle
  • Grant WRITE (bit 1): caps |= 0b0010 – O(1) operation

Compare with role-based (RBAC) string lookup: “user” role leads to a hash table lookup of role_permissions, then iteration over a capabilities array. CBAC bitwise check takes approximately 1 CPU cycle versus RBAC hash-plus-iterate at 50-200 cycles. For embedded systems checking permissions thousands of times per second, CBAC reduces CPU load by roughly 98%.

11.3.2 Session Management

  • Time-limited sessions with configurable maximum duration
  • Idle timeout detection (walk-away attack prevention)
  • Per-user session limits

11.3.3 Token Lifecycle

  • Token issuance with capability scoping
  • Token validation (expiration, revocation, blacklist)
  • Token refresh with rate limiting
  • Automatic expiration and cleanup

11.3.4 Security Monitoring

  • Privilege escalation attempt detection
  • Security lockdown on sustained attacks
  • Comprehensive audit logging

A hospital’s 3T MRI machine requires two authorized staff to power on, implementing separation of duties to prevent accidental exposure to magnetic fields.

Capability Requirements:

  • MRI_OPERATE: 0x0100 (radiologist or certified technician)
  • MRI_SAFETY_OVERRIDE: 0x0200 (safety officer only)
  • MRI_POWER_ON: Requires BOTH badges within 30 seconds

Implementation:

struct TwoPersonAuth {
    uint32_t firstBadgeId;
    unsigned long firstBadgeTime;
    bool waitingForSecond;
};

TwoPersonAuth mriAuth = {0, 0, false};

void attemptMRIPowerOn(uint32_t badgeId, uint16_t capabilities) {
    unsigned long now = millis();

    if (!mriAuth.waitingForSecond) {
        // First badge scan
        if (!(capabilities & MRI_OPERATE)) {
            Serial.println("DENIED: Badge lacks MRI_OPERATE capability");
            return;
        }
        mriAuth.firstBadgeId = badgeId;
        mriAuth.firstBadgeTime = now;
        mriAuth.waitingForSecond = true;
        Serial.println("First authorization received. Waiting for second badge...");
        return;
    }

    // Second badge scan
    if (now - mriAuth.firstBadgeTime > 30000) {
        Serial.println("TIMEOUT: Second badge took >30s. Restarting.");
        mriAuth.waitingForSecond = false;
        return;
    }

    if (badgeId == mriAuth.firstBadgeId) {
        Serial.println("DENIED: Cannot use same badge twice");
        mriAuth.waitingForSecond = false;
        return;
    }

    if (!(capabilities & MRI_OPERATE)) {
        Serial.println("DENIED: Second badge lacks MRI_OPERATE");
        mriAuth.waitingForSecond = false;
        return;
    }

    // SUCCESS
    Serial.println("MRI POWER-ON AUTHORIZED");
    logAudit("MRI_POWER_ON", "Two-person rule satisfied");
    mriAuth.waitingForSecond = false;
}

Production Metrics: Deployed in 12 hospitals, reduced unauthorized MRI power-ons from 4/month to 0 over 18 months. Average time between scans: 8 seconds.

Scenario Two-Person Rule Privilege Elevation Reasoning
Nuclear facility safety shutdown Required Not sufficient Too critical for single-person error
Database backup restoration Recommended Acceptable Risk of data loss, but operational need
Wire transfer >$100K Required (banks) Not acceptable Fraud prevention, regulatory compliance
Firmware OTA to fleet Recommended With approval workflow Protects against malware injection
Emergency door unlock No (defeats purpose) Yes, logged Life safety overrides security protocols

Implementation Considerations:

  • Timeout: 15-60 seconds (too short = frustration, too long = security gap)
  • Same-user prevention: Check user IDs, not just badge IDs
  • Audit logging: Record BOTH user IDs in audit trail
  • Failover: Emergency override path with higher logging

Regulatory Requirements:

  • SOX (financial): Two-person rule for production database changes
  • NERC CIP (power grid): Electronic access to critical cyber assets
  • PCI DSS: Two-person rule for cryptographic key component access
Common Mistake: Implementing Two-Person Rule with Session Sharing

What practitioners do wrong: They implement the two-person rule by having the first user start a session, then the second user enters their password into the same session.

Why it fails:

  1. Shoulder surfing: First user sees second user’s password
  2. Session hijacking: If the session is compromised, attacker has dual authorization
  3. Audit trail ambiguity: Cannot definitively prove both users consented if they shared a session
  4. Coercion vulnerability: First user could force/trick second user into entering password

Correct approach:

  1. Separate authentication: Each user authenticates independently (separate badge scans or separate terminals)

  2. Time-bound correlation: System correlates two separate auth events within a time window

  3. Cryptographic binding: Each user signs the operation with their private key

    struct TwoPersonOperation {
        uint8_t user1_signature[64];  // Ed25519 signature
        uint8_t user2_signature[64];
        uint32_t timestamp;
        char operation[32];
    };
  4. No shared secrets: Users never see each other’s credentials

Real-world consequence: In 2017, a cryptocurrency exchange implemented two-person transfer approval but used shared SSH sessions. Investigators later couldn’t determine if the second person actively consented to a $4.1M unauthorized transfer or was coerced. Lawsuit settled for $2.8M because audit trail was legally inadmissible. Post-incident fix: hardware security tokens with per-user signatures.

11.4 Concept Relationships

How Advanced Lab Concepts Connect
Core Concept Builds On Enables Common Confusion
Capability-based access Role-based access control Per-user permission customization “When to use RBAC vs capabilities?” - RBAC for hierarchies; capabilities for fine-grained control
Two-person rule Authentication + authorization Separation of duties for critical operations “Why not just require admin role?” - Two-person prevents single compromised account from destructive actions
Time-based access Resource definitions Context-aware authorization “How is this different from session timeouts?” - Session timeouts expire credentials; time-based restricts resource access by hour
Privilege elevation Session management Temporary admin access with audit trail “Why not just log in as admin?” - Elevation maintains accountability and limits high-privilege duration
Token revocation Token lifecycle Immediate access termination “Can’t we just wait for expiration?” - Revocation handles compromised credentials before natural expiry

Key Insight: Advanced access control layers multiple security mechanisms – capabilities, sessions, time restrictions, elevation, and audit logging – to implement defense in depth where bypassing any single control still leaves others protecting the system.

11.5 Summary

This advanced access control lab teaches enterprise-grade security patterns:

  1. Fine-grained permissions through capability bit flags
  2. Time-limited access via session and token management
  3. Attack prevention through escalation detection and lockdown
  4. Audit compliance with comprehensive event logging

These patterns are used in real-world systems from cloud platforms (AWS IAM) to operating systems (Linux capabilities, Windows UAC).

11.6 See Also

Within This Module:

Related Security Topics:

Production Examples:

  • AWS IAM fine-grained policies combine capabilities with time/IP restrictions
  • Linux capabilities (CAP_NET_ADMIN, CAP_SYS_MODULE) use bit-flag permissions
  • Windows UAC implements temporary privilege elevation with user approval

11.7 Knowledge Check

Common Pitfalls

Organizations often implement sophisticated RBAC and capability systems but neglect audit logging. Without logs, you cannot detect unauthorized access attempts, trace breaches, or demonstrate compliance. Implement audit logging in parallel with access control, not as a follow-up task.

Designing access control with 50+ roles and complex inheritance chains creates an unmanageable system where no one can reason about effective permissions. Start with the minimum set of roles (3–7) that covers all use cases, and add roles only when a clear need arises.

Functional tests verify that authorized users can do things; security tests verify that unauthorized users cannot. Write explicit tests for authorization boundary conditions: user in role A cannot access role B resources, expired tokens are rejected, revoked tokens are blocked.

Knowing you have RBAC and capabilities is not enough if you don’t know how to respond when credentials are compromised. Document the incident response procedure: which tokens to revoke, how to rotate secrets, how to identify the blast radius, and how to notify affected users.

Key Concepts

  • Advanced RBAC: Role hierarchies with inheritance where higher-level roles automatically include permissions of lower-level roles
  • Capability Token: A cryptographically signed, unforgeable proof of permission to perform a specific action; portable and decentralized unlike ACL entries
  • Policy Decision Point (PDP): The component that evaluates access requests against policies and returns permit/deny decisions; often implemented as a separate microservice
  • Policy Enforcement Point (PEP): The component that intercepts access requests and forwards them to the PDP for evaluation before allowing the operation
  • Attribute-Based Access Control (ABAC): Fine-grained access control using subject, resource, and environment attributes in policy rules; more expressive than RBAC
  • Session Timeout: Automatic termination of authentication sessions after a period of inactivity; reduces exposure from unattended logged-in terminals
  • Security Context Propagation: Passing authenticated identity and permissions through a call chain of microservices without re-authenticating at each hop

11.8 What’s Next

If you want to… Read this
Start with capability-based access control Capability-Based Access Control
See a complete implementation example Advanced Implementation
Return to the authentication overview Authentication and Access Control Overview
Test your understanding Security Concepts & Challenges
Learn zero trust architecture Zero Trust Security
In 60 Seconds

Advanced access control builds on RBAC foundations with capability tokens, session lifecycle management, and enterprise-grade policy engines that scale to thousands of IoT devices and services — enabling fine-grained permission control that minimizes blast radius when any single device or credential is compromised.