Cyber Security & Data Protection

Chapter 9
Secure Software and DevSecOps

Advance Diploma in Information Technology
Cyber Security & Data Protection   •   Advance Diploma

Secure Software and DevSecOps

Introduction

Software is now part of nearly every business process, critical service and personal activity. A vulnerability in an application can expose confidential records, alter transactions, interrupt operations or provide a pathway into wider organisational systems. Security therefore cannot be treated as a final testing activity or as the sole responsibility of a security team. It must be integrated into the software development lifecycle (SDLC), from business requirements through design, implementation, deployment and retirement.

Secure software development is the disciplined production and maintenance of software that preserves confidentiality, integrity, availability, authenticity and accountability. DevSecOps extends this idea by embedding security practices, controls and feedback into collaborative development and operations processes. It combines development, security and operations rather than placing them in separate sequential silos.

This chapter explains how to establish security requirements, model threats, write and review secure code, manage dependencies, test applications, protect APIs and implement security controls in continuous integration and continuous delivery (CI/CD) pipelines. OWASP guidance is used as a practical reference, but professional judgement remains essential because no checklist can guarantee security.

Learning Objectives

By the end of this chapter, students should be able to:

  1. Explain why security must be integrated throughout the SDLC.
  2. Convert business and regulatory needs into testable security requirements.
  3. Apply threat-modelling methods to identify threats and select mitigations.
  4. Recognise secure coding principles and conduct an effective code review.
  5. Manage third-party dependencies and software supply-chain risk.
  6. Select appropriate application-security testing techniques.
  7. Identify common API weaknesses and appropriate controls.
  8. Design security controls for CI/CD pipelines.
  9. Use OWASP resources critically in professional software development.

1. Security Across the Software Development Lifecycle

A traditional SDLC may contain initiation, requirements, design, implementation, testing, deployment and maintenance. A secure SDLC adds security activities and decision points to every phase.

SDLC phaseSecurity activitiesTypical evidence
InitiationDefine risk appetite, data classification and legal obligationsSecurity charter, data inventory
RequirementsSpecify authentication, authorisation, privacy, logging and resilience needsTestable security requirements
DesignThreat modelling, trust-boundary analysis and secure architecture reviewThreat model, architecture decisions
ImplementationSecure coding, peer review and secret-management controlsReviewed commits, scan results
TestingAutomated and manual security testingTest reports and defect records
ReleaseRisk acceptance, configuration verification and deployment approvalRelease decision, artefact provenance
OperationsMonitoring, patching, incident response and vulnerability managementAlerts, tickets, patch records
RetirementData retention, secure deletion and credential revocationDecommissioning record

Security defects become more expensive to correct when discovered late because design decisions, data structures and interfaces may already be embedded in the product. Early analysis does not eliminate later testing; it reduces the number and cost of defects that testing must discover.

DevSecOps is not simply “adding a security scanner to a build.” It involves shared ownership, automation where appropriate, security-skilled developers, rapid feedback and risk-based governance. Teams should make security controls observable and repeatable while retaining human review for significant risks.

2. Security Requirements and Abuse Cases

A security requirement states a protection property that the system must provide. It should be specific, testable and connected to an asset or risk. “The system must be secure” is not testable. “After five failed login attempts within 15 minutes, the account must be temporarily blocked and the event logged” is substantially more useful, although the duration and recovery process must also be defined.

Requirements should address:

  • Identity and authentication: account enrolment, password policy, multifactor authentication, session lifetime and account recovery.
  • Authorisation: permitted actions for each role, object-level access and administrative separation.
  • Confidentiality: encryption in transit and at rest, data minimisation and access restrictions.
  • Integrity: transaction validation, anti-tampering controls, audit trails and concurrency protection.
  • Availability: capacity, rate limiting, graceful degradation, backup and recovery objectives.
  • Privacy: purpose limitation, retention, consent where applicable, rights of data subjects and secure deletion.
  • Auditability: security-relevant events, time synchronisation, log integrity and restricted log access.
  • Resilience: recovery from dependency failure, denial-of-service conditions and compromised credentials.

