Software Application Security

Secure Software Application

Complete notes for the TVET CDACC unit. Learn how to find the software that needs protection, test it, harden it, watch it, and report on it, with diagrams, code samples, practice exercises and a self test.

CDACC code SEC/CU/CS/CR/04/5/BISCED 0612 067 5 B110 hours
Start reading

About this unit

Every app you use, from a school portal to a mobile money service, stores or moves information that someone else may want. This unit teaches you to stop them.

Unit description

This unit covers the competencies required to secure a software application. You will identify the software to be secured, establish tools for application security assessment, perform the assessment, harden the software, monitor how it performs from a security point of view, and prepare reports on software security.

Unit at a glance
ItemDetail
Unit nameSoftware Application Security (Secure software application)
ISCED unit code0612 067 5 B
TVET CDACC unit codeSEC/CU/CS/CR/04/5/B
Duration110 hours
Assessment methodsObservation, written tests, oral questioning and practical tests

Learning outcomes and how these notes are arranged

  1. Identify software to be secured
  2. Establish tools for application security assessment, which also covers performing the assessment
  3. Harden software application
  4. Monitor application security performance
  5. Prepare a report on software security
  6. Manage data and information

The numbering inside each section (for example 3.5.1) follows the official CDACC outline, so you can match these notes to your syllabus line by line.

How to study with these notes

Read then try

Read a topic, then open the practice exercises at the end of each section and answer before you reveal the solution.

Track your progress

Press the finished button at the end of a section. Your progress is saved in this browser, and the button at the top returns you to where you stopped.

Practise safely

Only scan or attack systems you own or have written permission to test. Use a lab such as a virtual machine with DVWA or OWASP Juice Shop.

Legal and ethical warning

Testing an application without permission is a crime under the Computer Misuse and Cybercrimes Act, 2018 of Kenya, and under similar laws elsewhere. Always get written authorisation that states what you may test, when, and how. Everything in this course must be practised only in a lab or on systems you are allowed to test.

1. Identify software to be secured

You cannot protect what you do not know you have. The first job of a security technician is to find, name and rank the software in an organisation.

1.1 Meaning of terms

Security has its own vocabulary. Learn these terms first, because every later topic depends on them.

TermMeaning
SoftwarePrograms, data and instructions that tell a computer what to do. It is the non physical part of a computer system.
Software applicationA program designed for an end user to perform a specific task, such as word processing, banking, or learner records.
SecurityProtection of information and systems from unauthorised access, use, change or destruction.
Application securityThe practice of making applications safe at every stage: design, coding, testing, deployment and operation.
AssetAnything of value to the organisation, such as data, software, servers and reputation.
ThreatAnything that can cause harm to an asset, for example a hacker, malware or a careless employee.
VulnerabilityA weakness in the software, its configuration or its use that a threat can take advantage of.
ExploitA method, tool or piece of code that takes advantage of a vulnerability.
RiskThe chance that a threat will exploit a vulnerability, combined with the damage it would cause.
Attack surfaceAll the points where an attacker can try to enter or extract data: forms, APIs, open ports, file uploads and user accounts.
Control (countermeasure)Any action or tool that reduces risk, for example input validation, a firewall or a policy.
PatchA small update released to fix a bug or security flaw.
Zero dayA vulnerability that attackers use before the vendor has released a fix.
CVECommon Vulnerabilities and Exposures. A public list that gives every known flaw a unique number such as CVE 2021 44228.
CVSSCommon Vulnerability Scoring System. Rates the severity of a vulnerability from 0 to 10.
HardeningReducing the attack surface by removing what is not needed and tightening what remains.

The CIA triad

The whole of information security rests on three goals.

Confidentiality

Only authorised people can see the information. Tools: passwords, encryption, access control.

Integrity

Information stays accurate and is changed only by authorised people. Tools: hashing, digital signatures, version control.

Availability

Authorised users can reach the system when they need it. Tools: backups, redundancy, protection against denial of service.

Remember the difference

A threat is who or what may hurt you. A vulnerability is where you are weak. A risk is what may happen when the two meet. A door with a broken lock is a vulnerability, a thief is a threat, and a stolen laptop is the risk.

1.2 Types of software

Software is grouped by the job it does. Each group faces different security problems.

TypePurposeExamplesMain security concern
System softwareRuns and manages the hardware and gives other software a place to runWindows, Linux, Android, device drivers, firmwareUnpatched kernels, weak default settings, privilege escalation
Application softwareHelps the user do a taskWord processors, browsers, school management systems, mobile banking appsInput attacks, weak login, insecure data storage
Programming softwareUsed to write and test other softwareCompilers, IDEs, debuggers, GitStolen source code, leaked keys and passwords in code
MiddlewareConnects different applications and systemsWeb servers (Apache, Nginx), message queues, API gatewaysMisconfiguration, open management consoles
Utility softwareMaintains and protects the computerAntivirus, backup tools, disk cleanersUtilities run with high privilege, so a flaw is serious
Database softwareStores and retrieves dataMySQL, PostgreSQL, MongoDB, SQL ServerDefault accounts, exposed ports, injection
Embedded software and firmwareControls a deviceRouters, ATMs, smart meters, point of sale terminalsHard to update, hard coded passwords

1.3 Classification of software and their application

Classifying software helps you decide how much protection it needs. The same software can be classified in several ways at once.

Software By purpose By licence By deployment By criticality SystemApplicationProgrammingUtility ProprietaryOpen sourceFreewareShareware DesktopWebMobileCloud (SaaS) Mission criticalBusiness importantSupportingLow impact Choose the classification that helps you decide how much protection is needed.
Figure 1.1 Four ways of classifying software

Classification by licence

  • Proprietary: source code is closed and owned by a company. You depend on the vendor for fixes.
  • Open source: source code is public and can be checked by anyone. It is often reviewed widely, but you must still track updates yourself.
  • Freeware and shareware: free to use or free for a trial period. Download only from the official site, because fake copies often carry malware.

Classification by deployment

  • Desktop applications run on one computer. Risks include local malware and unpatched versions.
  • Web applications run on a server and are used through a browser. They face the widest range of attacks because they are reachable from the internet.
  • Mobile applications run on phones. Risks include insecure data storage, weak permissions and reverse engineering.
  • Cloud or SaaS applications are run by a provider. You still control users, settings and data, which is the customer's share of security.

Classification by criticality

ClassMeaningExampleProtection level
Mission criticalIf it fails, the organisation stopsPayment system, hospital records systemHighest: frequent testing, monitoring 24 hours, tested backups
Business importantFailure causes serious delayLearner management system, emailHigh: regular scans and patching
SupportingFailure is inconvenientInternal notice boardStandard: routine updates
Low impactLittle effect if lostTest tools with no real dataBasic: keep updated or remove

1.4 Factors influencing software selection

Security should be part of the decision when an organisation chooses software, not something added after installation.

FactorQuestions to ask
FunctionalityDoes it do what the user needs, without extra features that widen the attack surface?
Security featuresDoes it support strong authentication, encryption, role based access and audit logs?
Vendor reputationIs the vendor trusted? How quickly did they fix past vulnerabilities?
Update and support policyAre security patches released regularly? When does support end?
Vulnerability historySearch the CVE list. Many old, unfixed flaws are a warning sign.
Cost of ownershipLicence, training, support, hosting and upgrade costs, not only the purchase price.
Compatibility and integrationDoes it work with existing systems and standards without unsafe workarounds?
Scalability and performanceWill it stay stable and secure as users and data grow?
Legal and compliance needsDoes it help meet the Data Protection Act, 2019 and industry rules?
Data location and ownershipWhere is data stored and who controls it, especially for cloud services?
UsabilityHard to use software pushes users to unsafe shortcuts.

