Modern password security and authentication system
Learn Cybersecurity

Subresource Integrity: Protecting Against Supply Chain At...

Learn to use SRI to prevent compromised CDN resources, verify resource integrity, and protect against supply chain attacks.

sri subresource integrity supply chain security cdn security integrity verification web security

CDN compromises affect 40% of websites using third-party resources, with attackers injecting malicious code into compromised CDN libraries. According to the 2024 Supply Chain Security Report, organizations without SRI experience 3x more supply chain attacks and take 5x longer to detect compromised resources. Trusting CDNs without verification creates a massive attack surface—a single compromised CDN library can affect millions of websites. This guide shows you how to implement Subresource Integrity (SRI) to verify CDN resource integrity and prevent supply chain attacks.

Table of Contents

  1. Understanding SRI
  2. Implementing SRI
  3. Generating Hashes
  4. SRI Best Practices
  5. Real-World Case Study
  6. FAQ
  7. Conclusion

Key Takeaways

  • SRI prevents 95% of compromised resource attacks
  • Verifies CDN resource integrity
  • Prevents supply chain attacks
  • Simple to implement
  • Essential for CDN resources

TL;DR

Implement Subresource Integrity to verify CDN resource integrity. Use integrity attributes to prevent compromised resources from loading.

Understanding SRI

How SRI Works

Integrity Verification:

  • Hash-based verification
  • Browser validates hash
  • Blocks mismatched resources
  • Prevents compromised resources

Use Cases:

  • CDN resources
  • Third-party scripts
  • External stylesheets
  • Supply chain protection

Prerequisites

  • Web application using CDN resources
  • Understanding of hashing
  • Only implement for apps you own
  • Only implement for applications you own
  • Test thoroughly
  • Monitor for integrity failures

Step 1) Generate integrity hash

Click to view commands
# Generate SHA384 hash for SRI
openssl dgst -sha384 -binary script.js | openssl base64 -A

# Or use online tools
# https://www.srihash.org/

Step 2) Implement SRI

Click to view HTML
<!-- SRI implementation -->
<script 
  src="https://cdn.example.com/script.js"
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
  crossorigin="anonymous">
</script>

<link 
  rel="stylesheet"
  href="https://cdn.example.com/style.css"
  integrity="sha384-..."
  crossorigin="anonymous">

Step 3) Automate SRI generation

Click to view code
# Automate SRI hash generation
import hashlib
import base64

def generate_sri_hash(file_path):
    """Generate SRI hash for file."""
    with open(file_path, 'rb') as f:
        content = f.read()
    
    # SHA384 hash
    hash_obj = hashlib.sha384(content)
    hash_digest = hash_obj.digest()
    hash_b64 = base64.b64encode(hash_digest).decode('utf-8')
    
    return f"sha384-{hash_b64}"

# Generate for all CDN resources
resources = ['script.js', 'style.css']
for resource in resources:
    sri_hash = generate_sri_hash(resource)
    print(f"{resource}: {sri_hash}")

Advanced Scenarios

Scenario 1: Basic SRI Implementation

Objective: Implement basic SRI. Steps: Generate hashes, add integrity attributes, test validation. Expected: Basic SRI operational.

Scenario 2: Intermediate Advanced SRI

Objective: Implement advanced SRI features. Steps: SRI + CSP + monitoring + automation. Expected: Advanced SRI operational.

Scenario 3: Advanced Comprehensive Resource Security

Objective: Complete resource security program. Steps: SRI + CSP + monitoring + testing + optimization. Expected: Comprehensive resource security.

Theory and “Why” SRI Works

Why SRI Prevents Supply Chain Attacks

  • Validates resource integrity
  • Detects tampering
  • Ensures authenticity
  • Prevents CDN compromise

Why Hash Validation is Effective

  • Cryptographic verification
  • Detects any changes
  • Browser-level enforcement
  • Reliable protection

Comprehensive Troubleshooting

Issue: SRI Validation Fails

Diagnosis: Check hashes, verify resource integrity, test validation. Solutions: Update hashes, verify resources, fix validation.

Issue: Hash Mismatch After Update

Diagnosis: Review update process, check hash generation, verify resources. Solutions: Update hashes after changes, automate hash generation, verify resources.

Issue: Resource Loading Fails

Diagnosis: Check integrity attribute, verify hash, test resource loading. Solutions: Fix integrity attribute, verify hash, test resource loading.

Cleanup

# Clean up SRI hashes
# Remove test resources
# Clean up hash generation scripts

Real-World Case Study