Acceptance criteria translate requirements into evidence. For example, an API requirement may state that a user may retrieve invoices only when the invoice belongs to that user’s authorised organisation. A test should attempt access with an invoice identifier belonging to another organisation and confirm denial without disclosure of sensitive information.

Misuse cases and abuse stories describe how a malicious or careless actor could use a feature. For a password-reset feature, examples include guessing reset tokens, forwarding a token to another person, changing the account email without re-authentication or causing excessive messages. Considering abuse cases alongside user stories prevents functional requirements from hiding security assumptions.

Security requirements should be traceable to tests and controls. A requirements traceability matrix can map each requirement to its design decision, implementation control, test and approval. This is especially valuable in regulated environments.

3. Threat Modelling

Threat modelling is a structured process for identifying what can go wrong, why it could happen and how risk can be reduced. It is most valuable during design, but it should be revisited when architecture, data flows or dependencies change.

A practical threat-modelling process is:

  1. Define scope: identify the system, users, data, dependencies and assumptions.
  2. Identify assets: for example, payment details, identities, source code and availability.
  3. Draw the architecture and data flows: show processes, stores, external services and trust boundaries.
  4. Identify threats: consider misuse, compromised components, malicious insiders and failures.
  5. Assess risk: estimate likelihood and impact using an agreed organisational method.
  6. Select mitigations: prefer architectural and preventive controls before detective controls.
  7. Record residual risk: document assumptions, owners and accepted risks.
  8. Validate: review the model with developers, operations, security and relevant business owners.

The STRIDE mnemonic helps identify categories of threat: Spoofing identity, Tampering with data, Repudiation of actions, Information disclosure, Denial of service and Elevation of privilege. STRIDE is a discovery aid, not a complete risk assessment.

A trust boundary is a location where the level of trust changes, such as between a browser and server, an application and database, or an organisation and a cloud provider. Data crossing a trust boundary requires validation, authentication or integrity protection appropriate to the risk.

Risk is often expressed qualitatively as a combination of likelihood and impact. A simple matrix may classify risks as low, medium or high. Numerical scores can create false precision if the scales are not defined consistently. The important professional practice is to state assumptions, use consistent criteria and assign ownership.

Mitigations should be mapped to threats. For example, a threat that an attacker modifies a request parameter to access another customer’s record is mitigated by server-side authorisation checks based on the authenticated identity and resource ownership—not merely by hiding the parameter in the user interface.

4. Secure Architecture and Design Principles

Secure design principles provide general guidance when detailed requirements are incomplete.

  • Least privilege: give identities and processes only the permissions required for their task.
  • Fail securely: failures should deny sensitive access rather than grant it.
  • Complete mediation: check authorisation on every protected operation, not only at login.
  • Defence in depth: use multiple independent controls so one failure does not expose the system.
  • Secure defaults: initial configuration should be protective, with unnecessary features disabled.
  • Separation of duties: divide sensitive actions or approvals among roles where appropriate.
  • Economy of mechanism: reduce unnecessary complexity and attack surface.
  • Minimise attack surface: expose fewer interfaces, services and privileges.
  • Avoid security through obscurity: secrecy of design should not be the principal protection; secret keys and credentials must nevertheless remain confidential.

Architectural decisions should document security trade-offs. Microservices, for example, may isolate failures and permit independent deployment, but they also increase the number of identities, network paths, interfaces and secrets. A monolith is not automatically insecure, and microservices are not automatically secure.

Sensitive data should be classified and minimised. Do not collect or retain data merely because it might be useful later. Encryption protects confidentiality but does not replace access control, secure key management, input validation or sound authorisation.

5. Secure Coding and Code Review

Secure coding begins with treating all external input as untrusted. Input should be validated according to context, normalised consistently and constrained by an allow-list where feasible. Output should be encoded for its destination, such as HTML, SQL, a shell command, a URL or a log. Validation and output encoding solve different problems.