1.5 Identify software that needs security

Almost all software needs some protection, but time and money are limited, so you must decide where to start. Software needs urgent attention when it:

  • is reachable from the internet (web servers, APIs, remote access tools),
  • stores or processes sensitive data such as personal, medical, financial or exam records,
  • supports a critical business function,
  • is custom built, because nobody else has tested it,
  • is old, unsupported or has known unpatched flaws,
  • uses third party libraries and plugins that may hide weaknesses,
  • runs with administrator or root privileges.

A simple priority score

Score each application from 1 (low) to 3 (high) on the factors below, then add up. The highest totals are secured first.

ApplicationInternet facingData sensitivityBusiness importanceKnown weaknessesTotal
Learner portal333211
Fees payment gateway333110
Staff email32218
Old lab timetable tool11136
Watch out for shadow IT

Shadow IT is software that staff install or subscribe to without approval, such as free file sharing sites or unofficial messaging apps. It is invisible to security teams, so it is often unprotected. Include it when you build your list.

1.6 Identify the existing list of installed software

An software inventory is a current list of every application, its version, vendor, install date, owner and the machine it runs on. You can collect it with built in commands or with inventory tools.

Windows

winget list
Get-Package
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select DisplayName, DisplayVersion, Publisher

Linux

dpkg -l                 # Debian and Ubuntu
apt list --installed
rpm -qa                 # Red Hat, Fedora, CentOS
snap list
pip list                # Python packages
npm ls -g               # global Node packages

macOS

system_profiler SPApplicationsDataType
brew list

Record the results in a table like this one and keep it updated.

Sample software inventory
SoftwareVersionVendorHostOwnerCriticalitySupport ends
Apache HTTP Server2.4.58Apache FoundationWeb server 1ICT officerMission criticalCurrent
MySQL8.0.35OracleDB serverDatabase adminMission criticalCheck vendor
Office suite2019VendorAll staff PCsICT officerSupportingCheck vendor

1.7 Check software security updates

Most successful attacks use flaws that already have a fix. Keeping software up to date is the cheapest and most effective security control.

Where to find security information

  • The vendor's security advisories and release notes
  • The National Vulnerability Database (NVD) and CVE lists
  • Advisories from the National KE CIRT/CC and other national response teams
  • Operating system update tools: Windows Update, apt, dnf, the Play Store and App Store

Checking for updates by command

winget upgrade                    # Windows: apps with updates
sudo apt update && apt list --upgradable   # Debian and Ubuntu
sudo dnf check-update             # Fedora and Red Hat
pip list --outdated               # Python packages
npm outdated                      # Node packages
npm audit                         # Known vulnerabilities in Node packages

The patch management cycle

  1. Identify what is installed and which patches are available.
  2. Assess how serious each patch is, using the CVSS score and whether the flaw is already being attacked.
  3. Test on a copy of the system so the patch does not break anything.
  4. Deploy in a planned window, critical systems first.
  5. Verify that the patch installed and the application still works.
  6. Document what was done, when, and by whom.
End of life software

When a vendor stops supporting a product, it no longer receives security fixes. Plan to replace it, or isolate it and add extra controls until you can.

Key points to remember

  • Threat, vulnerability and risk are three different ideas.
  • Confidentiality, integrity and availability are the goals of security.
  • Classify software by purpose, licence, deployment and criticality.
  • Build and maintain an inventory, then rank applications by risk.
  • Patching promptly is the most effective control against known attacks.

Practice exercises

Exercise 1. Explain the difference between a threat, a vulnerability and a risk with one example.

A threat is something that can cause harm, such as an attacker. A vulnerability is a weakness, such as a login page with no limit on password attempts. A risk is the possible loss when a threat uses a vulnerability, for example learner records being stolen after the attacker guesses an admin password.

Exercise 2. List four factors you would consider before selecting a new school management system.

Security features (roles, encryption, audit logs), vendor support and update policy, vulnerability history, compliance with the Data Protection Act, cost of ownership, compatibility with existing systems, and where the data is stored.

Exercise 3. Write the commands you would use to list installed software on Ubuntu and to find which packages have updates.
apt list --installed
sudo apt update
apt list --upgradable
Exercise 4. Rank these by priority for securing: (a) internet facing fees portal, (b) old offline typing tutor, (c) staff email. Give reasons.

First the fees portal, because it is internet facing, holds financial data and is critical. Second staff email, which is exposed and holds sensitive messages. Last the offline typing tutor, which has no network exposure or sensitive data. It should still be updated or removed if unsupported.

Saved on this device

2. Establish tools for application security assessment

A security assessment is a planned, permitted check of an application to find weaknesses before an attacker does. This section covers the tools, the areas you test, and how to run a basic scan.

Scope Discover Scan Verify Report Retest Get permission Map the app Run the tools Remove false alarms Rate and explain Confirm the fix
Figure 2.1 The security assessment cycle

2.1 Types of tools used in software application security assessment

No single tool finds everything. Testers combine several kinds, each looking at the application from a different side.

Tool typeWhat it doesExamplesBest used
SAST (static application security testing)Reads source code without running it and flags unsafe patternsSonarQube, Semgrep, Bandit (Python), ESLint security pluginsWhile coding, in the build pipeline
DAST (dynamic application security testing)Attacks the running application from outside like a real attackerOWASP ZAP, Burp Suite, NiktoOn a test or staging copy
IAST (interactive testing)Sensors inside the running app watch what happens during testsContrast Assess, SeekerDuring quality assurance tests
SCA (software composition analysis)Checks third party libraries for known vulnerabilities and licence problemsOWASP Dependency Check, npm audit, pip audit, SnykEvery build
Network and port scannersDiscover hosts, open ports and running servicesNmap, MasscanDiscovery stage
Vulnerability scannersMatch services and versions against a database of known flawsOpenVAS (Greenbone), NessusScheduled scans
Web proxiesSit between browser and server so you can see and edit requestsBurp Suite, OWASP ZAPManual testing
Specialised exploit toolsTest one flaw type in depthsqlmap (SQL injection), Hydra (password guessing)Confirming a suspected flaw
Packet analysersCapture and inspect network trafficWireshark, tcpdumpChecking if data travels unencrypted
Configuration auditorsCompare settings with a security baselineLynis, CIS CATHardening checks
Test targets (practice labs)Deliberately vulnerable apps for learningDVWA, OWASP Juice Shop, WebGoatTraining

White box testing

The tester has full knowledge: source code, design, credentials. Most thorough. Uses SAST and code review.

Black box testing

The tester knows nothing except the address. Simulates an outside attacker. Uses DAST and scanners.

Grey box testing

The tester has partial knowledge, such as a normal user account. A common and efficient balance.

Choosing a tool

  • What type of application is it: web, mobile, desktop or API?
  • Do you have the source code (SAST) or only the running app (DAST)?
  • Is the tool free or paid, and is it kept up to date?
  • Does it produce clear reports with severity ratings?
  • Can it be automated inside your build pipeline?

2.2 Assessing a software application

Whatever the tool, you test the same key areas. The three the outline names are input validation, session management and error handling.

User Inputvalidation Session andaccess check Logic and data Safe errorand reply Reject bad data Is this user allowed? No system details shown
Figure 2.2 Where the three assessment areas sit in a request

2.2.1 Input validation

