SECTION 1: LEARNING OBJECTIVES

By the end of this lesson, you will be able to:

  • Understand the importance of application security in digital banking.

  • Apply secure development lifecycle (SDL) practices.

  • Implement API security – authentication, authorisation, and rate limiting.

  • Understand DevSecOps and its role in banking.

  • Perform security testing – SAST, DAST, and penetration testing.

  • Implement secure coding practices for banking applications.

  • Measure application security using key metrics.

  • Develop an application security strategy for a digital bank.


SECTION 2: APPLICATION SECURITY IN BANKING

2.1 Why Application Security Matters
 
 
Reason Description
Data Protection Protect customer data from breaches.
Regulatory Compliance Meet PCI DSS, GDPR, and other requirements.
Reputation Prevent reputational damage from breaches.
Financial Loss Avoid losses from fraud and fines.
Customer Trust Maintain customer confidence.
2.2 Common Application Vulnerabilities
 
 
Vulnerability Description Banking Example
OWASP Top 10 Most critical web vulnerabilities. Injection, broken authentication, XSS.
Injection Attacks SQL injection, command injection. Data theft via SQL injection.
Broken Authentication Weak authentication mechanisms. Account takeover.
Sensitive Data Exposure Unprotected data. Customer data leaks.
API Vulnerabilities Insecure APIs. Unauthorised data access.
Insecure Dependencies Vulnerable libraries. Third-party vulnerabilities.
Misconfiguration Security misconfiguration. Exposed admin panels.

SECTION 3: SECURE DEVELOPMENT LIFECYCLE (SDL)

3.1 SDL Phases
text
┌─────────────────────────────────────────────────────────────────────────────┐
│                    SECURE DEVELOPMENT LIFECYCLE                           │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    REQUIREMENTS                                     │   │
│  │  Security requirements, threat modelling                            │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DESIGN                                           │   │
│  │  Security architecture, design review, threat modelling             │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DEVELOPMENT                                      │   │
│  │  Secure coding, code review, SAST                                   │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  └──────────────────────────────────────────────────────────────────────┘   │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    TESTING                                          │   │
│  │  DAST, penetration testing, security scanning                      │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DEPLOYMENT                                       │   │
│  │  Security configuration, hardening, monitoring                      │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    MAINTENANCE                                      │   │
│  │  Patching, monitoring, incident response                           │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

SECTION 4: API SECURITY

4.1 API Security Best Practices
 
 
Practice Description Implementation
Authentication Verify API caller identity. OAuth 2.0, OIDC, API keys.
Authorisation Control what callers can access. Scopes, RBAC, ABAC.
Rate Limiting Prevent abuse. Throttling, quotas.
Input Validation Validate all inputs. Schema validation, sanitisation.
Encryption Protect data in transit. TLS 1.3.
Monitoring Monitor API usage. Logging, analytics.
Versioning Manage API changes. Versioned endpoints.
Security Headers Use security headers. CSP, HSTS, CORS.
4.2 OAuth 2.0 in Banking
text
┌─────────────────────────────────────────────────────────────────────────────┐
│                    OAUTH 2.0 FLOW IN BANKING                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐                    │
│  │  Customer   │    │  Bank       │    │  Third-Party│                    │
│  │  (User)     │ ─→ │  (ASPSP)    │ ─→ │  Provider   │                    │
│  └─────────────┘    └─────────────┘    │  (TPP)      │                    │
│                                         └─────────────┘                    │
│                                                                             │
│  1. Customer consents to share data.                                       │
│  2. TPP requests access token.                                             │
│  3. Bank authenticates customer and validates consent.                    │
│  4. Bank issues access token.                                              │
│  5. TPP uses token to call bank APIs.                                     │
│  6. Bank validates token and returns data.                                │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

SECTION 5: DEVSECOPS

5.1 What is DevSecOps?

DevSecOps integrates security into the DevOps pipeline, ensuring security is built in from the start rather than added at the end.