Important practices include:

  • Use parameterised database queries rather than constructing SQL through string concatenation.
  • Use safe APIs for operating-system commands and avoid shell interpretation where possible.
  • Apply server-side validation even when client-side validation exists.
  • Use memory-safe languages or carefully apply bounds checking and safe ownership practices.
  • Handle errors without revealing stack traces, secrets, internal paths or database details.
  • Store passwords using a modern adaptive password-hashing function with a unique salt; never encrypt or reversibly encode passwords for storage.
  • Generate security tokens using a cryptographically secure random generator.
  • Protect sessions with secure, HttpOnly and appropriately scoped cookies, expiration and server-side invalidation.
  • Avoid hard-coded credentials, private keys and tokens in source code.
  • Protect logs from injection and avoid recording passwords, access tokens or unnecessary personal data.
  • Make security-relevant operations atomic where partial failure could create inconsistent state.

Code review should be risk-based. Reviewers should understand the intended security property, identify trust boundaries and inspect data flows. Useful questions include: Where does input originate? Is authentication distinct from authorisation? Can a user select another user’s object identifier? What happens when a dependency or identity provider is unavailable? Are errors safe? Are secrets exposed in code, logs, build output or artefacts?

A review should produce actionable findings with location, consequence, evidence and recommended remediation. Automated tools are valuable for consistency, but they produce false positives and may miss business-logic flaws. Human review remains essential for authorisation, workflow and design weaknesses.

6. Dependency and Software Supply-Chain Security

Modern applications depend on open-source packages, commercial libraries, container images, build tools and hosted services. Each dependency can introduce vulnerabilities, malicious code, licensing obligations or operational risk.

A software bill of materials (SBOM) records components and versions in an application. Dependency management should include:

  1. inventorying direct and transitive components;
  2. pinning or constraining versions and verifying package integrity;
  3. monitoring vulnerability advisories and exploitability;
  4. updating dependencies through tested, reviewable changes;
  5. removing unused packages;
  6. controlling package sources and build permissions;
  7. reviewing licences and provenance; and
  8. generating provenance information for released artefacts.

A vulnerability severity rating is not the same as organisational risk. A severe vulnerability in an unreachable component may have lower immediate risk than a moderate vulnerability in an internet-facing authenticated service. Teams should consider exposure, exploit availability, compensating controls, affected data and business impact.

Lockfiles improve reproducibility but must themselves be maintained. Blindly accepting automated updates can introduce breaking changes or malicious packages; refusing all updates creates accumulated technical debt. A controlled update process combines automation, testing, review and emergency response.

Build systems are privileged assets. Protect them with strong authentication, isolated runners, minimal permissions, protected branches, secret stores and review of pipeline changes. Build artefacts should be traceable to source, dependencies and build instructions.

7. Application Security Testing

No single test detects every class of vulnerability. A mature programme combines complementary methods.

TechniqueStrengthLimitation
SASTFinds patterns in source or bytecode earlyMay miss runtime and business-logic issues
DASTTests a running application from an external perspectiveLimited visibility and can miss untriggered paths
IASTObserves execution with application contextRequires instrumentation and suitable test execution
SCAIdentifies vulnerable or non-compliant dependenciesVulnerability data and reachability may be imperfect
Fuzz testingExercises unexpected and malformed inputsRequires suitable targets and useful oracles
Manual penetration testingFinds complex workflows and practical exploit pathsCostly, periodic and dependent on tester skill
Configuration testingDetects insecure settings and deployment driftDoes not prove application logic is secure

Unit and integration tests should include security acceptance criteria. Negative tests are particularly important: unauthorised users, malformed input, expired tokens, replayed requests, excessive requests and cross-tenant access attempts.

Testing must be conducted safely. Production testing requires explicit authorisation, defined scope, data protection and rollback procedures. Test data should not expose real personal information unnecessarily. Findings should be triaged, remediated and retested; a scan report without ownership and closure is not an effective control.

Metrics should support decisions rather than reward superficial activity. Useful measures include time to remediate risks by severity, percentage of critical services with threat models, dependency update age, recurrence of defect classes and coverage of security tests. Counting scanner findings alone can encourage teams to optimise the metric rather than reduce risk.

8. API Security

APIs expose data and business functions directly, often to mobile applications, partners and automated clients. Common API risks include broken object-level authorisation, broken authentication, excessive data exposure, unrestricted resource consumption, unsafe consumption of third-party APIs and inadequate inventory of old versions.