Anything that comes from outside the application is untrusted: form fields, URL parameters, cookies, headers, uploaded files and data from other systems. Input validation makes sure that data is of the expected type, length, format and range before it is used.

Validation approaches

  • Allow list (whitelist): accept only what is known to be good, for example digits only for a phone number. This is the preferred approach.
  • Deny list (blacklist): block known bad characters or words. Attackers often find ways around it, so use only as an extra layer.
  • Type, length, range and format checks: age must be a number from 1 to 120, a name must be under 60 letters, an email must match a pattern.
  • Server side validation: always required. Client side checks in the browser are only for convenience, since an attacker can skip them.
  • Canonicalisation: convert input to one standard form before checking it, so encoded tricks do not slip past.

How to test input validation

  1. List every input point: forms, search boxes, URL parameters, headers, file uploads, API fields.
  2. Send unexpected data: very long text, special characters like ' " < > ;, negative numbers, empty values.
  3. Watch the response for errors, odd behaviour or your input returned unchanged in the page.
  4. Try uploading a file with the wrong type or a changed extension.
  5. Confirm the server rejects what the browser blocks, using a proxy to change the request.
// Weak: trusts the input
$age = $_GET['age'];

// Better: validate type and range on the server
$age = filter_input(INPUT_GET, 'age', FILTER_VALIDATE_INT, ['options'=>['min_range'=>1,'max_range'=>120]]);
if ($age === false || $age === null) { http_response_code(400); exit('Invalid age'); }

2.2.2 Session management

HTTP does not remember users. A session is how an application remembers that you logged in. After login, the server gives your browser a session identifier, usually stored in a cookie, and checks it on every request. If an attacker steals or guesses that identifier, they become you.

BrowserServer 1. Send username and password over HTTPS 2. New random session ID in a secure cookie 3. Each request carries the cookie 4. Server checks ID, expiry and permissions 5. Logout: server destroys the session
Figure 2.3 A healthy session lifecycle

What to check

CheckGood practiceProblem if missing
Session ID randomnessLong, unpredictable, made by the frameworkAttacker guesses another user's ID
New ID after loginIssue a fresh ID when the user logs inSession fixation: attacker plants a known ID
Cookie flagsSecure, HttpOnly, SameSiteCookie sent over plain HTTP, stolen by scripts, or abused by other sites
TimeoutIdle timeout of minutes, absolute limit of hoursAbandoned sessions stay open on shared computers
LogoutDestroy the session on the serverOld cookie still works after logout
ID in URLNever place the session ID in the URLLeaks through history, logs and referrer headers
Concurrent sessionsLimit or alert on many logins for one accountAccount sharing or takeover goes unnoticed
Set-Cookie: sessionid=9f8a7c2e41d6...; Secure; HttpOnly; SameSite=Strict; Path=/; Max-Age=1800

2.2.3 Error handling

Errors are unavoidable, but what the application shows about them matters. A detailed error message is a gift to an attacker: it can reveal the database type, table names, file paths, software versions and even code.

Unsafe error

SQLSTATE 42S02: Table 'school.students2' doesn't exist at /var/www/app/db.php line 42

Shows the database, table name and file location.

Safe error

Something went wrong. Please try again. Reference: E4821

The full detail goes to a private log, linked by the reference number.

Assessment checklist for error handling

  • Trigger errors on purpose (bad input, missing pages, broken requests) and read what is shown.
  • Look for stack traces, debug pages, file paths, database messages and version numbers.
  • Confirm custom error pages exist for 400, 403, 404 and 500 responses.
  • Check that login errors do not reveal whether the username or the password was wrong. Use one message: Invalid username or password.
  • Check the application fails securely: if a check fails or crashes, access is denied, not granted.
  • Confirm errors are logged with time, user and request details for investigation.

2.3 Perform a basic scan for a vulnerable application

A basic scan is the first quick look: what is running, what is exposed, and are there known weaknesses. Use a lab target such as DVWA or Juice Shop that you own.

Step one: prepare and get permission

Write down the target address, the tools you will use, the time window, and who approved it. Take a snapshot or backup of the lab machine so you can restore it.

Step two: discover hosts and open ports

nmap -sn 192.168.56.0/24             # which hosts are alive
nmap -sV -p 1-1000 192.168.56.101    # open ports and service versions
nmap -sV --script vuln 192.168.56.101   # run basic vulnerability scripts

The flag -sV asks Nmap to detect the version of each service. You then compare those versions with the CVE list.

Step three: scan the web application

nikto -h http://192.168.56.101/dvwa/        # common web server problems
zap-baseline.py -t http://192.168.56.101/dvwa/   # passive scan with OWASP ZAP

Step four: review and verify results

Scanners produce false positives (reports a flaw that is not real) and false negatives (misses a real flaw). Check each finding by hand before you report it.

Reading a scan result
FieldExampleMeaning
Port and service80/tcp open http Apache 2.4.7A web server is reachable and its version is old
FindingMissing X Frame Options headerThe page can be placed in a hidden frame (clickjacking)
SeverityMediumPriority for fixing
EvidenceResponse headers capturedProof you can show to developers

2.4 Conduct a security assessment using tools

A full assessment adds deeper testing to the basic scan. A common structure follows the stages below.

  1. Planning and scoping. Agree the goals, systems in scope, out of scope items, test times and emergency contacts.
  2. Information gathering. Map pages, forms, technologies and user roles. Browse the site through a proxy so it records everything.
  3. Threat modelling. Ask what an attacker wants (data, money, disruption) and which features they would target.
  4. Automated scanning. Run DAST, port and vulnerability scanners, and SCA if you have the code.
  5. Manual testing. Test logins, access control, business logic, file upload and the areas scanners miss.
  6. Exploit verification. Confirm serious findings safely, without damaging data.
  7. Analysis and rating. Score severity and impact of each confirmed finding.
  8. Reporting and retest. Report clearly, then test again after fixes.

Example workflow with OWASP ZAP

  1. Start ZAP and set your browser to use it as a proxy.
  2. Browse every page of the lab application so ZAP builds a site map.
  3. Run the Spider to find more pages, then the Active Scan on the target.
  4. Open the Alerts tab and sort by risk level.
  5. Select an alert, read the request and response, and confirm it manually.
  6. Export the report as HTML for your documentation.
Good testing habits
  • Test on a copy, not on live systems with real data.
  • Use the least aggressive settings first.
  • Keep notes and screenshots as you go.
  • Stop and tell the owner at once if you find a critical flaw or sensitive data.

Key points to remember

  • Combine SAST, DAST, SCA and scanners, because each sees different problems.
  • Validate on the server with allow lists. Never trust client side checks.
  • Session IDs must be random, protected by cookie flags, renewed at login and destroyed at logout.
  • Errors shown to users must never expose system details.
  • Always verify scanner results by hand and test only with permission.

Practice exercises

Exercise 1. Differentiate SAST from DAST.

SAST analyses source code without running the program, so it finds flaws early but cannot see runtime problems. DAST tests the running application from outside like an attacker, so it finds real, exploitable issues but does not point to the exact line of code.

Exercise 2. State four cookie or session settings that protect a session.

Random session ID, Secure flag, HttpOnly flag, SameSite attribute, idle timeout, new ID after login, and destroying the session on logout.

Exercise 3. Why is client side validation alone not enough?

Validation in the browser can be bypassed by disabling scripts or changing the request with a proxy. The server must validate again because it is the only place the attacker cannot control.

Exercise 4. Write an Nmap command that detects service versions on ports 1 to 1000 of host 192.168.56.101.
nmap -sV -p 1-1000 192.168.56.101
Exercise 5. A login page says "Password incorrect for user amos". What is wrong and how do you fix it?

