Worked example: With 5 runs and per-run times of 4 min setup, 6 min execution, and 3 min review, total lab time is \(5\times(4+6+3)=65\) minutes. This prevents under-scoping and helps schedule complete experimental cycles.
Show code
viewof labRuns = Inputs.range([1,20], {value:5,step:1,label:"Number of runs"})viewof setupTime = Inputs.range([1,15], {value:4,step:1,label:"Setup time (min)"})viewof runTime = Inputs.range([1,30], {value:6,step:1,label:"Execution time (min)"})viewof reviewTime = Inputs.range([1,15], {value:3,step:1,label:"Review time (min)"})
Show code
{const perRun = setupTime + runTime + reviewTime;const total = labRuns * perRun;const hours =Math.floor(total /60);const mins = total %60;const timeStr = hours >0?`${hours} hr ${mins} min`:`${mins} min`;returnhtml`<div style="background: #f0f7f4; border-left: 4px solid #16A085; padding: 12px 16px; border-radius: 4px; font-size: 1.05em; margin-top: 8px;"> <strong>Estimated total lab time:</strong> ${labRuns} runs x (${setupTime} + ${runTime} + ${reviewTime}) min = <strong>${total} min (${timeStr})</strong> </div>`;}
20.1 Learning Objectives
By completing this advanced lab, you will be able to:
Implement capability-based access control with fine-grained bit-flag permissions
Build session management with time limits and idle detection
Create token lifecycle management with issuance, refresh, and revocation
Implement privilege escalation prevention with detection and alerting
Design attribute-based access decisions including time restrictions
Complete challenge exercises extending the security system
For Beginners: Lab: Advanced Access Control
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.
This comprehensive implementation demonstrates enterprise-grade access control patterns. Copy all sections below in order into the Wokwi editor as a single file.
Add the ability for users with the GRANT capability to temporarily delegate a subset of their capabilities to another user:
Create a delegation token with source and target user IDs
Delegated capabilities cannot exceed the grantor’s current capabilities
Delegation expires when the grantor’s session ends
Log all delegation events for audit trail
Challenge 2: Add Attribute-Based Conditions
Extend the access control system with attribute-based conditions:
Device location (indoor/outdoor/restricted area)
Network connection type (WiFi/cellular/wired)
Device health status (normal/degraded/compromised)
Combine multiple attributes using AND/OR logic
Challenge 3: Implement Separation of Duties
For critical operations (firmware update, user deletion), require approval from two different administrators:
First admin initiates the operation
System waits for second admin approval (different user)
Both approvals must occur within a time window
Either admin can cancel the pending operation
Log the full approval chain
Challenge 4: Add Token Binding
Implement token binding to prevent token theft:
Bind tokens to device fingerprint (MAC address, hardware ID)
Validate binding on every token use
Alert on binding mismatch (possible token theft)
Allow secure token migration with re-binding
Challenge 5: Add Emergency Override
Implement an emergency mode for fire/evacuation:
Special “EMERGENCY” command unlocks all doors
All access restrictions temporarily disabled
Heavily logged with alert
Auto-reverts after 10 minutes or manual reset
Requires special admin confirmation
20.5 Expected Outcomes
After completing this advanced lab, you should be able to:
Concept
Demonstration
Real-World Application
Capability Flags
Fine-grained permission checking with bit operations
Linux file permissions, AWS IAM policies
Token Lifecycle
Issue, validate, refresh, revoke tokens
OAuth 2.0, JWT tokens
Session Management
Time-limited sessions with idle detection
Web applications, enterprise systems
Privilege Escalation Prevention
Detect and block unauthorized capability expansion
Unix sudo, Windows UAC
Time-Based Access
Restrict access to specific hours
Business hours policies, maintenance windows
Audit Logging
Complete security event trail
SIEM systems, compliance requirements
20.5.1 Interactive Capability Explorer
Use this tool to experiment with capability flag combinations from the lab code. Select individual capability bits to see the resulting bitmask and which predefined roles include those capabilities.
Worked Example: Implementing Privilege Escalation Detection in Production
Scenario: Your smart building management system has 500 operators and 20 administrators. You notice suspicious activity: operator accounts attempting admin-only firmware updates late at night.
Step 1: Analyze Attack Patterns
Week 1 Analysis:
- 47 escalation attempts from operator "op_clarke" at 2 AM - 4 AM
- Attempted capabilities: CAP_ADMIN_WRITE, CAP_FIRMWARE_UPDATE
- User's maximum: CAP_OPERATOR (lacks both capabilities)
- Pattern: 3-5 attempts per night, targeting firmware endpoints
Week 2: Same operator, different tactics
- Now attempting CAP_GRANT (trying to grant self admin rights)
- Using valid session but manipulating capability requests
- Rotating IP addresses (cloud proxies)
Step 2: Implement Detection Logic
// Detection thresholdsconstint ESCALATION_THRESHOLD =3;// Max attempts in windowconstunsignedlong ESCALATION_WINDOW =3600000;// 1 hourconstint LOCKOUT_DURATION =86400000;// 24 hoursbool detectEscalationAttack(Session* session,uint16_t attemptedCaps){ UserProfile* user = findUser(session->userId);if(user == NULL)returnfalse;// Check if attempting forbidden capabilitiesuint16_t forbidden = attemptedCaps &~user->maxCapabilities;if(forbidden ==0)returnfalse;// No forbidden capsunsignedlong now = millis();// Log the attempt logAudit(AUDIT_ESCALATION_ATTEMPT, session->userId,"SECURITY", attemptedCaps, session->currentCapabilities,false,"Forbidden capability bits detected");// Track first attempt time for window calculationif(escalationAttempts ==0) firstEscalationTime = now;// Update attack counter escalationAttempts++; lastEscalationTime = now;// Check if sustained attack (multiple attempts within time window)if(escalationAttempts >= ESCALATION_THRESHOLD &&(now - firstEscalationTime)< ESCALATION_WINDOW){// SECURITY LOCKDOWN Serial.println("\n!!! SUSTAINED ESCALATION ATTACK DETECTED !!!"); Serial.print("User: "); Serial.println(session->userId); Serial.print("Attempts: "); Serial.print(escalationAttempts); Serial.println(" in past hour");// 1. Lock account user->isActive =false;// 2. Revoke all sessions and tokens endAllUserSessions(session->userId);// 3. Alert security team sendSecurityAlert(session->userId,"PRIVILEGE_ESCALATION", escalationAttempts, forbidden);// 4. Log detailed forensics dumpSessionHistory(session->userId);returntrue;// Attack detected and handled}returnfalse;// Suspicious but below threshold}
Step 3: Forensic Analysis
After lockout, analyze the full attack:
Forensic Report - User: op_clarke (ID: OP_00147)
Timeline:
Jan 15, 02:14 AM: First escalation attempt (CAP_ADMIN_WRITE)
Jan 15, 02:31 AM: Second attempt (CAP_FIRMWARE_UPDATE)
Jan 15, 02:47 AM: Third attempt (CAP_GRANT)
Jan 15, 02:48 AM: Account locked (3 attempts in 34 minutes)
Attempted Capabilities:
Requested: CAP_ADMIN_WRITE | CAP_FIRMWARE_UPDATE | CAP_GRANT = 0x01C0
Maximum: CAP_OPERATOR = 0x00BF
Forbidden: 0x0100 (CAP_GRANT)
Network Analysis:
3 different source IPs (all Tor exit nodes)
User-Agent: curl/7.68.0 (automated script, not web browser)
TLS fingerprint: OpenSSL 1.1.1 (not standard browser)
Conclusion: Compromised operator credentials, automated privilege escalation script
Action: Forced password reset for all operators, MFA mandatory
Step 4: Response Metrics
Detection Performance:
Time to detect: 34 minutes (3 attempts)
Time to lockout: <1 second (automated)
Time to alert SOC: 5 seconds
False positives: 0 (legitimate users never request forbidden caps)
Attack Impact:
Systems compromised: 0 (prevented)
Data exfiltrated: 0 bytes
Firmware updates: 0 (blocked)
Downtime: 0 seconds
Remediation Time:
Account lockout: Immediate
Investigation: 2 hours
Credential reset: 500 operators, 24 hours
MFA rollout: 1 week
Key Decisions Made:
3-attempt threshold: Balance between catching attacks quickly and avoiding false positives from legitimate mistakes
1-hour window: Long enough to catch distributed attacks, short enough to respond quickly
Automatic lockout: Don’t wait for human approval (attacker may succeed in the meantime)
Revoke all sessions: Compromised user may have multiple active sessions
24-hour lockout: Gives security team time to investigate and remediate
Lessons Learned: The attacker had stolen operator credentials (phishing) and was running an automated script to escalate privileges. Without capability-based access control and escalation detection, the attack would have succeeded. The 34-minute detection time was acceptable given the automated response prevented any damage.
Decision Framework: When to Use RBAC vs CBAC vs ABAC
Choose the right access control model based on your IoT system requirements.
Factor
RBAC (Role-Based)
CBAC (Capability-Based)
ABAC (Attribute-Based)
Best For
Small-medium systems with stable roles
Systems needing fine-grained permissions
Dynamic, context-aware access decisions
Complexity
Low (5-10 roles typical)
Medium (10-20 capabilities)
High (policy engine required)
Performance
Excellent (simple role check)
Good (bit operations)
Moderate (policy evaluation overhead)
Flexibility
Low (adding roles requires code changes)
High (capabilities composable)
Very High (policy-driven)
Audit Trail
“User X (Admin role) accessed Y”
“User X used CAP_WRITE on resource Y”
“User X allowed by policy P1 at time T in zone Z”
Memory Footprint
Small (role enum per user)
Small (16-bit capability flags)
Large (policy engine + attributes)
Example Use Case
Office access control (3 roles: Guest, Employee, Admin)
Operating system (UNIX permissions, Windows ACLs)
Cloud IAM (AWS, Azure: combine role + tags + time + location)
Decision Tree:
Q1: Do you have more than 100 users?
NO → RBAC (simplicity wins)
YES → Continue to Q2
Q2: Do permissions change based on context (time, location, device state)?
YES → ABAC (context-aware decisions required)
NO → Continue to Q3
Q3: Do you need permissions more granular than role-level (e.g., "read sensor A but not sensor B")?
YES → CBAC (fine-grained control needed)
NO → RBAC (keep it simple)
Real-World Examples:
System
Model
Why
Smart Home (consumer)
RBAC
3 roles: Owner, Family, Guest. Simple, stable.
Smart Building (enterprise)
CBAC
Needs fine-grained control: “HVAC admin can write zone configs but not global settings.”
Smart City Platform
ABAC
Needs context: “Operators can control traffic lights ONLY in their assigned districts DURING work hours IF incident severity is HIGH.”
Industrial IoT
CBAC
Process engineers need read access to 1,000s of sensors but write access to only their assigned equipment. Capability flags scale better than roles.
Healthcare IoT
ABAC
HIPAA requires: Doctor can access patient records ONLY for patients under their care, ONLY from hospital network, WITH audit logs.
Common Mistake: Starting with RBAC, then adding “admin2,” “admin3,” “super_admin,” “operator_level_2” as requirements change. This is role explosion. If you have >10 roles, you probably need CBAC or ABAC instead.
Common Mistake: Token Refresh Without Rate Limiting
Mistake: Implementing token refresh without rate limiting allows attackers to extend compromised tokens indefinitely.
Vulnerable Code:
// BAD: No rate limiting on refreshbool refreshToken(AccessToken* token){if(token == NULL ||!validateToken(token))returnfalse;// Refresh the token (extends expiration) token->expiresAt = millis()+ TOKEN_LIFETIME; token->refreshCount++;returntrue;// SUCCESS!}
Attack Scenario:
Attacker steals a valid token (network interception, memory dump, etc.)
Token expires in 5 minutes
Attacker calls refreshToken() every 4 minutes
Token NEVER expires (refreshed indefinitely)
Attacker maintains access even after legitimate user logs out
Real-World Impact: In 2022, a smart building platform was compromised when an attacker stole an operator token and kept it alive for 9 months by refreshing it every hour. The legitimate operator had left the company 7 months earlier, but the token remained valid because there was no refresh limit or rate limiting.
Secure Implementation:
// GOOD: Rate limiting + maximum refresh countconstunsignedlong MIN_TOKEN_REFRESH_INTERVAL =60000;// 1 minute minimumconstint MAX_REFRESH_COUNT =5;// Token dies after 5 refreshesbool refreshToken(AccessToken* token){if(token == NULL ||!validateToken(token))returnfalse;// Check 1: Minimum time since last refreshif(millis()- token->lastRefreshTime < MIN_TOKEN_REFRESH_INTERVAL){ Serial.println("Token refresh denied: Too frequent"); logAudit(AUDIT_SUSPICIOUS_ACTIVITY, token->userId,"TOKEN",0,0,false,"Refresh rate limit exceeded");returnfalse;}// Check 2: Maximum refresh countif(token->refreshCount >= MAX_REFRESH_COUNT){ Serial.println("Token refresh denied: Max refreshes reached"); logAudit(AUDIT_SUSPICIOUS_ACTIVITY, token->userId,"TOKEN",0,0,false,"Max refresh count exceeded"); revokeToken(token);// Force re-authenticationreturnfalse;}// Check 3: Total token age (even with refreshes)unsignedlong tokenAge = millis()- token->issuedAt;if(tokenAge > MAX_TOKEN_AGE){ Serial.println("Token refresh denied: Too old (force re-auth)"); revokeToken(token);returnfalse;}// All checks passed - refresh the token token->expiresAt = millis()+ TOKEN_LIFETIME; token->refreshCount++; token->lastRefreshTime = millis(); logAudit(AUDIT_TOKEN_REFRESHED, token->userId,"TOKEN",0, token->capabilities,true,"Refresh successful");returntrue;}
Protection Mechanisms:
Protection
Purpose
Example Values
MIN_REFRESH_INTERVAL
Prevent rapid refresh attempts (rate limiting)
1 minute (60,000 ms)
MAX_REFRESH_COUNT
Force re-authentication after N refreshes
5 refreshes
MAX_TOKEN_AGE
Absolute maximum token lifetime (even with refreshes)
8 hours (28,800,000 ms)
Result:
Token Lifecycle with Protections:
Issue: 10:00 AM (expires 10:05 AM)
Refresh 1: 10:04 AM (expires 10:09 AM)
Refresh 2: 10:08 AM (expires 10:13 AM)
Refresh 3: 10:12 AM (expires 10:17 AM)
Refresh 4: 10:16 AM (expires 10:21 AM)
Refresh 5: 10:20 AM (expires 10:25 AM)
Refresh 6: 10:24 AM → DENIED (max refresh count)
User must re-authenticate at 10:24 AM
Maximum token lifetime: 25 minutes (with 5 refreshes)
Even if attacker steals token at 10:00 AM, it DIES at 10:25 AM
Testing Checklist:
Matching Quiz: Match Advanced Lab Components to Functions
Ordering Quiz: Order the Multi-Factor Lab Authentication Flow
Label the Diagram
💻 Code Challenge
20.6 Summary
By completing this advanced lab, you have:
Implemented capability-based access control with fine-grained bit-flag permissions
Built session management with time limits, idle detection, and privilege elevation
Created token lifecycle management including issuance, validation, refresh, and revocation
Implemented privilege escalation prevention with detection and security lockdown
Designed attribute-based access decisions including time-of-day restrictions
Built comprehensive audit logging for security forensics
Key Takeaway
Enterprise security requires defense in depth: authentication verifies identity, authorization checks permissions, and accounting tracks all activity. Add capability-based access for fine-grained control, time-limited tokens to reduce exposure, and escalation detection to prevent privilege abuse.
20.7 Knowledge Check
Quiz: Lab: Advanced Access Control
Common Pitfalls
1. Not Including JTI (JWT ID) Claim for Revocation
Without a unique JWT ID (JTI) claim in each token, the server cannot individually revoke a specific token without invalidating all tokens. Always include a random UUID as the JTI claim and maintain a revocation list.
2. Implementing Rate Limiting Only on Login, Not on All Sensitive Endpoints
Brute-force attacks target not just login but also password reset, account enumeration, and API key validation endpoints. Apply rate limiting to every sensitive endpoint, not just the primary login flow.
3. Logging Sensitive Data in Audit Logs
Audit logs that capture full request bodies may log credentials, PII, or confidential payload data. Design audit logging to capture authentication events (who, when, from where, what action) without including credential values or sensitive payload contents.
4. Using Symmetric Keys for Multi-Service JWT Validation
If multiple services need to validate JWTs, using HMAC with a shared secret means all services have access to the signing key — a compromise of any service exposes the key. Use RS256 (asymmetric RSA): the signing service holds the private key, all validating services have only the public key.
JWT Middleware: Server-side code that intercepts every request, validates the JWT signature and claims, and injects the decoded principal identity into the request context for use by handlers
RBAC Policy Enforcement: Code that checks the authenticated principal’s role against the required permissions for the requested resource and action before allowing the operation
Token Blacklist: A server-side store of invalidated token IDs (JTI claims); checked on every request to support revocation before token expiry
Refresh Token Rotation: Issuing a new refresh token each time the old one is used; a used refresh token that appears again signals possible token theft and should trigger immediate session revocation
Rate Limiting: Restricting the number of authentication attempts per time window per IP or account; prevents brute-force attacks on credentials
CORS Policy: Cross-Origin Resource Sharing headers that restrict which web origins can call the API; prevents unauthorized frontend applications from accessing the IoT API
Security Headers: HTTP response headers (HSTS, CSP, X-Frame-Options) that instruct browsers to apply additional security restrictions when displaying API responses
In 60 Seconds
This advanced lab implements production-grade access control with JWT authentication, RBAC middleware, short-lived session tokens, and audit logging — the complete combination of security controls needed for a real IoT management platform.