A secure API should:

  • authenticate clients and users using an appropriate protocol and securely managed credentials;
  • authorise every operation and every object access on the server;
  • validate method, content type, schema, size and semantic constraints;
  • apply rate limits and quotas appropriate to the operation;
  • return only the fields required by the caller;
  • use TLS and validate certificates appropriately;
  • prevent replay where transactions are sensitive, using expiry, nonce or idempotency controls as applicable;
  • define safe error responses and consistent status behaviour;
  • log security-relevant events without exposing secrets; and
  • maintain an inventory of versions, owners, data classifications and retirement dates.

An object identifier is not an authorisation decision. For example, replacing /accounts/1001 with /accounts/1002 must not reveal account 1002 merely because the request is authenticated. The server must establish that the requester is authorised for the specific object and operation.

API keys identify applications but generally do not provide sufficient evidence of a human user’s authority. Tokens should be scoped, short-lived where practical and revocable. Token contents should not be trusted merely because they are readable; signature, issuer, audience, expiry and appropriate claims must be validated according to the selected protocol.

9. CI/CD Security Controls

A secure pipeline creates a controlled path from reviewed source to a deployable artefact. Typical controls include:

  1. protected branches and mandatory peer review;
  2. secret and sensitive-data scanning before merge;
  3. dependency and licence checks;
  4. static analysis and unit security tests;
  5. isolated, reproducible builds;
  6. signed or otherwise verifiable artefacts;
  7. deployment identity with least privilege;
  8. environment separation and approval for high-risk releases;
  9. infrastructure-as-code scanning and configuration validation;
  10. post-deployment verification and monitoring; and
  11. rapid rollback or forward-fix capability.

Pipeline secrets should be supplied at runtime from a managed secret store, with limited scope and rotation. They should not be printed in logs or passed to untrusted build steps. Pull requests from untrusted contributors require special care because build scripts may execute attacker-controlled code.

Security gates should be proportionate. Blocking every low-confidence warning may cause teams to disable the tool. A better model defines thresholds for blocking, warning, exception approval and expiration. Exceptions should identify the risk, rationale, owner, compensating control and review date.

Continuous delivery does not mean continuous uncontrolled release. Automation can execute policy consistently, while release decisions remain accountable to appropriate owners. Monitoring must confirm that the deployed environment matches the approved artefact and configuration.

10. OWASP Guidance and Professional Use

OWASP provides widely used, freely available resources, including the OWASP Top 10, Application Security Verification Standard (ASVS), Software Assurance Maturity Model (SAMM), API Security Top 10 and testing guidance. These resources help teams establish common language, requirements and test ideas.

The OWASP Top 10 is an awareness document, not a complete security standard or a ranking that permits ignoring all other risks. Teams should use ASVS or organisation-specific requirements when precise verification is needed. Guidance must be adapted to technology, threat environment, architecture and regulatory obligations, and its version should be recorded because recommendations evolve.

Illustrative Case: Secure Online Student Records API

Background

A fictional university introduces an API for a mobile student portal. Students can view grades and update contact details. Lecturers can submit grades, while administrators manage enrolment. The first release passes functional tests but has no formal threat model.

Problem

A penetration test discovers that any authenticated student can change an identifier in a request and retrieve another student’s record. The API also returns full internal objects, uses long-lived access tokens and permits unlimited password-reset requests. A dependency scanner identifies an outdated package, but no owner is assigned.

Analysis

The central failure is not merely a missing filter. Requirements did not define object-level authorisation, data minimisation or rate limits. The design treated authentication as if it implied permission. The absence of an API inventory and dependency ownership allowed additional risks to remain unmanaged.

Approach and solution

The university creates a data-flow diagram and threat model. It defines roles and resource-ownership rules, then implements server-side authorisation for every record access. Responses use explicit schemas containing only necessary fields. Password-reset requests are rate-limited, reset tokens are short-lived and single-use, and security events are logged with privacy controls. Tokens are shortened and scoped, and the API validates issuer, audience and expiry.

The team introduces dependency inventory, automated update pull requests and an emergency patch process. CI/CD now runs secret scanning, SAST, SCA, API contract tests and infrastructure checks. A protected release requires review of high-risk findings, while exceptions expire after a defined period. Test data is synthetic, and an independent retest verifies cross-student access denial.