It confirms that the username exists, which helps an attacker build a list of valid accounts. Replace it with one message for all failures, such as "Invalid username or password".

Saved on this device

3. Harden software application

Hardening means making an application harder to attack by removing what it does not need, fixing what is weak, and adding protection at every layer.

3.1 Introduction to software hardening

A fresh installation is built to be easy to use, not safe. It often has default accounts, sample pages, debug modes, open ports and generous permissions. Software hardening reduces the attack surface so there are fewer ways in.

Hardening in one line: if you do not need it, remove it. If you need it, restrict it. If you restrict it, monitor it.

Why harden

  • Fewer entry points for attackers
  • Less damage when something does go wrong
  • Meets legal and industry requirements
  • Protects users' data and the organisation's reputation

Types of hardening

Application hardening

Secure code, validation, safe authentication, and removal of unused features.

Server and operating system hardening

Patches, minimal services, firewall, restricted accounts and file permissions.

Database hardening

Change default accounts, least privilege users, encryption, no public access.

Network hardening

Firewalls, segmentation, closing unused ports, secure protocols only.

3.2 Basic security principles for software applications

People, policy and training Network and perimeter: firewall, segmentation Host: patched operating system, antivirus Application: validation, authentication Data: encryption
Figure 3.1 Defence in depth: several layers, so one failure does not mean total failure
PrincipleMeaningExample
Least privilegeGive users and programs only the access they needA web app database account that can read and write its own tables but cannot drop them
Defence in depthUse several layers of protectionFirewall, secure code, encryption and monitoring together
Secure by defaultThe safest settings are on from the startNew accounts have no admin rights
Fail secureWhen something breaks, deny accessIf the permission check crashes, the user is blocked
Minimise attack surfaceFewer features, ports and accounts mean fewer targetsDisable unused modules and sample pages
Separation of dutiesNo one person controls a whole critical processOne person requests a payment, another approves it
Complete mediationCheck permission on every access, every timeVerify the user on each request, not only at login
Keep it simpleSimple designs are easier to secureOne trusted login system instead of five different ones
Open designSecurity must not depend on secret methodsUse public, tested encryption instead of a homemade scheme
Never trust inputTreat all outside data as hostile until validatedValidate forms, headers, files and API calls
AccountabilityActions can be traced to a personAudit logs with user, time and action

3.3 Software configuration

Many breaches come from misconfiguration, not clever hacking. Secure configuration means setting every option deliberately, using a documented baseline such as the CIS Benchmarks as a guide.

Configuration hardening checklist

AreaActions
AccountsChange or disable default accounts and passwords. Remove unused accounts. Use unique admin accounts, not shared ones.
Features and servicesUninstall sample applications, demo pages and unused modules. Stop unused services.
Debug and error settingsTurn off debug mode and detailed errors in production. Use custom error pages.
Files and permissionsApply least privilege on files and folders. Keep configuration and upload folders outside the web root where possible. Do not run the application as administrator or root.
EncryptionUse HTTPS with a valid certificate and modern TLS versions. Encrypt sensitive data stored on disk and in databases.
SecretsNever place passwords, API keys or tokens in source code. Use environment variables or a secrets manager.
NetworkOpen only required ports. Allow database access only from the application server. Hide management consoles from the internet.
UpdatesApply operating system, framework and library patches regularly.
LoggingTurn on security logging and send logs to a protected central place.
BackupsBack up configuration and data, store copies offline, and test restoring.
# Example: hardening Apache in the configuration file
ServerTokens Prod          # hide detailed version
ServerSignature Off
TraceEnable Off
Options -Indexes           # stop directory listing

# Example: check and lock down a Linux firewall
sudo ufw default deny incoming
sudo ufw allow 443/tcp
sudo ufw enable

3.4 Common threats to applications

The OWASP (Open Worldwide Application Security Project) publishes the Top 10 list of the most serious web application risks. Learn it, because most exam and real world problems come from it.

OWASP Top 10 (2021 edition) in simple words
CodeRiskSimple meaning
A01Broken access controlUsers can do or see things they should not, such as opening another user's record by changing a number in the URL
A02Cryptographic failuresSensitive data is not encrypted, or weak encryption is used
A03InjectionUntrusted data is run as a command or query (SQL, command, LDAP)
A04Insecure designThe application was planned without security in mind
A05Security misconfigurationDefault settings, open services, missing headers, verbose errors
A06Vulnerable and outdated componentsOld libraries and software with known flaws
A07Identification and authentication failuresWeak passwords, no lockout, poor session handling
A08Software and data integrity failuresUnverified updates, insecure deserialization, tampered pipelines
A09Security logging and monitoring failuresAttacks happen without being recorded or noticed
A10Server side request forgeryThe server is tricked into making requests to internal systems

Other common threats

  • Malware: viruses, worms, trojans, ransomware and spyware.
  • Phishing and social engineering: tricking people into giving passwords or running malicious files.
  • Denial of service (DoS and DDoS): flooding an application so real users cannot reach it.
  • Man in the middle: an attacker secretly reads or changes traffic between two parties.
  • Brute force and credential stuffing: guessing passwords or trying leaked passwords from other breaches.
  • Insider threats: staff who misuse access, deliberately or by mistake.
  • Supply chain attacks: attackers compromise a library or update that many apps trust.

3.5 Software vulnerabilities

The following five vulnerability groups are named in the outline. For each you should know what it is, how it works, what damage it does, and how to prevent it.

3.5.1 Injection attacks (SQL injection, command injection)

Injection happens when an application mixes untrusted data with a command or query, so the interpreter cannot tell where the data ends and the instruction begins.

Attacker types' OR '1'='1 Login formno validation Query built byjoining strings Databasereturns all users Result: login succeeds without a valid password
Figure 3.2 How SQL injection reaches the database

SQL injection example

// Vulnerable code: builds the query by joining text
$sql = "SELECT * FROM users WHERE name='" . $_POST['name'] . "' AND pass='" . $_POST['pass'] . "'";

// If the attacker enters   ' OR '1'='1   the query becomes:
SELECT * FROM users WHERE name='' OR '1'='1' AND pass='' OR '1'='1'
// The condition is always true, so every row is returned.

Types of SQL injection

  • In band: results appear directly in the page (error based or union based).
  • Blind: no data is shown, so the attacker learns from true or false behaviour or from time delays.
  • Out of band: data is sent to a server the attacker controls.

Prevention

// Parameterised query (prepared statement) with PDO in PHP
$stmt = $pdo->prepare("SELECT * FROM users WHERE name = :name");
$stmt->execute([':name' => $name]);

# Python with a placeholder
cursor.execute("SELECT * FROM users WHERE name = %s", (name,))
  • Use parameterised queries or an ORM. This keeps data and code apart and is the main defence.
  • Validate input with allow lists.
  • Give the database account only the rights it needs.
  • Do not show database errors to users.
  • Use a web application firewall as an extra layer, not as the only defence.

Command injection

Here the application passes user input to the operating system shell. An attacker adds extra commands using characters such as ;, && or |.

// Vulnerable: the user supplies a host name to ping
system("ping -c 4 " . $_GET['host']);
// Input   8.8.8.8; cat /etc/passwd   runs a second command

# Safer in Python: no shell, arguments passed as a list, input checked first
import ipaddress, subprocess
ip = str(ipaddress.ip_address(host))
subprocess.run(["ping", "-c", "4", ip], check=True)

