Secure Software, Web and Application SecurityIntroductionModern organisations depend on software for communication, financial transactions, healthcare, education, manufacturing and public services. A vulnerability in an application can therefore expose confidential information, alter records, interrupt operations or provide a pathway into wider infrastructure. Application security is the discipline of reducing these risks throughout the software development lifecycle (SDLC). Application security is broader than testing a completed program. It includes security requirements, architecture, coding practices, dependency management, identity and access control, deployment configuration, monitoring and incident response. Effective security is therefore a shared responsibility among business owners, developers, testers, system administrators, security specialists and users. This chapter introduces secure development lifecycle practices, threat modelling, security testing and common web and application weaknesses. Particular attention is given to injection, broken access control and insecure application programming interfaces (APIs), together with practical mitigations. Learning ObjectivesAfter studying this chapter, you should be able to: - describe the main activities of a secure software development lifecycle;
- explain threat modelling and apply a structured model to a simple system;
- distinguish static, dynamic, dependency and manual security testing;
- recognise injection, broken access control and insecure API designs;
- recommend controls for authentication, authorisation, input handling and data protection;
- assess the professional, ethical and governance implications of application security.
1. Foundations of Secure Software Development1.1 Security propertiesSecure applications support the familiar confidentiality, integrity and availability objectives: - Confidentiality: only authorised parties can view information.
- Integrity: information and operations cannot be changed without authorisation.
- Availability: authorised users can access the service when required.
Applications also require related properties such as authenticity, accountability, privacy, resilience and non-repudiation. These properties may conflict. For example, strong authentication can improve confidentiality but introduce usability costs. Security engineering is consequently a risk-management activity rather than an attempt to eliminate every possible threat. 1.2 The secure SDLCA secure SDLC integrates security activities into each development phase rather than treating security as a final inspection. | SDLC phase | Typical security activities | Useful outputs |
|---|
| Planning and requirements | Identify assets, regulations, users and security requirements | Security requirements and acceptance criteria | | Design | Threat modelling, trust-boundary analysis, secure architecture review | Threat model, security architecture | | Implementation | Secure coding, peer review, dependency control and secret management | Reviewed source code and build records | | Verification | Automated and manual security testing | Defect reports and test evidence | | Release | Configuration review, deployment approval and rollback planning | Security sign-off and release plan | | Operations | Monitoring, patching, vulnerability management and incident response | Logs, alerts and remediation records | | Retirement | Data retention, secure disposal and access removal | Decommissioning evidence |
Security requirements should be testable. “The system must be secure” is not a useful requirement. “An account is locked or rate-limited after a defined number of failed authentication attempts, subject to an approved recovery process” is more measurable, although the exact threshold should be chosen according to risk and usability. 1.3 Shift-left and DevSecOps“Shift-left” means finding and addressing defects earlier, when correction is generally less disruptive. DevSecOps extends this idea by embedding security into collaborative development and automated delivery pipelines. A pipeline may perform source-code analysis, dependency checks, unit tests, container checks and deployment-policy validation. Automation is valuable but incomplete. Tools can produce false positives, miss business-logic flaws and fail to understand whether an endpoint properly authorises a particular user. Human review remains essential, especially for architecture, privilege boundaries and high-risk workflows. 2. Threat ModellingThreat modelling is a systematic method for identifying what must be protected, how an attacker might cause harm and which controls should reduce the risk. It should begin during design and be updated when architecture, dependencies or business functions change. 2.1 A practical processA useful threat-modelling process contains five activities: - Define scope and objectives. Identify the application, users, data, business processes and security goals.
- Model the system. Draw data flows between users, services, databases, queues and external providers. Mark trust boundaries where data or authority crosses from one security context to another.
- Identify threats. Consider spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege. These categories are commonly associated with the STRIDE model.
- Evaluate risk. Consider likelihood, affected assets, business impact and existing controls. Qualitative labels such as low, medium and high are acceptable when their meanings are documented.
- Select and track mitigations. Assign owners, priorities and verification methods. Residual risk should be formally accepted or further reduced.
A threat is not simply a vulnerability. A vulnerability is a weakness; a threat is a possible harmful event or actor capability; risk combines the likelihood and impact of harm. A simple qualitative risk statement is often more useful than an apparently precise numerical score that lacks reliable data. 2.2 Trust boundaries and attack surfacesA trust boundary is a point at which assumptions about identity, authority or data quality change. Examples include a browser-to-server connection, an internet-facing API, a service-to-service call and an application-to-database connection. Every boundary should raise questions: Is the caller authenticated? Is the input validated? Is the message protected in transit? Is the caller authorised for this particular operation? The attack surface includes exposed endpoints, administrative functions, file uploads, authentication interfaces, third-party libraries, cloud services, management ports and operational processes. Reducing unnecessary functionality and limiting network exposure can reduce the attack surface, but essential interfaces still require robust controls. 2.3 Illustrative threat modelConsider an online library application. A member signs in through a web browser, searches the catalogue, borrows a book and views borrowing history. The application communicates with a catalogue database and a payment provider for overdue charges. Important assets include member credentials, personal information, borrowing records and payment data. Threats include credential theft, unauthorised viewing of another member’s history, SQL injection through search fields, manipulation of payment requests and denial of service. Mitigations include multi-factor authentication for privileged users, parameterised database queries, server-side authorisation checks, signed or mutually authenticated provider requests, rate limiting and monitoring. The model should record assumptions. For example, the payment provider may be trusted to process a request, but the application must not trust client-supplied payment status. It should verify the provider’s authenticated response and correlate it with the correct transaction. 3. Secure Architecture and Design Principles3.1 Least privilege and separation of dutiesLeast privilege gives a subject only the permissions required for its legitimate task. A web application should not normally connect to a database using an administrator account. Separate service identities, narrowly scoped permissions and controlled administrative functions reduce the consequences of compromise. Separation of duties prevents one person or component from completing a sensitive process alone. For example, a developer may deploy code to a test environment while production release approval requires an independent authorised person. 3.2 Secure defaults and fail-safe behaviourSecure defaults mean that a new account, endpoint or deployment begins with restrictive settings. Access should be denied unless explicitly granted. Fail-safe behaviour means that errors do not expose secrets or silently grant access. Error messages should help legitimate diagnosis without revealing stack traces, credentials, internal paths or database details to untrusted users. 3.3 Defence in depthNo single control is assumed to be perfect. A robust design may combine transport encryption, authentication, authorisation, input validation, parameterised queries, network restrictions, logging and backups. Defence in depth must not become an excuse for weak primary controls: encryption cannot compensate for missing authorisation, and a web application firewall cannot reliably correct flawed business logic. 4. Common Application Weaknesses4.1 InjectionInjection occurs when untrusted data is interpreted as part of a command or query. Common forms include SQL injection, operating-system command injection, LDAP injection and cross-site scripting (XSS). The underlying design error is confusing data with instructions. A vulnerable database pattern may construct a query by concatenating a user’s search text into a query string. An attacker can then provide specially crafted input that changes the intended query. The preferred mitigation is a parameterised query or prepared statement, in which the database receives the command structure separately from the data values. Other controls include: - allow-list validation where the permitted format is known;
- context-specific output encoding for HTML, JavaScript, URLs or SQL;
- avoiding dynamic code evaluation;
- using safe database and operating-system APIs;
- applying least privilege to service accounts;
- testing error paths and unusual encodings.
Input validation is not a universal substitute for parameterisation. A valid-looking string may still be dangerous in a particular interpreter context, and deny-list filtering is commonly bypassed by alternate encodings or syntax. Cross-site scripting occurs when attacker-controlled content is executed as script in another user’s browser. Stored XSS persists in application data; reflected XSS is returned in a response; DOM-based XSS results from unsafe client-side processing. Context-aware output encoding, safe templating, sanitised rich text, a carefully configured Content Security Policy and appropriate cookie attributes help reduce XSS risk. These measures should be combined rather than treated as interchangeable. 4.2 Broken access controlAuthentication answers “Who are you?” Authorisation answers “What may you do?” Broken access control occurs when an application fails to enforce permissions correctly. Examples include viewing another user’s invoice by changing an identifier in a URL, accessing administrative functions through an unlinked endpoint, or modifying a record by submitting fields that should be read-only. Effective controls include: - checking authorisation on the server for every protected operation;
- denying access by default;
- using centralised and consistently tested policy mechanisms;
- checking object ownership or permitted relationship, not merely whether a user is logged in;
- avoiding reliance on hidden form fields, client-side checks or obscure URLs;
- preventing mass assignment of sensitive fields;
- testing horizontal access (one user accessing another user’s data) and vertical access (a normal user accessing administrator functions).
An object-level authorisation decision should consider the authenticated identity, requested action, target object and relevant business context. A policy such as “a member may read a borrowing record only when the record belongs to that member” is stronger than merely checking that the member has a valid session. 4.3 Insecure APIsAPIs expose application functions to browsers, mobile clients, partners and internal services. Common API weaknesses include excessive data exposure, missing object-level authorisation, weak authentication, unrestricted resource consumption, unsafe file handling and poor validation of content types. A secure API should: - use TLS for connections and validate certificates appropriately;
- authenticate callers using a suitable protocol and protect credentials or tokens;
- authorise every object and action on the server;
- validate method, content type, size, schema and business rules;
- return only the fields required by the client;
- apply rate limits, quotas, pagination and request-size limits;
- avoid placing sensitive data in URLs when a safer method is available;
- protect against replay where transactions are sensitive;
- log security-relevant events without recording secrets;
- version and document the interface, including error behaviour.
Tokens should have limited scope and lifetime. A bearer token must be protected because possession may be sufficient to use it. Secrets should not be embedded in mobile applications, source repositories, client-side code or logs. 4.4 Authentication and session managementPasswords should be stored using a modern, deliberately slow password-hashing scheme with a unique salt per password. Plaintext passwords and reversible encryption are inappropriate for password storage. Authentication should resist credential stuffing through multi-factor authentication where risk justifies it, rate limiting, breached-password screening and secure recovery processes. Sessions require unpredictable identifiers, secure transport and appropriate cookie attributes. Secure restricts transmission to HTTPS, HttpOnly reduces access by client-side scripts, and SameSite helps limit some cross-site request risks. Session identifiers should be rotated after significant privilege changes, and sessions should expire according to risk and operational needs. 4.5 Cross-site request forgery and file handlingCross-site request forgery (CSRF) tricks a browser into sending an authenticated request to a vulnerable site. Anti-CSRF tokens, appropriate SameSite cookie settings, origin checks and requiring re-authentication for highly sensitive operations are useful controls. APIs using non-cookie authorisation may have a different CSRF profile, but they still require careful token and origin handling. File uploads should be treated as hostile. Controls include size limits, allow-listed types, content inspection, randomised storage names, storage outside executable web paths and malware scanning where appropriate. A file’s extension or client-supplied MIME type is not reliable proof of its content. 5. Security TestingSecurity testing should combine multiple techniques because each detects different classes of weakness. | Technique | Main purpose | Strength | Limitation |
|---|
| Static application security testing (SAST) | Analyse source or bytecode | Early and repeatable | May miss runtime and business-logic flaws | | Dynamic testing (DAST) | Test a running application | Observes real responses | Limited visibility into code and unlinked functions | | Software composition analysis (SCA) | Identify vulnerable dependencies and licences | Covers third-party components | A listed vulnerability may not be exploitable in context | | Interactive testing (IAST) | Combine runtime and code information | Useful diagnostic context | Requires instrumentation and representative tests | | Manual review and penetration testing | Examine architecture and behaviour | Finds logic and design flaws | Expensive and dependent on tester skill | | Fuzz testing | Supply unexpected or malformed inputs | Finds robustness defects | Requires suitable monitoring and oracles |
Testing should be risk-based. Authentication, payment, personal-data access and administrative functions deserve greater depth than a low-risk informational page. Findings should be triaged by exploitability, affected assets, exposure and business impact. A scanner result is not automatically a confirmed vulnerability, and a clean scan is not proof of security. A mature verification process includes security unit tests, integration tests, negative tests and regression tests. For example, a test should verify not only that an owner can retrieve an invoice, but also that another authenticated user and an unauthenticated visitor cannot retrieve it. 6. Secure Operations and GovernanceSecurity continues after deployment. Teams should maintain an inventory of applications and dependencies, monitor vulnerability advisories, patch according to risk, protect build pipelines and rotate exposed credentials. Logs should record authentication events, privilege changes, sensitive-data access, administrative actions and significant failures. Logs must be protected against unauthorised alteration and should avoid unnecessary personal data. Organisations should establish vulnerability disclosure and response procedures. Security researchers need a safe channel for reporting defects, while staff need clear rules governing authorisation for scanning and testing. Testing another person’s system without permission can be unlawful even if the intention is educational. Privacy and data-protection obligations influence application design. Data minimisation, purpose limitation, retention controls, access rights and breach notification requirements may apply depending on jurisdiction and sector. Security controls should be proportionate, documented and reviewed for unintended effects such as discriminatory denial of access or excessive surveillance. 7. Applied Case: A Retail API FailureBackgroundThe following is an illustrative case. A small retailer releases a mobile shopping application backed by a REST API. Customers can view orders, download invoices and request refunds. ProblemA security review discovers that a customer can change the order number in a request and receive another customer’s invoice. The API also returns internal database identifiers and accepts a refund amount supplied by the mobile client. Automated testing had checked that logged-in users could access their own orders, but had not tested access to other customers’ orders. AnalysisThe first defect is broken object-level authorisation: the server checks that the caller is authenticated but not that the requested order belongs to that caller. The second is excessive trust in client data. A malicious client can alter the refund amount because the server treats the client’s value as authoritative. The exposed identifiers may assist enumeration and disclose unnecessary internal information, although changing an identifier is not itself a complete security control. Approach and solutionThe retailer introduces a server-side policy requiring the authenticated customer to be the owner of the requested order, or requiring a separately approved support role. The refund amount is calculated from trusted order and payment records on the server. API responses are reduced to necessary fields, and opaque identifiers are used where appropriate without treating opacity as authorisation. Tests are added for horizontal privilege escalation, altered refund values, missing fields and repeated requests. Rate limits and audit logs are applied to invoice and refund operations. OutcomeUnauthorised invoice access is blocked, refund decisions are based on trusted records and suspicious access attempts become detectable. The retailer also updates its SDLC checklist so that every protected object has positive and negative authorisation tests. Learning pointsAuthentication is not authorisation. Client-side restrictions are not security boundaries. Object-level checks must be performed for every request, and security testing must include adversarial changes to identifiers, roles, amounts and workflow order. 8. Contemporary Developments and LimitationsCloud-native systems, microservices, containers, serverless functions and software supply chains increase flexibility but create more identities, interfaces and dependencies. Infrastructure-as-code security checks, signed builds, provenance records, dependency pinning and protected CI/CD systems are increasingly important. Artificial intelligence can assist code review, vulnerability discovery, test generation and documentation. It can also generate insecure code, reproduce biased decisions, leak confidential prompts or create false confidence. AI-generated code must undergo the same review, testing, licensing assessment and threat modelling as human-written code. Sensitive data should not be submitted to an AI service without an approved governance basis. No technique provides complete assurance. Formal verification may prove selected properties but depends on an accurate specification; automated scanners have coverage limits; penetration tests are time-bounded; and secure code can be deployed with an insecure configuration. Security is therefore an ongoing socio-technical process involving technology, people, governance and continuous learning. Best-Practice Checklist- Define security and privacy requirements before implementation.
- Model assets, trust boundaries, threats and misuse cases.
- Use secure frameworks, parameterised queries and context-aware output encoding.
- Authenticate and authorise every protected operation on the server.
- Apply least privilege to users, services, databases and pipelines.
- Validate schemas, sizes, types and business rules; do not trust client input.
- Protect secrets, sessions, dependencies, builds and deployment configurations.
- Combine SAST, DAST, SCA, manual review and negative testing.
- Log meaningful security events without exposing secrets or unnecessary personal data.
- Patch, monitor, rehearse response and retest after changes.
- Obtain permission before security testing and provide responsible disclosure channels.
Chapter SummarySecure software development integrates security into requirements, design, coding, testing, release and operations. Threat modelling identifies assets, trust boundaries, threats and mitigations before defects become expensive to correct. STRIDE-style categories and qualitative risk analysis provide practical ways to structure this work. Injection results when data is interpreted as commands and is best mitigated through parameterised interfaces, safe APIs, validation and context-specific encoding. Broken access control occurs when the application fails to enforce permissions for a particular object or action. Insecure APIs commonly expose excessive data, trust client-supplied values, omit object-level checks or lack resource controls. Authentication, authorisation, session management, secure file handling and API governance must be designed together. SAST, DAST, SCA, fuzzing, manual review and penetration testing provide complementary evidence, but none proves that an application is secure. Professional practice requires least privilege, defence in depth, secure defaults, privacy protection, ethical testing, vulnerability response and continuous improvement. Key TermsApplication security: Protection of software, its data and its interfaces against unauthorised use, alteration or disruption. Authorisation: Determination of what an authenticated subject may do. Authentication: Verification of an identity or credential claim. Broken access control: Failure to enforce intended permissions. CSRF: An attack that causes a browser to submit an unintended authenticated request. DAST: Testing performed against a running application. Defence in depth: Use of multiple complementary security controls. Injection: Interpretation of untrusted input as commands or queries. Least privilege: Granting only the permissions necessary for a task. SAST: Automated or assisted analysis of source code or compiled code. Secure SDLC: Development lifecycle with security activities integrated into every phase. Security requirement: A testable statement of a required security property or control. Session: Server-recognised state associated with a user or client interaction. Threat model: A structured representation of assets, threats, trust boundaries and mitigations. Trust boundary: A point where assumptions about identity, authority or data quality change. XSS: Injection of script content that executes in another user’s browser. SCA: Analysis of third-party components for vulnerabilities, versions and licence issues. Review QuestionsShort Answer Questions- What is the difference between authentication and authorisation?
- Why should threat modelling begin during system design?
- State two controls that reduce SQL injection risk.
- What is the purpose of least privilege?
- Name two limitations of automated security scanners.
Long Answer Questions- Explain how security activities can be integrated into each phase of the SDLC.
- Describe a threat-modelling process for an internet-facing web application.
- Explain broken access control using both horizontal and vertical privilege escalation examples.
- Compare SAST, DAST, SCA and manual penetration testing.
- Discuss secure API design, including authentication, authorisation, validation, rate limiting and logging.
Analytical / Application Questions- A logged-in user can change
/orders/4812 to /orders/4813 and view another customer’s invoice. Identify the weakness, explain why login alone is insufficient, and propose tests and mitigations. - A developer builds a database query by concatenating a search term and relies on a deny-list of keywords. Analyse the risks and redesign the interaction securely.
- Design a brief threat model for a mobile banking API. Identify at least three assets, two trust boundaries, four threats and a suitable mitigation for each threat.
Multiple Choice Questions with AnswersQuestion 1Which activity belongs primarily to the design phase of a secure SDLC? A. Threat modelling and trust-boundary analysis B. Deleting production logs C. Disabling all authentication D. Retiring an obsolete application Correct Answer: A. Threat modelling and trust-boundary analysis Question 2What is the most direct mitigation for SQL injection? A. Hiding the database hostname B. Using parameterised queries C. Increasing screen brightness D. Adding more client-side links Correct Answer: B. Using parameterised queries Question 3A user changes an object identifier in a URL and accesses another user’s record. What weakness does this most directly demonstrate? A. Broken object-level authorisation B. Weak compression C. Poor screen resolution D. Insufficient database indexing Correct Answer: A. Broken object-level authorisation Question 4Which statement about client-side authorisation checks is correct? A. They are sufficient if JavaScript is minified B. They replace server-side checks C. They improve usability but cannot be the security boundary D. They prevent all API abuse Correct Answer: C. They improve usability but cannot be the security boundary Question 5Which testing technique analyses third-party libraries for known vulnerabilities? A. SCA B. DAST C. Usability testing D. Load balancing Correct Answer: A. SCA Question 6What is the main purpose of a trust-boundary analysis? A. To identify where assumptions about identity, authority or data quality change B. To measure monitor brightness C. To select a programming font D. To calculate storage capacity Correct Answer: A. To identify where assumptions about identity, authority or data quality change Question 7Which practice is appropriate for password storage? A. Storing plaintext passwords B. Using reversible encryption only C. Using a modern password-hashing scheme with unique salts D. Emailing passwords to administrators Correct Answer: C. Using a modern password-hashing scheme with unique salts Question 8Why should APIs limit response fields? A. To increase unnecessary data exposure B. To reduce excessive data exposure and minimise disclosure C. To remove the need for authentication D. To guarantee availability during every outage Correct Answer: B. To reduce excessive data exposure and minimise disclosure Question 9Which statement best describes defence in depth? A. Relying on one supposedly perfect control B. Using multiple complementary controls C. Removing all monitoring D. Allowing every service administrator access to every database Correct Answer: B. Using multiple complementary controls Question 10Why is a clean automated scan not proof that an application is secure? A. Scanners can miss business-logic and design flaws B. Scanners always modify production data C. Scanners cannot inspect any running application D. Scanners are designed only for physical locks Correct Answer: A. Scanners can miss business-logic and design flaws
|