Outcome

The immediate vulnerability is removed, but the more important outcome is institutional: security requirements, ownership, testing and monitoring become part of normal delivery. The university accepts a documented residual risk for a legacy integration, with a time-bound migration plan.

Learning points

  1. Authentication does not replace authorisation.
  2. Business-logic and object-level flaws require contextual tests.
  3. Data minimisation reduces the consequence of an API failure.
  4. Tool output needs ownership, prioritisation and remediation.
  5. DevSecOps is a socio-technical practice involving people, process and technology.

Governance, Ethics and Limitations

Security controls must respect privacy, accessibility and legitimate user needs. Excessive monitoring can create unjustified surveillance; logging should be proportionate, access-controlled and retained only as long as justified. Security testing requires permission and must avoid harm to users or third parties.

Organisations should define accountability for risk acceptance, vulnerability disclosure, incident response and regulatory notification. Data-protection laws may impose obligations concerning lawful processing, security measures, breach response, retention and data-subject rights. Legal advice is necessary because requirements vary by jurisdiction and sector.

Automation and AI-assisted coding can increase productivity, but generated code may contain insecure dependencies, incorrect cryptography, weak authorisation or confidential information copied into external services. Generated code must be reviewed, tested and governed like any other code. AI systems also create risks involving prompt injection, training-data exposure, model supply chains and unauthorised data disclosure when integrated into applications.

DevSecOps has limitations. Automation cannot fully understand business context, eliminate zero-day vulnerabilities or decide acceptable residual risk. High-frequency delivery can amplify mistakes if governance is weak. Security teams must therefore combine engineering controls with education, independent assurance, incident learning and continuous improvement.

Contemporary Developments and Best Practice

Current practice increasingly emphasises software supply-chain security, provenance, signed artefacts, infrastructure as code, cloud-native identity, zero-trust principles and continuous verification. Runtime application self-protection and behavioural monitoring can provide additional signals, but they should not excuse insecure design.

A practical organisational baseline is to:

  • establish security ownership for every product;
  • classify data and identify critical business processes;
  • threat-model significant changes;
  • use secure coding standards and peer review;
  • maintain an SBOM and patch dependencies;
  • combine automated and manual testing;
  • protect API identities, objects and resources;
  • isolate and harden CI/CD infrastructure;
  • monitor production and rehearse incident response;
  • measure remediation and recurring defects; and
  • review controls after incidents, major changes and emerging threats.

The objective is not to make software risk-free, which is impossible, but to make risks visible, controlled, testable and accountable throughout the product lifecycle.

Chapter Summary

Secure software development integrates confidentiality, integrity, availability, privacy and accountability into every SDLC phase. Security requirements must be specific and testable, while abuse cases expose ways that legitimate features may be misused. Threat modelling uses assets, data flows, trust boundaries and structured threat categories such as STRIDE to guide mitigations.

Secure architecture applies least privilege, complete mediation, secure defaults, defence in depth and attack-surface reduction. Secure coding depends on contextual validation, safe APIs, protected sessions, secure password storage, safe error handling and careful treatment of secrets. Code review and automated analysis are complementary.

Dependencies and build systems form part of the software supply chain and require inventory, provenance, controlled updates and least privilege. SAST, DAST, SCA, fuzzing, manual testing and configuration testing find different classes of weakness. APIs require object-level authorisation, schema validation, rate limits, data minimisation and lifecycle management.

DevSecOps embeds these practices into CI/CD through protected source control, security scanning, reproducible builds, artefact verification, secret management, controlled deployment and monitoring. OWASP resources provide valuable guidance but must be adapted to context. Effective security is ultimately a shared organisational responsibility supported by technology, governance, ethics and continuous learning.

Key Terms

Threat modelling: A structured process for identifying threats, assessing risk and selecting mitigations.

Trust boundary: A point where data or execution crosses between different levels of trust.

Secure SDLC: A software lifecycle that integrates security activities into every phase.

DevSecOps: Collaborative development, security and operations with security embedded in delivery practices.

Least privilege: Granting only the permissions necessary for an identity or process.