5.2 DevSecOps Principles
 
 
Principle Description Implementation
Shift Left Move security earlier in the pipeline. SAST in development.
Automation Automate security testing. CI/CD security checks.
Continuous Security Security throughout the lifecycle. Continuous monitoring, scanning.
Collaboration Security team collaboration. Shared responsibility.
Visibility Security metrics and dashboards. Security reporting.
5.3 DevSecOps Pipeline
text
┌─────────────────────────────────────────────────────────────────────────────┐
│                    DEVSECOPS PIPELINE                                     │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    CODE COMMIT                                      │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    SAST (Static Analysis)                           │   │
│  │  Code security scanning                                             │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    BUILD                                            │   │
│  │  Dependency scanning, container scanning                           │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    TEST                                             │   │
│  │  DAST, security testing, penetration testing                        │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DEPLOY                                           │   │
│  │  Infrastructure scanning, configuration hardening                   │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    MONITOR                                          │   │
│  │  Runtime security monitoring, threat detection                     │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

SECTION 6: IMPLEMENTATION IN PYTHON – APPLICATION SECURITY TOOLS

python
# ===================================================================
# MODULE 5, LESSON 4: APPLICATION SECURITY AND DEVSECOPS
# ===================================================================

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import re
import hashlib
from datetime import datetime
import warnings
warnings.filterwarnings('ignore')

print("="*70)
print("APPLICATION SECURITY AND DEVSECOPS IN BANKING")
print("="*70)

# ----------------------------------------------------------------
# PART A: SECURE CODING PRACTICES
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART A: Secure Coding Practices")
print("-"*60)

class SecureCodingChecker:
    """Simulate a secure coding practice checker."""
    
    def __init__(self):
        self.practices = {
            'Input Validation': {'checked': True, 'description': 'Validate all user inputs'},
            'Output Encoding': {'checked': True, 'description': 'Encode outputs to prevent XSS'},
            'Parameterised Queries': {'checked': True, 'description': 'Prevent SQL injection'},
            'Secure Authentication': {'checked': True, 'description': 'Strong password hashing'},
            'Session Management': {'checked': True, 'description': 'Secure session handling'},
            'Error Handling': {'checked': True, 'description': 'Safe error messages'},
            'Secure Logging': {'checked': True, 'description': 'Log securely'},
            'Least Privilege': {'checked': True, 'description': 'Minimum required permissions'},
            'Secure Configuration': {'checked': True, 'description': 'Secure default configuration'},
            'Dependency Management': {'checked': True, 'description': 'Manage dependencies securely'}
        }
    
    def check_code(self, code):
        """Simulate checking code for secure practices."""
        findings = []
        
        # Simulate checking for SQL injection patterns
        if re.search(r'SELECT.*\+', code, re.IGNORECASE):
            findings.append('Potential SQL injection risk: string concatenation in query')
        
        # Simulate checking for hardcoded credentials
        if re.search(r'password\s*=\s*[\'"]', code, re.IGNORECASE):
            findings.append('Hardcoded credential detected')
        
        # Simulate checking for unsafe input handling
        if re.search(r'eval\s*\(', code, re.IGNORECASE):
            findings.append('Unsafe use of eval() detected')
        
        return findings

# Test the checker
checker = SecureCodingChecker()
code_sample = """
def process_input(user_input):
    query = "SELECT * FROM users WHERE username = '" + user_input + "'"
    password = "hardcoded123"
    result = eval(user_input)
    return result
"""

findings = checker.check_code(code_sample)
print("Secure Coding Checker Results:")
for finding in findings:
    print(f"  ⚠️ {finding}")
if not findings:
    print("  ✅ No issues found")

# ----------------------------------------------------------------
# PART B: DEPENDENCY VULNERABILITY CHECK
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART B: Dependency Vulnerability Check")
print("-"*60)

# Simulate a dependency list
dependencies = pd.DataFrame({
    'Package': ['django', 'requests', 'numpy', 'flask', 'cryptography', 'pandas', 'werkzeug'],
    'Version': ['3.2.0', '2.28.0', '1.24.0', '2.2.0', '39.0.0', '1.5.0', '2.2.0'],
    'Vulnerabilities': ['2', '0', '1', '0', '0', '0', '1'],
    'Severity': ['High', 'None', 'Medium', 'None', 'None', 'None', 'High'],
    'Recommended Version': ['4.0.0', '2.31.0', '1.25.0', '2.3.0', '41.0.0', '2.0.0', '2.3.0']
})

print("Dependency Vulnerability Report:")
print(dependencies.to_string(index=False))

# ----------------------------------------------------------------
# PART C: API SECURITY CHECKLIST
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART C: API Security Checklist")
print("-"*60)