Prevention: avoid calling the shell at all, use built in library functions, pass arguments as a list, validate against an allow list, and run the application with low privileges.

3.5.2 Broken authentication and session management

Authentication proves who you are. When it is weak, attackers log in as someone else, often an administrator.

Common weaknesses

  • Weak or default passwords such as admin and 123456
  • No limit on failed logins, allowing brute force and credential stuffing
  • Passwords stored in plain text or with fast, weak hashes
  • Session IDs that are predictable, exposed in the URL, or never expire
  • Weak password reset, such as easy security questions
  • No multi factor authentication for sensitive accounts

Prevention

  • Enforce long passwords (length matters more than odd symbols) and check them against lists of known leaked passwords.
  • Store passwords using a slow, salted hash such as bcrypt, scrypt or Argon2. Never store them in plain text.
  • Add multi factor authentication (something you know, have, and are).
  • Lock or slow down accounts after repeated failures and send an alert.
  • Use secure session handling from section 2.2.2: random IDs, cookie flags, timeouts and proper logout.
  • Use the same generic message for all login failures.
# Bad: plain text or a fast hash
password = "amos123"
md5("amos123")

# Good: a slow salted hash
import bcrypt
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))
bcrypt.checkpw(password.encode(), hashed)

3.5.3 Cross site scripting (XSS)

XSS occurs when an application includes untrusted input in a web page without proper handling, so the attacker's script runs in the victim's browser as if it came from the trusted site.

Attacker postsa comment with script Website stores itwithout cleaning Victim opensthe page Script runs inthe victim's browser Cookie sent tothe attacker
Figure 3.3 Stored XSS: a script saved on the site attacks every visitor
TypeHow it works
Stored (persistent)The malicious script is saved on the server, for example in a comment or profile, and hits every visitor.
ReflectedThe script is inside a link. The server echoes it back in the page, and it runs when a victim clicks the link.
DOM basedThe flaw is in browser side JavaScript that writes unsafe data into the page.

Impact: stolen session cookies, fake login forms, page defacement, redirection to harmful sites, and actions performed as the victim.

<!-- Vulnerable: prints the input directly -->
<p>Hello <?php echo $_GET['name']; ?></p>
<!-- If name is a script tag, the browser runs it -->

<!-- Safe: encode output for HTML -->
<p>Hello <?php echo htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8'); ?></p>

// In JavaScript, use textContent instead of innerHTML
element.textContent = userInput;

Prevention

  • Output encoding for the place where data is used: HTML, attribute, JavaScript, URL.
  • Validate input with allow lists.
  • Use frameworks that escape output automatically, such as React, Angular and template engines with auto escaping.
  • Add a Content Security Policy header to limit which scripts may run.
  • Set the HttpOnly flag on cookies so scripts cannot read them.
  • Sanitise any HTML you must accept, using a trusted library such as DOMPurify.

3.5.4 Insecure deserialization

Serialization turns an object into text or bytes so it can be stored or sent. Deserialization rebuilds the object. If the data comes from an untrusted source and the application rebuilds it blindly, an attacker can change objects or make the application run their code.

Example situations

  • A cookie holds a serialised user object with a field role=user. The attacker edits it to role=admin.
  • A Python application uses pickle to load data from users. Pickle can execute code while loading.
  • Java or PHP objects with dangerous methods are triggered during loading.
# Dangerous: pickle on data from the user
import pickle
data = pickle.loads(request.cookies["profile"])

# Safer: use a plain data format and validate it
import json
data = json.loads(request.cookies["profile"])
if not isinstance(data.get("name"), str) or len(data["name"]) > 60:
    abort(400)

Prevention

  • Do not deserialise data from untrusted sources. Prefer simple formats such as JSON.
  • Sign the data with a secret key (HMAC) and verify the signature before use, so tampering is detected.
  • Never trust roles or permissions stored in something the user controls. Keep them on the server.
  • Allow only a short list of expected classes during deserialisation.
  • Run the code with low privileges and log deserialisation failures.

3.5.5 Misconfigured security headers

HTTP security headers are instructions the server sends to the browser to switch on built in protections. When they are missing or wrong, the browser does not apply them and attacks become easier.

HeaderPurposeSample value
Content-Security-PolicyControls where scripts, images and styles may load from. Strong protection against XSS.default-src 'self'
Strict-Transport-SecurityForces the browser to use HTTPS only.max-age=31536000; includeSubDomains
X-Frame-OptionsStops your page being placed in a frame on another site (clickjacking).DENY
X-Content-Type-OptionsStops the browser guessing file types.nosniff
Referrer-PolicyLimits what address information is sent to other sites.strict-origin-when-cross-origin
Permissions-PolicyRestricts browser features such as camera and location.camera=(), geolocation=()
Set-Cookie flagsProtect cookies from theft and misuse.Secure; HttpOnly; SameSite=Strict

Also remove headers that reveal too much

Headers such as Server: Apache/2.4.7 (Ubuntu) and X-Powered-By: PHP/5.5 tell attackers exactly which versions to target.

# Nginx example
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Content-Security-Policy "default-src 'self'" always;
server_tokens off;

Test your headers with browser developer tools (Network tab), with curl -I https://yoursite, or with online header checkers, then fix any that are missing.

3.6 Security measures in software application

Hardening is a combination of technical, procedural and human measures. Use this list as a summary of what to apply.

Secure development

  • Follow secure coding standards
  • Review code before release
  • Test security in every build
  • Keep libraries updated

Access control

  • Role based permissions
  • Least privilege
  • Multi factor authentication
  • Check access on every request

Data protection

  • HTTPS everywhere
  • Encrypt sensitive data at rest
  • Hash passwords properly
  • Collect only necessary data

Protective tools

  • Web application firewall
  • Antivirus and endpoint protection
  • Intrusion detection
  • Rate limiting on logins and APIs

Operations

  • Regular patching
  • Backups with tested restores
  • Central logging and alerts
  • Incident response plan

People and policy

  • Security awareness training
  • Clear password and access policy
  • Onboarding and exit procedures
  • Regular audits

Secure software development life cycle (SSDLC)

Security is cheaper when it begins early. At each stage of development add a security activity.

StageSecurity activity
RequirementsState security and privacy needs, such as who may see what
DesignThreat modelling and secure architecture review
CodingSecure coding rules, peer review, SAST
TestingDAST, SCA, penetration testing
DeploymentHardened configuration, secrets management, HTTPS
MaintenancePatching, monitoring, incident response, periodic retesting
Security is a process, not a product

No application is ever finished and perfectly safe. New flaws appear and attackers change tactics. Hardening, testing and monitoring must be repeated regularly.

Key points to remember

  • Hardening removes, restricts and monitors. Defence in depth adds layers.
  • Injection is stopped by parameterised queries and validated input.
  • Broken authentication is stopped by strong hashing, multi factor authentication, lockout and safe sessions.
  • XSS is stopped mainly by output encoding and a Content Security Policy.
  • Never deserialise untrusted data. Sign data you must trust.
  • Set security headers and hide version information.

Practice exercises

Exercise 1. Explain the principle of least privilege with an example.

Users and programs receive only the permissions needed for their task. For example, the database account used by a website should be able to select, insert and update its own tables, but not create users or drop the database. If the site is attacked, the damage is limited.

Exercise 2. Rewrite this query so it is safe: "SELECT * FROM learners WHERE adm='" + adm + "'"
stmt = pdo.prepare("SELECT * FROM learners WHERE adm = :adm")
stmt.execute({"adm": adm})

The placeholder keeps the input as data, so it cannot change the query.