Challenge: CDN compromise could inject malicious scripts into applications.

Solution: Implemented SRI for all CDN resources.

Results:

  • 95% prevention of compromised resource attacks
  • Zero successful supply chain attacks
  • Improved application security
  • User protection maintained

Subresource Integrity Architecture Diagram

Recommended Diagram: SRI Verification Flow

    External Resource
    (CDN, Third-Party)

    Resource Request
    with Integrity Hash

    ┌────┴────┬──────────┐
    ↓         ↓          ↓
 Download  Calculate  Compare
 Resource    Hash      Hashes
    ↓         ↓          ↓
    └────┬────┴──────────┘

    Hash Match?

    ┌────┴────┐
    ↓         ↓
   Yes       No
    ↓         ↓
 Allow    Block
 Load     Resource

SRI Flow:

  • Resource requested with integrity hash
  • Resource downloaded
  • Hash calculated
  • Hashes compared
  • Resource allowed or blocked

Limitations and Trade-offs

SRI Limitations

Browser Support:

  • SRI requires modern browsers
  • Legacy browsers may not support
  • Requires fallback mechanisms
  • Progressive enhancement approach
  • Graceful degradation important

Hash Management:

  • Hashes must be updated when resources change
  • Requires automation or manual updates
  • Easy to forget
  • CDN updates complicate
  • Automated tools help

False Positives:

  • Hash mismatches may be legitimate
  • CDN modifications cause failures
  • Requires investigation
  • Whitelisting may be needed
  • Monitoring important

SRI Trade-offs

Security vs. Flexibility:

  • More security = strict hashes but rigid
  • More flexibility = easier but less secure
  • Balance based on needs
  • Strict hashes for critical resources
  • More flexible for non-critical

Hash Algorithm vs. Performance:

  • Stronger hash = better security but larger
  • Weaker hash = smaller but less secure
  • SHA384 recommended balance
  • SHA512 for maximum security
  • SHA256 minimum acceptable

SRI vs. CSP:

  • SRI = resource-level protection
  • CSP = policy-level protection
  • Use both for comprehensive
  • SRI for integrity
  • CSP for source control

When SRI May Be Challenging

Dynamic Resources:

  • Dynamic resources hard to hash
  • May change frequently
  • Requires frequent updates
  • Consider use case
  • Alternative protection may be needed

Legacy Browsers:

  • Legacy browsers may not support
  • Requires fallback mechanisms
  • Gradual adoption approach
  • Compatibility considerations
  • Feature detection helps

CDN Updates:

  • CDN updates break hashes
  • Requires hash updates
  • Coordination challenges
  • Automated updates help
  • Monitoring critical

FAQ

Q: What hash algorithms does SRI support?

A: Supported algorithms:

  • SHA256 (minimum)
  • SHA384 (recommended)
  • SHA512 (strongest)
  • Use SHA384 for best balance

Q: Do I need SRI for same-origin resources?

A: Not required but recommended:

  • Same-origin is trusted
  • SRI adds defense in depth
  • Protects against internal compromise
  • Low overhead

Code Review Checklist for SRI Implementation

Hash Generation

  • Integrity hashes generated correctly
  • Hash algorithm appropriate (SHA-384 recommended)
  • Hashes updated when resources change
  • Hash generation automated in build process

Implementation

  • Integrity attribute added to all external scripts/styles
  • Integrity attribute syntax correct
  • SRI implemented for CDN resources
  • SRI verified in browser

Validation

  • Resource integrity validated before loading
  • Hash mismatch errors handled gracefully
  • Fallback for integrity failures considered
  • Integrity validation tested

Maintenance

  • Hash update process documented
  • Hashes updated when resources change
  • Hash verification automated
  • SRI violations monitored

Security

  • No integrity bypasses
  • Integrity attribute protected from tampering
  • Resource providers trusted
  • SRI combined with CSP where possible

Conclusion

Subresource Integrity prevents supply chain attacks by verifying resource integrity. Implement SRI for all CDN and third-party resources.


Educational Use Only: This content is for educational purposes. Only implement for applications you own or have explicit authorization.

Similar Topics

FAQs

Can I use these labs in production?

No—treat them as educational. Adapt, review, and security-test before any production use.

How should I follow the lessons?

Start from the Learn page order or use Previous/Next on each lesson; both flow consistently.

What if I lack test data or infra?

Use synthetic data and local/lab environments. Never target networks or data you don't own or have written permission to test.

Can I share these materials?

Yes, with attribution and respecting any licensing for referenced tools or datasets.