api_security_checklist = [
    "✅ Use OAuth 2.0 for authentication.",
    "✅ Implement scopes for authorisation.",
    "✅ Use TLS 1.3 for all API calls.",
    "✅ Validate all inputs (schema validation).",
    "✅ Implement rate limiting and throttling.",
    "✅ Use API keys for service authentication.",
    "✅ Log all API calls with audit trails.",
    "✅ Implement CORS policies.",
    "✅ Version APIs to manage changes.",
    "✅ Use security headers (CSP, HSTS).",
    "✅ Monitor API usage and anomalies.",
    "✅ Conduct regular security testing."
]

print("API Security Checklist:")
for item in api_security_checklist:
    print(f"  {item}")

# ----------------------------------------------------------------
# PART D: SECURITY TESTING TYPES
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART D: Security Testing Types")
print("-"*60)

security_testing = pd.DataFrame({
    'Testing Type': ['SAST', 'DAST', 'IAST', 'RASP', 'Penetration Testing', 'Security Scanning'],
    'Full Name': [
        'Static Application Security Testing',
        'Dynamic Application Security Testing',
        'Interactive Application Security Testing',
        'Runtime Application Self-Protection',
        'Penetration Testing',
        'Security Scanning'
    ],
    'Description': [
        'Analyse source code for vulnerabilities.',
        'Test running application for vulnerabilities.',
        'Combine SAST and DAST.',
        'Protect application at runtime.',
        'Simulate attacks on application.',
        'Scan for known vulnerabilities.'
    ],
    'Phase': ['Development', 'Testing', 'Testing', 'Runtime', 'Testing', 'Testing']
})

print("Security Testing Types:")
print(security_testing.to_string(index=False))

# ----------------------------------------------------------------
# PART E: DEVSECOPS PIPELINE METRICS
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART E: DevSecOps Pipeline Metrics")
print("-"*60)

devsecops_metrics = pd.DataFrame({
    'Metric': [
        'SAST Coverage',
        'DAST Coverage',
        'Vulnerabilities Found',
        'Vulnerability Remediation Time',
        'False Positive Rate',
        'Security Scan Pass Rate',
        'Critical Vulnerabilities',
        'Infrastructure as Code Security'
    ],
    'Current Value': [
        '72%',
        '45%',
        '28/month',
        '14 days',
        '15%',
        '68%',
        '5/month',
        '55%'
    ],
    'Target Value': [
        '> 95%',
        '> 80%',
        '< 10/month',
        '< 7 days',
        '< 5%',
        '> 90%',
        '< 1/month',
        '> 90%'
    ],
    'Status': ['🟡', '🔴', '🔴', '🔴', '🔴', '🟡', '🟡', '🔴']
})

print("DevSecOps Pipeline Metrics:")
print(devsecops_metrics.to_string(index=False))

# ----------------------------------------------------------------
# PART F: DEVSECOPS PIPELINE VISUALISATION
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART F: DevSecOps Pipeline Visualisation")
print("-"*60)

# Create a visual representation of the DevSecOps pipeline
fig, ax = plt.subplots(figsize=(12, 4))

stages = ['Plan', 'Code', 'Build', 'Test', 'Deploy', 'Monitor']
security_activities = ['Threat Modelling', 'SAST', 'SCA', 'DAST', 'Config Scanning', 'Runtime Security']

# Create a pipeline diagram
y = 0
x_positions = [0, 1, 2, 3, 4, 5]
stage_colors = ['#2ecc71', '#3498db', '#f1c40f', '#e67e22', '#e74c3c', '#9b59b6']

for i, (stage, color) in enumerate(zip(stages, stage_colors)):
    ax.add_patch(plt.Rectangle((i - 0.35, -0.3), 0.7, 0.6, color=color, alpha=0.7))
    ax.text(i, 0, stage, ha='center', va='center', fontsize=10, fontweight='bold', color='white')

# Add security activities below
for i, activity in enumerate(security_activities):
    ax.text(i, -0.6, activity, ha='center', va='center', fontsize=8, style='italic')

ax.set_xlim(-0.5, 5.5)
ax.set_ylim(-1, 0.8)
ax.axis('off')
ax.set_title('DevSecOps Pipeline - Security Integration', fontsize=14)

plt.tight_layout()
plt.savefig('devsecops_pipeline.png', dpi=300, bbox_inches='tight')
plt.show()
print("DevSecOps pipeline visualisation saved as 'devsecops_pipeline.png'")