Exercise 3. Distinguish stored XSS from reflected XSS.

In stored XSS the script is saved on the server and runs for every visitor who views the affected page. In reflected XSS the script travels inside a request, usually a link, and is echoed back immediately to the person who clicked it.

Exercise 4. Name four security headers and what each does.

Content Security Policy limits script sources. Strict Transport Security forces HTTPS. X Frame Options prevents clickjacking. X Content Type Options stops file type guessing.

Exercise 5. A site stores the user role in a cookie as plain text. What could an attacker do, and what is the fix?

The attacker can edit the cookie to claim an admin role. The fix is to keep the role on the server tied to the session, and if data must be kept in a cookie, sign it and verify the signature.

Exercise 6. List five configuration steps to harden a web server.

Apply updates, disable directory listing, hide version banners, remove sample files and unused modules, enable HTTPS, run the service as a low privilege user, close unused ports, and turn on logging.

Saved on this device

4. Monitor application security performance

Prevention is never perfect. Monitoring lets you notice an attack quickly, understand what happened, and respond before serious damage is done.

4.1 Factors to consider in monitoring application security performance

FactorWhat to think about
Criticality of the applicationMonitor the most important and most exposed applications most closely.
Security objectives and baselineKnow what normal looks like (usual login times, traffic and file changes) so you can spot the abnormal.
What to monitorLogins, access to sensitive data, administrator actions, errors, configuration and file changes.
Legal and compliance requirementsSome laws and standards require logs to be kept for a set time, for example under the Data Protection Act.
Tools and costFree tools such as Wazuh and the Elastic stack, or paid tools. Consider setup effort, storage and skills.
Alert qualityToo many false alarms cause alert fatigue, and people start ignoring them. Tune alerts carefully.
Staff and response processSomeone must be responsible for reading alerts and there must be a clear response procedure.
Storage and retentionLogs grow quickly. Plan space, how long to keep them, and secure archiving.
PrivacyLogs may contain personal data. Collect only what is needed and protect the logs.
Performance impactMonitoring should not slow the application down noticeably.

4.2 Implementation of monitoring solutions

Sourcesapps, servers Collectagents, syslog Storecentral and safe Analyserules, baselines Alertemail, dashboard Respondand improve
Figure 4.1 A monitoring pipeline from event to response

Steps to implement monitoring

  1. Define goals. What attacks or events must you detect?
  2. List sources. Web server, application, database, operating system, firewall, authentication system.
  3. Turn on logging at each source with enough detail.
  4. Centralise logs in one protected place so an attacker who breaks into one machine cannot erase the evidence.
  5. Set a baseline of normal activity.
  6. Create alert rules with clear thresholds and severity levels.
  7. Assign responsibility and write a response procedure.
  8. Test and tune by simulating attacks and removing noisy alerts.
  9. Review regularly and update as the application changes.

Types of monitoring solutions

SolutionRoleExamples
SIEM (security information and event management)Collects and correlates logs from many sources and raises alertsWazuh, Splunk, Elastic Security, Microsoft Sentinel
Web application firewall (WAF)Filters and logs malicious web requestsModSecurity, Cloudflare WAF, AWS WAF
IDS and IPSDetects (IDS) or blocks (IPS) suspicious network trafficSnort, Suricata
File integrity monitoring (FIM)Detects unexpected changes to filesWazuh, AIDE, Tripwire, OSSEC
Application performance monitoring (APM)Watches speed, errors and availability, which can reveal attacksPrometheus and Grafana, Zabbix, Nagios
Endpoint detection and response (EDR)Watches devices for malicious behaviourWazuh agent, commercial EDR tools
Uptime and certificate monitorsAlert when the site is down or a certificate is about to expireUptime Kuma, Zabbix

4.3 Logs management and monitoring

A log is a time stamped record of an event. Logs answer the questions: who did what, when, from where, and with what result.

Types of logs

  • Application logs: errors, user actions, business events.
  • Access logs: every request to the web server, with address, page and response code.
  • Authentication logs: successful and failed logins, password changes, lockouts.
  • System logs: operating system events, service starts and stops.
  • Database logs: queries, failed connections, permission changes.
  • Audit logs: administrator actions and changes to settings or permissions.
  • Firewall and network logs: allowed and blocked connections.

What a good log entry contains

Time (with time zone), user or account, source IP address, action, target resource, result (success or failure), and a request or session reference. Never log passwords, full card numbers or session tokens.

192.168.1.45 - amos [29/Sep/2026:09:14:22 +0300] "POST /login HTTP/1.1" 401 512 "Mozilla/5.0"
Sep 29 09:14:23 web1 sshd[2210]: Failed password for invalid user admin from 203.0.113.9 port 51422 ssh2

The log management life cycle

  1. Generate logs at the sources.
  2. Collect them to a central server.
  3. Normalise them into a common format and synchronise time (use NTP so clocks agree).
  4. Store securely with limited access and protection against changes.
  5. Analyse manually and with automated rules.
  6. Retain for the required time, then dispose of them safely.

Useful commands for reading logs

tail -f /var/log/apache2/access.log              # watch requests live
grep "Failed password" /var/log/auth.log          # find failed SSH logins
journalctl -u nginx --since "1 hour ago"          # service logs with systemd
grep " 500 " /var/log/nginx/access.log | wc -l    # count server errors
Windows event numbers worth knowing

4624 is a successful logon. 4625 is a failed logon. 4720 is a new user account created. 4672 shows special privileges assigned to a logon. Many of these can be searched in Event Viewer.

Protect your logs

Attackers often delete or edit logs to hide their tracks. Send copies to a separate server, restrict who can change them, and use hashing or write once storage for important logs.

4.4 Key metrics to monitor

Metrics are measurable signs of security health. The outline names three key ones. Others give a wider view.

4.4.1 Failed login attempts

A burst of failed logins is a classic sign of brute force (many guesses on one account) or credential stuffing (one guess each on many accounts using leaked passwords).

PatternLikely meaningResponse
Many failures on one account in a short timeBrute force on that accountLock or delay the account, notify the owner
One or two failures on many accounts from one addressCredential stuffing or password sprayingBlock or rate limit the address, force resets if any succeeded
Failures followed by a successAttacker may have guessed the passwordInvestigate the session, reset the password
Logins from new countries or at odd hoursStolen credentialsRequire extra verification
# Top addresses with failed SSH logins
grep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head

Example alert rule: raise a medium alert when one address causes 10 failed logins within 5 minutes, and a high alert if a success follows.

4.4.2 Unusual API requests

APIs are the doorway that mobile apps and other systems use to reach your data, so attackers probe them heavily. Look for these signs.

  • A sudden rise in the number of requests from one client or address (scraping or denial of service)
  • Requests to endpoints that are rarely used, or that do not exist (scanning)
  • Many 401 and 403 responses (someone testing access) or 404 responses (guessing paths)
  • Many 500 errors after strange input (someone probing for injection)
  • Unusually large responses or many sequential record numbers requested (data harvesting)
  • Requests at unusual hours, from unusual places, or with odd user agent names such as scanning tools
  • Changes to normal request size, method or parameters
# Which addresses make the most requests?
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head

# Which requests return 403 or 404?
awk '$9 ~ /403|404/ {print $1, $7, $9}' /var/log/nginx/access.log | head

Controls: rate limiting, API keys or tokens with expiry, input schema validation, authentication on every endpoint and an API gateway with logging.

4.4.3 Changes in application files

Attackers often modify or add files, for example a hidden web shell, a changed login page, or altered configuration. File integrity monitoring compares files to a known good record and reports differences.