Complete mediation: Checking authorisation for every protected operation.

Abuse case: A description of how a feature could be misused or attacked.

STRIDE: A threat-identification mnemonic covering spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege.

SAST: Static application security testing of source, bytecode or intermediate code.

DAST: Dynamic testing of a running application.

SCA: Software composition analysis of third-party and open-source components.

SBOM: A structured inventory of software components and dependencies.

API: An application programming interface through which software systems communicate.

Object-level authorisation: Permission checking for access to a specific resource or record.

CI/CD: Continuous integration and continuous delivery or deployment practices.

Software supply chain: The people, tools, components and processes used to build and deliver software.

Defence in depth: Use of multiple complementary controls to reduce dependence on one control.

Residual risk: Risk remaining after controls have been implemented.

OWASP: An open community producing application-security knowledge, standards and tools.

Review Questions

5 Short Answer Questions

  1. Why should security requirements be testable?
  2. What is a trust boundary?
  3. State two principles of secure design.
  4. What is the purpose of an SBOM?
  5. Why does authentication not replace authorisation?

5 Long Answer Questions

  1. Explain how security activities can be integrated across the SDLC.
  2. Describe a threat-modelling process and explain the role of STRIDE.
  3. Compare SAST, DAST, SCA and manual penetration testing.
  4. Explain the main security controls required for a CI/CD pipeline.
  5. Discuss the strengths and limitations of OWASP guidance.

3 Analytical / Application Questions

  1. Design security requirements and abuse cases for an online payment API. Explain how each requirement would be tested.
  2. A developer proposes storing API keys in a public source repository because the application is “internal.” Analyse the risks and recommend a replacement design.
  3. An authenticated user can alter an invoice identifier and view another organisation’s invoice. Apply threat modelling and secure API principles to diagnose and remediate the weakness.

Multiple Choice Questions with Answers

Question 1

Which activity is most appropriate during the design phase of a secure SDLC?

A. Threat modelling and trust-boundary analysis

B. Deleting all production logs

C. Disabling peer review

D. Publishing untested artefacts

Correct Answer: A. Threat modelling and trust-boundary analysis

Question 2

Which principle requires the server to check permission for every protected operation?

A. Economy of mechanism

B. Complete mediation

C. Secure default

D. Separation of duties

Correct Answer: B. Complete mediation

Question 3

What is the primary purpose of an SBOM?

A. To replace all application tests

B. To record software components and dependencies

C. To encrypt database records

D. To authenticate end users

Correct Answer: B. To record software components and dependencies

Question 4

Which control best prevents SQL injection?

A. Hiding database error messages only

B. Using parameterised queries

C. Increasing token lifetime

D. Changing the database hostname

Correct Answer: B. Using parameterised queries

Question 5

What does DAST examine?

A. A running application

B. Only software licences

C. Employee training records

D. Physical server temperature

Correct Answer: A. A running application

Question 6

An authenticated user changes an object identifier to access another customer’s record. Which weakness is most directly involved?

A. Broken object-level authorisation

B. Insufficient password length only

C. Missing software licence

D. Excessive source-code comments

Correct Answer: A. Broken object-level authorisation

Question 7

Where should CI/CD secrets preferably be stored?

A. In public documentation

B. In source-code comments

C. In a managed secret store supplied at runtime

D. In the application URL

Correct Answer: C. In a managed secret store supplied at runtime

Question 8

Which statement about the OWASP Top 10 is most accurate?

A. It guarantees that an application is secure

B. It is an awareness resource, not a complete security standard

C. It replaces threat modelling

D. It applies only to desktop software

Correct Answer: B. It is an awareness resource, not a complete security standard

Question 9

Which API control limits excessive requests and resource consumption?

A. Rate limiting and quotas

B. Removing all authentication

C. Returning every database field

D. Using longer error messages

Correct Answer: A. Rate limiting and quotas

Question 10

Why are automated security tools insufficient on their own?

A. They cannot be executed in CI/CD

B. They always produce no results

C. They may miss business-logic and contextual flaws

D. They eliminate the need for requirements

Correct Answer: C. They may miss business-logic and contextual flaws

Cyber Security & Data Protection
Chapter 9 of 14