# ----------------------------------------------------------------
# PART G: APPLICATION SECURITY ROADMAP
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART G: Application Security Roadmap")
print("-"*60)

roadmap = {
    "Phase 1 (0-6 months) – Foundation": {
        "Focus": "Establish application security foundation.",
        "Activities": [
            "Implement SAST in CI/CD pipeline.",
            "Establish secure coding standards.",
            "Conduct security training for developers.",
            "Implement dependency scanning."
        ],
        "Success Metrics": ["SAST coverage > 80%", "DevSecOps adoption > 50%"]
    },
    "Phase 2 (6-12 months) – Scale": {
        "Focus": "Scale application security.",
        "Activities": [
            "Implement DAST and penetration testing.",
            "Automate security testing in CI/CD.",
            "Implement API security scanning.",
            "Establish security champions program."
        ],
        "Success Metrics": ["DAST coverage > 70%", "Vulnerability remediation < 7 days"]
    },
    "Phase 3 (12-24 months) – Advanced": {
        "Focus": "Advanced application security.",
        "Activities": [
            "Implement IAST and RASP.",
            "Deploy automated vulnerability remediation.",
            "Implement threat modelling.",
            "Build security analytics capabilities."
        ],
        "Success Metrics": ["Zero critical vulnerabilities", "Security testing 100% automated"]
    },
    "Phase 4 (24+ months) – Leadership": {
        "Focus": "Industry-leading application security.",
        "Activities": [
            "Implement predictive security analytics.",
            "Build autonomous security controls.",
            "Achieve industry-leading DevSecOps.",
            "Establish security culture."
        ],
        "Success Metrics": ["Industry-leading application security", "Continuous improvement"]
    }
}

for phase, details in roadmap.items():
    print(f"\n{phase}:")
    print(f"  Focus: {details['Focus']}")
    print("  Activities:")
    for activity in details['Activities']:
        print(f"    • {activity}")
    print("  Success Metrics:")
    for metric in details['Success Metrics']:
        print(f"    • {metric}")

# ----------------------------------------------------------------
# PART H: SUMMARY AND RECOMMENDATIONS
# ----------------------------------------------------------------

print("\n" + "="*70)
print("PART H: Summary and Recommendations")
print("="*70)

print("""
Application Security and DevSecOps – Key Takeaways:

1. Application security is critical for protecting customer data and compliance.
2. Secure Development Lifecycle: requirements → design → development → testing → deployment → maintenance.
3. API security: authentication, authorisation, rate limiting, input validation, encryption.
4. DevSecOps integrates security into the DevOps pipeline (shift left).
5. Security testing types: SAST, DAST, IAST, RASP, penetration testing.
6. Key metrics: SAST coverage, vulnerability remediation time, false positive rate.
7. Roadmap: foundation → scale → advanced → leadership.

Recommendations:
  - Implement SAST and DAST in CI/CD pipeline.
  - Establish secure coding standards.
  - Conduct regular security training for developers.
  - Automate security testing in CI/CD.
  - Implement API security best practices.
  - Foster a security-first culture.
""")

print("="*70)
print("END OF LESSON 4 – MODULE 5")
print("="*70)

SECTION 7: SUMMARY FOR THE DATA PRACTITIONER

  • Application security is critical for protecting customer data and maintaining regulatory compliance.

  • Secure Development Lifecycle (SDL) integrates security at every phase: requirements, design, development, testing, deployment, and maintenance.

  • API security requires authentication (OAuth 2.0), authorisation (scopes), rate limiting, input validation, and encryption (TLS).

  • DevSecOps integrates security into the DevOps pipeline, shifting security left to catch vulnerabilities early.

  • Security testing includes SAST (static), DAST (dynamic), IAST (interactive), RASP (runtime), and penetration testing.

  • Key metrics include SAST coverage, DAST coverage, vulnerability remediation time, and false positive rate.

  • Roadmap progresses from foundation to scaling, advanced, and leadership phases.


SECTION 8: RECOMMENDED NEXT STEPS

  1. Implement SAST and DAST in CI/CD pipeline.

  2. Establish secure coding standards.

  3. Conduct regular security training for developers.

  4. Automate security testing in CI/CD.

  5. Implement API security best practices.

  6. Foster a security-first culture.

  7. Prepare for Lesson 5: Data Protection and Encryption.


.