What to watch

  • Application code and scripts, especially in web folders
  • Configuration files
  • Uploaded files folders, where new scripts should never appear
  • System files and libraries
  • File permissions and ownership
# Record a baseline of file hashes
find /var/www/html -type f -exec sha256sum {} \; > baseline.txt

# Later, compare against the baseline
sha256sum -c baseline.txt | grep -v ": OK"

# Files changed in the last day
find /var/www/html -type f -mtime -1

Proper tools such as AIDE, Tripwire or Wazuh automate this, keep the baseline safe, and send alerts. Every unexpected change should be checked. Expected changes, such as a planned update, should be recorded so they are not mistaken for attacks.

Other useful metrics

MetricWhy it matters
Number of vulnerabilities open by severityShows the overall security position
Patch compliance percentageHow much software is up to date
Mean time to detect (MTTD)How fast attacks are noticed
Mean time to respond or repair (MTTR)How fast problems are contained and fixed
Error rate and response timeSudden changes can indicate attack or failure
Privileged account activityMisuse of admin rights is very damaging
Blocked attacks by the WAFShows attack volume and trends

Key points to remember

  • Know your baseline so that unusual activity stands out.
  • Centralise and protect logs. Synchronise time on all systems.
  • Three key metrics: failed logins, unusual API requests and file changes.
  • Tune alerts to avoid alert fatigue, and always define who responds.

Practice exercises

Exercise 1. State four items that a useful log entry should contain.

Timestamp with time zone, user or account, source IP address, action performed, target resource, and whether it succeeded or failed.

Exercise 2. Distinguish brute force from credential stuffing.

Brute force tries many passwords against one account. Credential stuffing tries username and password pairs leaked from other breaches against many accounts, usually one or two attempts each.

Exercise 3. Give three signs of unusual API activity.

A sudden spike in requests from one address, many 401, 403 or 404 responses, requests to unknown endpoints, very large responses, and requests at odd hours or from unexpected locations.

Exercise 4. Why should logs be sent to a separate server?

If an attacker takes over the application server they may delete or alter the local logs to hide their actions. A separate protected copy preserves the evidence.

Exercise 5. Describe how you would detect changes to files in a website folder.

Create a baseline of SHA 256 hashes of every file, store it safely off the server, and compare regularly, or install a file integrity tool such as AIDE or Wazuh that alerts when a file is added, changed or removed.

Saved on this device

5. Prepare a report on software security

Your findings only matter if the right people understand them and act. A good security report is clear, accurate, evidence based and tells the reader what to do next.

Know your readers

Managers need a short summary of risk and cost. Developers and system administrators need technical detail to reproduce and fix each problem. A good report serves both, by placing the summary first and the details later.

5.1 Application summary

5.1.1 Overview of the application

Describe what the application is, who uses it, what data it holds, where it runs, and the technologies involved (language, framework, database, server, hosting). Include the version and the date tested.

5.1.2 Security goals

State what must be protected and why, in terms of confidentiality, integrity and availability. For example: protect learner records from exposure, ensure marks cannot be changed without authorisation, and keep the portal available during registration.

5.1.3 Key findings

Give a short executive summary: the number of findings by severity, the most serious problems, and the overall conclusion in plain language. Example: The assessment found 2 critical, 3 high, 5 medium and 4 low issues. The most serious is SQL injection on the login page that allows access to all learner records.

5.2 Methodology

5.2.1 Assessment approach

Say how the test was done: black, grey or white box, manual and automated, the dates, and any standard followed, such as the OWASP Testing Guide or OWASP Top 10. State the scope and anything left out.

5.2.2 Tools used

List each tool with its version and purpose, for example OWASP ZAP 2.15 for dynamic scanning, Nmap for port discovery, and Nikto for web server checks.

5.2.3 Testing environment

Describe where the tests ran (production, staging or a lab copy), the network position of the tester, accounts and roles used, and any limits such as time windows and excluded systems.

5.2.4 Vulnerabilities and risks

Explain how findings were identified and grouped, and how risk was judged. This links to the rating method below.

5.2.5 Identified vulnerabilities

Each finding should be written in the same structure so it is easy to read and act on.

Template for one finding
FieldExample
ID and titleF01 SQL injection in login form
Locationhttps://portal.example.ke/login, parameter username
DescriptionUser input is added directly to the database query, so an attacker can change the query.
EvidenceScreenshot and request showing login as admin with no password
Steps to reproduce1. Open the login page. 2. Enter ' OR '1'='1 as username. 3. Submit and observe admin access.
Severity and impactCritical. Full access to learner records.
RecommendationUse parameterised queries, validate input, limit database rights.
ReferenceOWASP A03 Injection, CWE 89

5.2.6 Severity and impact

Severity says how bad a flaw is. Impact says what could be lost: data exposure, financial loss, downtime, legal penalties or damage to reputation. Always explain the impact in terms the organisation understands.

5.2.7 Risk rating methodology

Risk is commonly judged by combining likelihood (how easy and how probable an attack is) with impact (how damaging it would be).

Risk = Likelihood × Impact
Risk matrix
Likelihood / ImpactLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowLowLowMedium
CVSS score bands often used for severity
ScoreSeverityMeaning
9.0 to 10.0CriticalEasy to exploit with very serious results. Fix immediately.
7.0 to 8.9HighSerious. Fix urgently.
4.0 to 6.9MediumFix in the normal schedule.
0.1 to 3.9LowFix when convenient.
0.0None or informationalNote for awareness.

5.3 Security controls

5.3.1 Existing security measures

List the protections already in place, such as HTTPS, password policy, firewall, backups, logging and multi factor authentication. Recognising what works is fair and useful.

5.3.2 Effectiveness

State how well each control performed during testing. For example: HTTPS was correctly configured (effective). Password policy allowed six character passwords (partly effective). No lockout after failed logins (not effective).

Example control review
ControlFindingRating
HTTPS and TLSValid certificate, modern versionsEffective
Password policyMinimum six charactersPartly effective
Account lockoutUnlimited attempts allowedNot effective
BackupsDaily, but restore never testedPartly effective

5.4 Recommendations

5.4.1 Security improvements

For every finding give a specific, practical fix, not a general statement. Say what to change and where. For example, replace string built queries in login.php with prepared statements.

5.4.2 Best practices

Suggest wider improvements that prevent whole classes of problems: secure coding training, code review, regular scanning in the build pipeline, patch policy, multi factor authentication, and central log monitoring.

5.4.3 Remediation timeline

Example timeline
PrioritySeveritySuggested time to fixOwner
1CriticalWithin 24 to 72 hoursDevelopment lead
2HighWithin 7 daysDevelopment lead
3MediumWithin 30 daysSystem administrator
4LowWithin 90 days or next releaseSystem administrator

5.5 Conclusion

Summarise the overall security position, the most important actions, and the next steps such as a retest date. Keep it short, honest and free of blame. Do not promise that the application is fully secure, because no test can prove that.

5.6 Appendices

5.6.1 Detailed findings

Place long technical evidence here: full scan output, request and response captures, screenshots, and step by step reproduction notes.

5.6.2 References

List standards and sources used, for example the OWASP Top 10, the OWASP Testing Guide, the CVE and NVD databases, CVSS documentation, and vendor advisories.

Report outline at a glance

Title page: application name, version, date, tester, confidentiality level
Document control: version history, distribution list
1. Application summary
   1.1 Overview   1.2 Security goals   1.3 Key findings
2. Methodology
   2.1 Approach   2.2 Tools   2.3 Environment
   2.4 Vulnerabilities and risks   2.5 Identified vulnerabilities
   2.6 Severity and impact   2.7 Risk rating method
3. Security controls
   3.1 Existing measures   3.2 Effectiveness
4. Recommendations
   4.1 Improvements   4.2 Best practices   4.3 Remediation timeline
5. Conclusion
6. Appendices
   6.1 Detailed findings   6.2 References
Writing tips
  • Use plain language and short sentences.
  • Every claim needs evidence.
  • Rate findings consistently, using the same method throughout.
  • Mark the report confidential and share it only with authorised people.
  • Never put real passwords or personal data in the report. Hide or mask them.

Key points to remember

  • Lead with a clear summary, then methodology, findings, controls and recommendations.
  • Risk equals likelihood multiplied by impact.
  • Each finding needs evidence, impact, steps to reproduce and a specific fix.
  • Give a realistic timeline and an owner for each fix, then retest.

Practice exercises

Exercise 1. List the main sections of a software security report.

Application summary (overview, goals, key findings), methodology, vulnerabilities and risks, security controls, recommendations, conclusion and appendices.

Exercise 2. A flaw is easy to exploit and would expose all customer data. Rate its risk.

Likelihood is high and impact is high, so the risk is critical and must be fixed immediately.

Exercise 3. Write a finding entry for a login page that reveals detailed database errors.

Title: Verbose database errors on login page. Description: Invalid input causes a message showing the database type, table name and file path. Impact: Helps attackers plan injection attacks. Medium severity. Recommendation: Show a generic message, log the detail privately, and disable debug mode in production. Reference: OWASP A05 Security misconfiguration.

Exercise 4. Why include existing security measures in a report?

It gives a fair picture, shows what should be kept, and helps decide where extra effort is needed. It also avoids wasting money replacing controls that already work.

Saved on this device

6. Manage data and information

Applications exist to handle data. This section covers how to keep records and information organised, correct, protected and lawfully used, which is part of the unit's outcomes.

6.1 Data, information and records

  • Data is raw facts, such as marks, names and numbers.
  • Information is data that has been processed so it has meaning, such as a learner's average grade.
  • Records are information kept as evidence, for example security reports, logs and inventories.

6.2 Data classification

Not all data needs the same protection. Classify it, then apply controls to match.

ClassExampleHandling
PublicCourse brochures, published noticesNo special controls, but protect integrity
InternalStaff meeting notes, internal proceduresOnly staff may access
ConfidentialLearner records, contracts, security reportsAccess on need to know, encrypted, logged
RestrictedPasswords, health data, payment data, exam papers before releaseStrictest control, strong encryption, minimal people, full audit

6.3 Data life cycle and protection

  1. Collect only what you need, and tell people why.
  2. Store in secure, access controlled places. Encrypt sensitive data at rest.
  3. Use according to purpose and permissions.
  4. Share only through approved, encrypted channels.
  5. Archive what must be kept for legal or business reasons.
  6. Dispose securely when no longer needed: secure delete, overwrite or physically destroy media.

Data at rest

Stored on disks, databases and backups. Protect with disk or database encryption and access control.

Data in transit

Moving across a network. Protect with HTTPS and TLS, secure VPN and encrypted email where needed.

Data in use

Being processed in memory. Protect with least privilege, screen locks and secure coding.

6.4 Backup and recovery

Backups protect availability and integrity when data is lost, corrupted or held to ransom.

The 3 2 1 rule: keep 3 copies of your data, on 2 different types of media, with 1 copy stored off site or offline.
  • Full, incremental and differential backups offer different trade offs between speed and storage.
  • Encrypt backups and restrict who can reach them.
  • Test restores regularly. A backup that cannot be restored is worthless.
  • Set recovery goals: how much data you can afford to lose (RPO) and how fast you must be back (RTO).

6.5 Legal and ethical requirements in Kenya

  • Data Protection Act, 2019. Organisations that collect personal data must process it lawfully, fairly and transparently, collect only what is necessary, keep it accurate, store it no longer than needed, secure it, and respect the rights of the person, such as access and correction. The Office of the Data Protection Commissioner oversees compliance, and serious breaches must be reported within the time the law sets (72 hours).
  • Computer Misuse and Cybercrimes Act, 2018. Defines offences such as unauthorised access, interference with data and systems, and misuse of computer systems.
Check current law

Laws and regulations are updated from time to time. For any real project, confirm the current text and get advice from a qualified person.

Key points to remember

  • Classify data, then protect it according to its class.
  • Protect data at rest, in transit and in use.
  • Follow the 3 2 1 backup rule and test restores.
  • Collect only necessary personal data and dispose of it securely.

Practice exercises

Exercise 1. Explain the 3 2 1 backup rule.

Keep three copies of the data, on two different media types, with one copy off site or offline, so a single disaster or attack cannot destroy everything.

Exercise 2. Classify these: a public notice, learner exam results, and administrator passwords.

The public notice is public. Learner exam results are confidential. Administrator passwords are restricted.

Exercise 3. Give three duties of an organisation that holds personal data.

Collect only necessary data with a clear purpose, keep it secure and accurate, do not keep it longer than needed, allow people to see and correct their data, and report serious breaches promptly.

Saved on this device

Self test quiz

Twenty questions covering the whole unit. Choose an answer for each, then press the check button to see your score and the reasons.

Saved on this device

Glossary

Quick meanings of the key words used in this unit. Type to filter.

TermMeaning
Access controlRules that decide who can see or do what in a system.
Allow listA list of inputs or items that are permitted. Everything else is rejected.
APIApplication programming interface. A way for programs to talk to each other.
Attack surfaceAll the places where an attacker can try to get in.
AuthenticationProving who you are, for example with a password.
AuthorisationDeciding what an authenticated person is allowed to do.
BaselineA record of normal or approved settings and behaviour used for comparison.
Brute forceTrying many passwords or keys until one works.
ClickjackingTricking a user into clicking something hidden inside a frame.
CVEA public identifier for a known vulnerability.
CVSSA scoring system that rates vulnerability severity from 0 to 10.
DASTDynamic testing of a running application from outside.
Defence in depthUsing several layers of protection.
DeserializationRebuilding an object from stored or transmitted data.
EncryptionScrambling data so only holders of the key can read it.
ExploitCode or method that uses a vulnerability.
False positiveA reported problem that is not real.
File integrity monitoringDetecting unexpected changes to files.
HardeningReducing attack surface by removing, restricting and securing.
HashingTurning data into a fixed size fingerprint that cannot be reversed.
InjectionSending untrusted data that is run as a command or query.
Least privilegeGiving only the access needed and no more.
LogA time stamped record of an event.
Multi factor authenticationUsing two or more proofs of identity, such as a password and a phone code.
PatchAn update that fixes a bug or vulnerability.
Penetration testAn authorised simulated attack to find weaknesses.
PhishingFake messages that trick people into giving information or running malware.
RiskLikelihood of harm combined with its impact.
SASTStatic analysis of source code without running it.
SaltRandom data added to a password before hashing.
SCASoftware composition analysis. Checks third party components for known flaws.
SessionThe period during which the server recognises a logged in user.
SIEMA system that collects, correlates and alerts on logs from many sources.
SQL injectionInserting SQL code through input to change a database query.
TLSThe protocol that encrypts traffic between a browser and a server (HTTPS).
VulnerabilityA weakness that can be exploited.
WAFWeb application firewall. Filters malicious web requests.
XSSCross site scripting. Injecting scripts that run in other users' browsers.
Zero dayA flaw exploited before the vendor has a fix.