0% found this document useful (0 votes)
39 views37 pages

Secure Coding Techniques Exam Guide

The document outlines the examination structure for a course on Secure Coding Techniques, detailing topics such as network types, cybersecurity services, and the importance of cybersecurity in modern environments. It discusses various cyber threats, including Cross-Site Scripting (XSS) and methods of attack, as well as preventive measures. The content emphasizes the critical nature of cybersecurity for organizations to protect sensitive data and maintain operational integrity.

Uploaded by

lathaavvar6997
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views37 pages

Secure Coding Techniques Exam Guide

The document outlines the examination structure for a course on Secure Coding Techniques, detailing topics such as network types, cybersecurity services, and the importance of cybersecurity in modern environments. It discusses various cyber threats, including Cross-Site Scripting (XSS) and methods of attack, as well as preventive measures. The content emphasizes the critical nature of cybersecurity for organizations to protect sensitive data and maintain operational integrity.

Uploaded by

lathaavvar6997
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Set No.

1
IV [Link] I Semester Regular/Supplementary Examinations, Nov/Dec – 2025
SECURE CODING TECHNIQUES
(Open Elective-IV: CSE, CSE-AIML, CSE-AI, CSE-DS, CSE-AIDS, AIDS, AIML & CSD)
Time: 3 hours Max. Marks: 70
Answer any FIVE Questions ONE
Question from Each unit All Questions
Carry Equal Marks
*****
UNIT - I
1 a) Explain different network types and compare their characteristics. [7]

Types of Networks: (4marks)


• Local Area Network (LAN):

• Metropolitan Area Network (MAN):

• Wide Area Network (WAN):


Topology:
Network Topology -.
There are two ways of defining network geometry:
1) Physical topology
2) Logical (or) signal topology.
Different Network Topologies: They are...
1) Bus Topology
2) Ring Topology
3) Star Topology
4) Mesh Topology
5) Tree Topology
6) Hybrid Topology
Characteristics of these networks: [3Marks]
LAN
MAN .
WAN

b) List out the major cyber security services? Explain how each service adds value to
organizational security. [7]

Ans. Cyber Security Objectives-services


1. Risk Assessment and Management
2. Network Security
3. Endpoint Security

4. Identity and Access Management (IAM)


5. Data Protection and Privacy
6. Incident Response and Management
7. Security Operations Center (SOC)
8. Compliance and Governance
9. Security Awareness
|''|'|''|''|'''Training 1 of 1
|||'|
10. Cloud Security
11. Application Security
12. Physical Security
.

Data integrity is a crucial aspect of overall cybersecurity as it ensures the accuracy, completeness, and
consistency of data throughout its lifecycle. Here are the key contributions of data integrity to cybersecurity:
1. Prevention of Data Tampering

2. Trustworthiness of Data

3. Ensuring Compliance

4. Detection of Cyberattacks
5. Maintaining System Functionality

(OR)
2. a) Describe cybersecurity? Explain why it is important in modern networked
environments. [7]

Ans. Cybersecurity (also called information security or InfoSec) is the practice of protecting digital systems,
networks, devices, programs, and data from unauthorized access, attack, theft, damage, or disruption. It
encompasses a wide range of technologies, processes, policies, and practices designed to ensure three
fundamental goals, often referred to as the CIA triad:

1. Confidentiality – Ensuring that sensitive information is accessible only to authorized people (e.g.,
encryption, access controls).
2. Integrity – Protecting data from being altered or destroyed in an unauthorized way (e.g., hashing,
digital signatures, version control).
3. Availability – Making sure that systems and data are accessible to authorized users when needed (e.g.,
backups, DDoS protection, redundancy).

Cybersecurity is critically important in modern networked environments because today’s networks are
fundamentally different from those of even 10–15 years ago. The combination of scale, complexity, value, and
real-world consequences has turned weak security into an existential risk for organizations, governments, and
individuals.

Here are the key reasons why cybersecurity is non-negotiable today:

1. Everything is connected (massive attack surface) Billions of devices — laptops, phones, IoT sensors,
cars, medical equipment, industrial controllers, and cloud services — are permanently online. A single
vulnerable device (e.g., an internet-exposed camera or a misconfigured server) can become the entry
point for attacking an entire organization or critical infrastructure.
2. Data has become the most valuable asset Personal data, financial records, health information, trade
secrets, and national security intelligence are all stored and transmitted digitally. A breach can cause
identity theft, corporate espionage, blackmail, or massive regulatory fines (hundreds of millions under
GDPR, CCPA, etc.).
3. Cybercrime is a multi-trillion-dollar industry. Ransomware gangs, initial-access brokers, and state-
sponsored groups operate like professional businesses. Attacks are automated, highly scalable, and
extremely profitable.
4. The traditional perimeter no longer exists. Remote/hybrid work, cloud adoption, and BYOD mean
employees and contractors can access corporate resources from anywhere. Firewalls and castle-and-
|''|'|''|''|''' 1 of 1
|||'|
moat defenses are obsolete; attackers are already “inside” via stolen credentials or supply-chain
compromises.
5. Supply-chain attacks can compromise millions at once. Recent examples:
o SolarWinds (2020) – affected 18,000+ organisations
o Log4j (2021) – billions of applications vulnerable overnight
o MOVEit (2023), Okta (2023), CrowdStrike update incident (2024). One weak link in a vendor or
open-source library can create global damage.
o
6. Attacks now have physical and societal consequences
o Ransomware shutting down hospitals (patients die or are diverted)
o Attacks on power grids, water treatment plants, or pipelines (Colonial Pipeline 2021 caused fuel
shortages across the U.S. East Coast)
o Election infrastructure, GPS spoofing, or transportation systems being targeted
7. Regulatory and legal pressure is intense. Governments now mandate rapid breach disclosure (24–72
hours in many jurisdictions) and impose massive fines. Directors and officers can face personal liability
(e.g., new SEC cyber rules in the U.S.).
8. Speed and automation favour attackers. Attackers can scan the entire internet in minutes, exploit
zero-days within hours of disclosure, and use AI to craft perfect phishing emails or automate attacks.
Defenders must be right 100% of the time; attackers only need to be right once.
9. Zero-trust is the new reality. Modern environments assume breach: identity, device health, and
behaviour are verified continuously, not just at the network edge. Weak cybersecurity directly
undermines zero-trust architectures.
10. Reputation and business continuity are at stake A single major breach can destroy customer trust,
tank stock prices (often 5–20% drops), and put companies out of business (e.g., Target, Equifax, and
many smaller firms that never recovered).

b) Why do companies need cybersecurity? Explain what can happen if an organization fails
to protect its systems. [7]

Ans. Companies need cybersecurity to protect sensitive data, maintain business operations, preserve
customer trust and brand reputation, and comply with legal and regulatory requirements in an increasingly
digital world. Failing to protect systems can lead to devastating financial, legal, and operational
consequences below are some of the Common types of Cyber-Attacks if an organization fails to protect its
system:
1. Targeting of Vulnerabilities:
o Cyber-attacks often exploit vulnerabilities in software, hardware, or networks.
These vulnerabilities may include unpatched software, misconfigured systems, or
insecure applications.
o Example: A hacker uses a known software vulnerability that hasn't been patched to inject
malicious code.
2. Use of Malicious Code or Software:
o Many cyber-attacks involve the use of malware (e.g., viruses, ransomware,
spyware) designed to harm or gain control of systems.
o Example: An attacker installs a Trojan horse to create a backdoor into the system.
3. Social Engineering:
o Attackers often use social engineering techniques to manipulate users into revealing sensitive
information or granting access. This is a non-technical method that relies on human error.
Example: Phishing attacks where users are tricked into providing login credentials
o
or downloading malware.
|''|'|''|''|''' 1 of 1
[Link] Access or Privilege Escalation:
|||'|
o Attackers may seek to gain unauthorized access to systems by cracking passwords,
exploiting weak authentication methods, or escalating privileges within a compromised
system.
o Example: An attacker who gains user-level access then exploits vulnerabilities to
elevate privileges to an administrator.
[Link] Theft or Exfiltration:
o Many cyber-attacks focus on stealing sensitive information such as personal data, financial
records, or intellectual property.
o Example: A data breach where attackers steal customer data from a corporate database.
[Link] of Services:
o Some attacks are aimed at disrupting services or taking down networks. These types of
attacks can cause downtime and financial losses.
o Example: Distributed Denial of Service (DDoS) attacks overwhelm servers with traffic to
make services unavailable.
[Link]:
o In advanced attacks, especially by nation-states or well-funded organizations, attackers
maintain long-term access to compromised systems. These are known as Advanced
Persistent Threats (APTs).
o Example: Hackers infiltrate a network and remain undetected for months, exfiltrating data
gradually.
[Link] of Command and Control (C2) Channels:
o Many cyber-attacks involve attackers using C2 servers to remotely control compromised
systems or networks.
o Example: Malware that phones home to a C2 server to receive instructions and send stolen
data.

How Attackers Typically Gain Unauthorized Access to Systems:


1. Phishing and Social Engineering:

o Attackers trick users into divulging sensitive information (like passwords) or performing
actions that compromise security, such as downloading malware or clicking on malicious
links.
o Example: A phishing email masquerading as a legitimate organization prompts the user to
log into a fake website and provide their credentials.
2. Exploiting Software Vulnerabilities:

o Attackers exploit security flaws in software, operating systems, or applications that


haven't been patched or updated. These vulnerabilities allow attackers to inject malicious
code or gain unauthorized access.
o Example: Using a zero-day exploit in a web browser to take control of a system.
3. Weak or Stolen Credentials:

o Attackers often take advantage of weak passwords or reused credentials. They may use
brute-force attacks (trying many password combinations) or obtain passwords from
previous data breaches.
|''|'|''|''|''' 1 of 1
|||'|
o Example: A weak or reused password is guessed or obtained through credential stuffing,
allowing the attacker access.

|''|'|''|''|''' 1 of 1
|||'|
4. Insecure Networks or Devices:

o Attackers can intercept data from poorly secured networks (e.g., unencrypted public Wi-Fi) or
hack into insecure Internet of Things (IoT) devices.
o Example: A hacker gains access to a home network through an insecure IoT device, then
pivots to other devices connected to the same network.
5. Malware Infection:

o Attackers deliver malware via email attachments, infected websites, or downloads. Once
installed, malware can provide unauthorized access, steal information, or compromise
systems.
o Example: Ransomware encrypts the victim’s files, locking them out until a ransom is paid.
6. Man-in-the-Middle (MITM) Attacks:

o Attackers intercept communications between two parties to gain unauthorized access or


steal data. This often occurs over insecure or unencrypted networks.
o Example: Intercepting login credentials during an online banking session over an
unencrypted Wi-Fi connection.
7. Insider Threats:

o Malicious insiders or employees with authorized access can misuse their credentials to steal
data, sabotage systems, or provide entry points to external attackers.
o Example: A disgruntled employee exfiltrates sensitive data to sell on the dark web.
8. Drive-by Downloads:

o Attackers compromise legitimate websites or create fake sites that automatically download
malicious software when a user visits the page.
o Example: A user visits an infected website, which silently downloads malware onto their
computer.
9. Privilege Escalation:

o Attackers exploit vulnerabilities in a system to elevate their access from a lower-level user to
an administrator with broader permissions.
o Example: An attacker with basic user access finds a vulnerability in the system’s permission
management, allowing them to gain administrative rights.
10. SQL Injection:

 Attackers exploit vulnerabilities in web applications to insert malicious SQL queries, allowing them to
bypass authentication or retrieve, modify, or delete data from a database.
 Example: An unprotected login form allows an attacker to enter a crafted SQL statement that
retrieves all user credentials from a database.

|''|'|''|''|''' 1 of 1
|||'|
UNIT– II
3.a) Describe A7 Cross-Site Scripting (XSS)? Explain the different types and preventive
approaches. [7]

A7 Cross Site Scripting (XSS):

 XSS is an attack where malicious scripts are injected into web pages.
 XSS is a client-side code injection attack where an attacker injects malicious scripts into web
pages or applications.
 The actual attack occurs when the victim visits the web page or web application that executes the
malicious code in their browser, allowing the attacker to steal data or perform actions on the
victim’s behalf.
 They are most common in JavaScript, primarily because JavaScript is fundamental to most
browsing experiences.
 Proper input validation, output encoding, and secure coding practices can help prevent XSS attacks.

Types of XSS attacks:


According to OWASP, there are three types of XSS attacks: stored, reflected, and DOM based
1. Stored XSS attack
 The attacker injects a malicious script into the web application's database, typically through input
fields like comment sections or forums.
 The script is stored on the server and delivered to users whenever they load the affected page.
 Impact on Web Applications:
 Data Theft: Sensitive information like cookies or session tokens can be stolen from
users who load the affected page.
 Widespread Impact: Because the script is stored and served to multiple users, many can be
affected.
 Account Hijacking: The attacker can perform actions on behalf of users, potentially
leading to account compromise.
2. Reflected XSS attack
 In a reflected XSS attack, the application or API injects malicious code as part of the HTML input
or URL.
 The server returns the unescaped and unvalidated response with malicious content to the browser.
 The attacker can then run arbitrary HTML or JavaScript on the user’s web browser.
 Usually targets individual users by getting them to click on a malicious link.
 Impact on Web Applications:
 Targeted Attacks: Often used in phishing attacks where specific users are tricked
into clicking a malicious link.
 Data Theft: Attackers can steal sensitive information from the user's session.
 Temporary Impact: Unlike stored XSS, the impact is usually limited to the victim who
clicks the malicious link.
3. DOM-based attack
 This type of XSS occurs entirely on the client side.
 The malicious script modifies the Document Object Model (DOM) of the page directly in the
user's browser, without involving the server.
 This typically happens when the web page's JavaScript code processes data from the URL or other
client-side sources without proper validation.
 In a DOM attack, the source of the data and the response
1 of 1 of the attack are also in the DOM, and the
|''|'|''|''|'''
data flow never leaves the browser.
|||'|
 Impact on Web Applications:
 Client-Side Vulnerability: The attack manipulates how the web application is displayed
or functions in the user's browser.
 Difficult to Detect: Since it doesn’t involve server interaction, it can be harder to detect and
mitigate.
 Potential Data Theft and Manipulation: Just like other XSS attacks, DOM-Based XSS
can lead to data theft, unauthorized actions, and altered user experiences.
Input Sanitization and Output Encoding:
Input sanitization and output encoding are two critical security measures that can significantly reduce
the risk of Cross-Site Scripting (XSS) vulnerabilities
Input Sanitization
 What it is: Input sanitization involves cleaning or filtering user inputs to ensure that they don't
contain potentially harmful data. This process can involve removing or escaping special characters
that might be used to inject malicious scripts.
 How it helps:
o Preventing code injection: By removing or modifying malicious characters like <, >, &,
and ', sanitization prevents attackers from injecting malicious scripts into the application.

|''|'|''|''|''' 1 of 1
|||'|
o Enforcing expected input formats: Sanitization ensures that user input adheres to
the expected format, preventing unexpected or unintended behaviour.

 Techniques:
o Whitelisting: Allow only a specific set of characters or formats.

o Blacklisting: Disallow a specific set of characters or formats.

o Regular expressions: Use regular expressions to match and filter input patterns.

o Encoding: Convert potentially harmful characters into safe, encoded representations.

Output Encoding
 What it is: Output encoding is the process of converting user-supplied data into a safe format
before displaying it on a web page. This ensures that any potentially harmful code is treated as
text rather than executable code.
 How it helps:
o Preventing code execution: By encoding harmful characters, output encoding ensures that
they are displayed as plain text rather than being executed as code.
o Protecting against reflected and stored XSS: Both types of XSS can be mitigated
by properly encoding output data.
 Techniques:
o HTML encoding: Convert HTML special characters (e.g., <, >, &) into their
corresponding HTML entities.
o URL encoding: Convert URL-unsafe characters (e.g., spaces, special characters) into
their URL-encoded equivalents.
o JavaScript encoding: Convert JavaScript special characters (e.g., quotes, slashes) into
their JavaScript-encoded equivalents.
o

b) Explain insufficient logging & monitoring. Why does OWASP consider it a major
vulnerability? [7]
Ans. Insufficient logging and monitoring refers to the failure to adequately capture, retain, protect, and actively
review security-relevant events in an application or system—such as authentication attempts, privilege
escalations, password changes, failed logins, and administrative actions. This includes not only the absence of
logs but also logs that are incomplete, stored locally on compromised hosts, easily tampered with or deleted by
attackers, sent to unmonitored locations, or drowned in noise without proper alerting and response processes.
Consequences of inadequate logging and monitoring
 Data breaches:
With no way to track or detect suspicious activity, attackers can gain deep access to sensitive systems and data
undetected for extended periods.
 Operational disruption:
Malicious actors can disable critical systems, delete data, or plant malware, leading to significant operational
downtime and recovery costs.
 Difficulty in investigations:
Without proper logs, security teams cannot properly investigate security incidents to determine the cause,
identify affected data, and implement effective remedial measures.
 Increased insider threat risk:
Employees can unintentionally or maliciously misuse their elevated privileges, and the lack of monitoring
makes these actions difficult to detect.
 Regulatory|''|'|''|''|'''
non-compliance: 1 of 1
|||'|
Many regulations require strict controls over privileged accounts. Failing to log and monitor them can lead to
hefty fines and damage the company's reputation.
 Financial loss:
This can result from direct costs like fines and operational recovery, as well as indirect costs like lost customer
trust and damage to brand reputation.

Why OWASP considers it a major vulnerability

 Enables undetected attacks: It allows attackers to perform malicious actions, such as gaining
unauthorized access or exfiltrating data, without being noticed for potentially hundreds of days.
 Increases damage: The longer an attack goes undetected, the more time an attacker has to move
laterally, compromise more systems, and cause greater damage.
 Hinders incident response: Without logs, security teams cannot effectively determine the scope of a
breach, leading to a slow or ineffective response.
 Prevents forensics and recovery: It makes it extremely difficult, if not impossible, to reconstruct the
sequence of events during an attack to understand what happened and how to fix the vulnerabilities.
 Risks regulatory and compliance failures: Many regulations, like PCI DSS, require detailed audit
trails and monitoring, and failure to comply can result in fines and other penalties.

(OR)

4 a) Explain A3 Sensitive Data Exposure. How can secure cryptographic practices reduce
risks? [7]

Ans. Sensitive Data Exposure:


 Inadequate protection of sensitive information can lead to data breaches.
 Examples include using weak encryption, storing passwords in plain text, and
 exposing sensitive data through insecure channels.
 Employing strong encryption, using secure communication protocols, and implementing
proper access controls are crucial.
Attackers exploit sensitive data exposure vulnerabilities through several common methods, aiming
to steal or misuse sensitive information like personal data, financial details, and credentials. Here
are the key methods:
1. Unencrypted Data Transmission: Attackers intercept data transmitted over insecure channels
(e.g., HTTP instead of HTTPS) using methods like packet sniffing or man-in-the-middle (MITM)
attacks.
2. Insecure Data Storage: Sensitive data stored without encryption (e.g., in databases or files) can
be easily accessed by attackers if they gain system access.
3. Exposing Sensitive Data in URLs: Including sensitive information (e.g., tokens or
credentials) in URLs exposes it to interception via logs, browser history, or referrer headers.
4. Improper Error Handling: Detailed error messages may reveal sensitive data, like
database structure or system configurations, that attackers can exploit.
5. Failure to Use Strong Encryption Algorithms: Using weak or outdated encryption
algorithms allows attackers to decrypt sensitive data.
|''|'|''|''|''' 1 of 1
6. Inadequate Access Controls: Attackers can access sensitive files or databases if proper
|||'|
permissions and access control measures are not enforced.
7. Lack of Secure Token Management: Insecure handling of authentication tokens (e.g., storing
tokens in browser storage without proper protections) can lead to session hijacking or unauthorized
access.
How secure cryptographic practices reduce risks

 Protects confidentiality: By turning plain text into ciphertext, encryption makes data unreadable to
unauthorized individuals, preventing data theft and exposure.
 Prevents breaches: Encryption is a critical defense against data breaches. Even if an attacker gains
access to a system, the data remains useless without the decryption key.
 Ensures integrity: Cryptography helps ensure that data has not been tampered with during transit or
storage.
 Facilitates compliance: Implementing strong encryption practices helps organ

b) What are unvalidated redirects and forwards (A10)? Explain how they can
be exploited. [7]

Ans. Unvalidated redirects occur when user input is used to determine the destination URL for a redirect
without proper validation. This can lead to phishing attacks or redirection to malicious sites. Typically, the
application uses a URL parameter such as ?url=, ?next=, ?redirect=, ?target=, or ?return_to= and sends the user
directly to that location without sufficient validation or whitelisting.

Attackers exploit this vulnerability primarily through social engineering and malicious link manipulation.

1. Phishing amplification (the most common and dangerous use) An attacker sends a link like:
[Link]
o The URL starts with the legitimate domain ([Link]), so it passes email filters, link
previews, and many reputation checks.
o Victims click the link, briefly land on the real site (often seeing a valid SSL certificate and green
padlock), and are instantly redirected to the attacker’s fake login page.
o This dramatically increases phishing success rates and is heavily used by banking trojans,
business email compromise kits (Emotet, Qakbot, etc.), and credential-stealing campaigns.
2. Bypassing allow-lists and security tools Many organizations and browsers block or warn about direct
links to known malicious domains. By routing traffic through a trusted open redirect ([Link],
[Link], [Link], etc.), attackers “launder” the final destination and evade blocklists.
3. OAuth/OpenID Connect Misuse Legitimate OAuth flows often use a redirect_uri parameter. If the
authorization server does not strictly validate it against a pre-registered list, attackers can steal
authorization codes or tokens by redirecting the user to a domain they control.
4. Server-side forwards leading to SSRF or local file inclusion When the vulnerable code uses server-
side forwarding (e.g., [Link]() in Java or [Link] in .NET) instead of a
|''|'|''|''|''' 1 of 1
client-side redirect, attackers can sometimes force the server to connect to internal network resources
|||'|
([Link] [Link] for cloud metadata, or even [Link] turning a
simple redirect bug into Server-Side Request Forgery (SSRF).
5. Reputation hijacking and SEO poisoning Attackers use open redirects on high-authority domains to
host scam, malware, or adult content temporarily, boosting the malicious page’s search ranking or
trustworthiness.

Because exploitation requires no authentication, is trivial to automate, and turns any trusted website into a
phishing accomplice, unvalidated redirects and forwards remain one of the easiest and most abused
vulnerabilities on the internet—even though they were formally A10 in the 2017 list, they are still actively
tracked by OWASP

UNIT - III
5 a) Explain cryptographic principles and list common cryptographic implementation errors. [7]

Ans. Cryptographic principles are the foundational security goals that information systems strive to achieve:
confidentiality, integrity, availability, authenticity, and non-repudiation. Common implementation errors in
secure coding often stem from misusing cryptographic primitives or failing to follow best practices
Common Cryptographic Implementation Errors
 Hard-coding keys or passwords in the code or config files
 Using weak/broken algorithms (MD5, SHA-1, DES, RC4, Blowfish)
 Using AES-CBC or AES-ECB without authentication
 Reusing the same IV/nonce with AES-GCM or ChaCha20
 Hashing passwords with SHA-256, MD5, or single iteration
 Generating keys/IVs from weak random (like Java Random or time-based seeds)
 Comparing secrets with normal == or [Link]() (timing attack)
 Rolling your own encryption/protocol instead of using libsodium or standard libraries
 Storing private keys or secrets in plaintext files, shared preferences, or databases
 Using old RSA padding (PKCS#1 v1.5) instead of OAEP
 Logging keys or encrypted data during debugging
 Using the same key for too many years without rotation
 Transmitting keys in URL parameters or unencrypted channels.

b) What are safe APIs? Explain how they reduce vulnerability risks. [7]
Ans. Safe APIs are interfaces that enforce secure communication and error handling, helping prevent
misuse, data leaks, and unauthorized access. They provide consistent input validation, authentication, and
exception handling, reducing the chance of vulnerabilities.

|''|'|''|''|''' 1 of 1
|||'|
Role of Safe APIs in Security
1. Input Validation at the API Level:
 Safe APIs automatically perform input validation, ensuring that invalid or malicious inputs don’t
reach the application logic.
 Example: An API may reject input if it doesn't meet the expected format or data type.
2. Authentication and Authorization:
 APIs should enforce authentication and access control mechanisms to prevent unauthorized
access. This avoids the "confused deputy" problem, where unauthorized entities use
legitimate APIs improperly.
3. Use of Parameterized Queries:
 Safe APIs for database access implement parameterized queries to prevent SQL injection attacks.
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement stmt = [Link](query);
[Link](1, username);
ResultSet rs = [Link]();

4. Proper Rate Limiting


 Safe APIs implement throttling and rate limiting to avoid Denial-of-Service (DoS) attacks and
abuse by limiting the number of requests a client can make.
5. Secure Data Transmission
 Safe APIs typically enforce the use of secure transport protocols (like HTTPS) to encrypt data in
transit. This prevents eavesdropping and man-in-the-middle attacks.
 Example: APIs that require HTTPS automatically secure data exchanged between the client and
server.
6. Access Control
 Granular Permissions: Safe APIs can enforce fine-grained access control, allowing developers to
define which resources users can access based on their roles.
 Example: An API for a content management system might restrict editing permissions to users
with specific roles (e.g., editor, admin).

Examples of Best Practices for Exception Management & Safe API Usage
1. Avoid Revealing Sensitive Information in Error Messages
 What to Avoid:
o Displaying stack traces, database queries, or detailed error messages to end users.
 Good Practice:
o Display generic error messages (e.g., "Something went wrong. Please try again.").
o Log detailed errors only in server-side logs accessible to admins.

|''|'|''|''|''' 1 of 1
|||'|
2. Use Whitelisting for Input Validation
 What to Avoid:
o Relying on blacklisting, as attackers may find ways to bypass it.
 Good Practice:
o Use safe APIs that validate inputs based on whitelisted patterns (e.g., only allowing digits
in phone numbers).
3. Prefer Parameterized Queries to Avoid SQL Injection
 What to Avoid:
o Concatenating user inputs directly in SQL queries:
String query = "SELECT * FROM users WHERE username = '" + userInput +
"'";

 Good Practice:
o Use prepared statements or ORMs:

String query = "SELECT * FROM users WHERE username = ?";


PreparedStatement stmt = [Link](query);
[Link](1, userInput);

4. Handle Exceptions Gracefully


 What to Avoid:
o Allowing unhandled exceptions to cause application crashes.

 Good Practice:
o Wrap sensitive operations in try-catch blocks and ensure graceful failure.
try:
data = open("[Link]").read()
except FileNotFoundError as e:
[Link]("File not found: %s", e)

5. Log Exceptions Securely


 What to Avoid:
o Logging sensitive information like passwords or private keys.
 Good Practice:
o Use secure logging frameworks and sanitize logs to avoid storing sensitive data.
6. Limit Error Handling in Public APIs
1 of 1
 What |''|'|''|''|'''
to Avoid:
|||'|
o Exposing internal error codes or exceptions to API consumers.
 Good Practice:
o Use a consistent error format (e.g., HTTP status codes) and document them properly:
{ "error": "Invalid request", "code": 400 }
7. Use Safe Memory Operations in Low-Level Languages
 What to Avoid:
o Direct memory manipulation (e.g., using unsafe strcpy in C/C++).
 Good Practice:
o Use safer alternatives like strncpy or buffer-overflow-safe APIs.

(OR)
6.a) Discuss how input/output sanitization helps prevent security vulnerabilities. [7]

b) Illustrate the different type safety measures in secure coding. [7]

UNIT - IV
7.a) Explain common software risks in C/C++ such as buffer overflow and dangling pointers. [7]

In C/C++ development, several key software risks arise due to the language's low-level nature and lack of
built-in safety mechanisms. The most common risks include:
1. Memory Management Issues
 Manual memory control: In C/C++, memory management (allocation and deallocation) is
manually handled using functions like malloc()/free() in C and new/delete in C++. Mismanagement
leads to various issues:
o Memory leaks: Failing to deallocate memory properly causes a program to consume more
memory over time, potentially leading to system crashes or degraded performance.
o In C/C++, memory allocation (e.g., using malloc or new) must be manually managed,
including freeing memory when it’s no longer needed. Failing to free memory leads to leaks,
eventually causing programs to run out of memory.
o Dangling pointers: When a pointer still references memory that has been deallocated,
any attempt to use it can cause crashes or unpredictable behavior.
o Double-free errors: This happens when the same block of memory is deallocated more
than once, leading to corruption of the memory management system.
2. Buffer Overflow
A buffer overflow occurs when data exceeds the allocated space in memory, potentially overwriting
adjacent memory. This can lead to program crashes, erratic behavior, or security vulnerabilities like
executing arbitrary code.

|''|'|''|''|''' 1 of 1
|||'|
 Out-of-bounds memory access: C/C++ do not automatically check if memory access is within
valid bounds, so if a program writes more data than a buffer can hold (for example, using strcpy()
on a string without validating its length), it can overwrite adjacent memory.
o Exploitable vulnerabilities: Buffer overflows are a major security risk because
attackers can manipulate program execution by injecting malicious code into memory.
It allows attackers to execute arbitrary code, potentially gaining control over the system.
o Stack smashing: In some cases, buffer overflows can overwrite return addresses on the
stack, causing the program to jump to unintended memory locations.
3. Pointer Arithmetic and Null Pointer Dereferencing
 C/C++ allow pointer arithmetic, which gives great flexibility but also poses significant risk. If done
incorrectly, this can lead to accessing invalid memory.
 Null pointer dereferencing occurs when a program tries to access memory through a null pointer,
leading to segmentation faults or crashes.
4. Uninitialized Variables
 In C/C++, variables are not automatically initialized, leading to the use of garbage data from
previous memory contents. This can result in unpredictable program behavior, security
vulnerabilities, or crashes.
5. Race Conditions (in Multithreaded Programs)
 Without proper synchronization mechanisms, threads might concurrently modify shared data,
leading to inconsistent or incorrect program states. C/C++ do not provide built-in thread safety,
making race conditions more likely if multithreading is used improperly.
How Buffer Overflows and Memory Management Issues Contribute to Risks:
 Buffer overflows exploit the lack of boundary checking in C/C++, potentially allowing attackers to
execute malicious code or corrupt sensitive data. This is especially dangerous in networked
applications, where user input can be crafted to trigger these vulnerabilities.
 Memory management issues such as dangling pointers and memory leaks reduce the
reliability and stability of applications. Unchecked memory misuse can lead to crashes,
degraded performance, or system resource exhaustion, making programs vulnerable to denial-
of-service (DoS) attacks.
In summary, buffer overflows and memory management issues significantly increase the security and
stability risks of C/C++ applications, demanding extra care from developers to mitigate these risks through
techniques like bounds checking, using smart pointers, and adopting modern practices (e.g., using libraries
like ASan or Valgrind for memory safety).

b) Explain denial-of-service risks in Java applications and ways to mitigate them. [7]
 Denial-of-Service (DoS) attacks occur when an attacker overwhelms a system, service, or
application with excessive requests or malicious inputs, causing it to become unavailable to
legitimate users.
 In Java, Unit Testing can help identify potential vulnerabilities that might lead to DoS attacks,
enabling developers to design defenses against such threats.

 By writing|''|'|''|''|'''
targeted unit tests, developers can simulate 1 of 1 loads and validate performance under
heavy
specific conditions.
|||'| These tests ensure the code is resilient against unexpected inputs or conditions that
could degrade system performance.
How Unit Testing Helps Mitigate DoS Risks
6. Input Validation Tests:
o Maliciously large or malformed inputs can lead to DoS if the application doesn’t handle them
properly. Unit tests can ensure the system rejects or limits excessive input sizes and malformed
data, thus preventing DoS.
7. Load Handling Tests:
o Unit tests can simulate multiple rapid requests or high volumes of data input to verify how
the system handles these conditions. The goal is to prevent the application from slowing
down, crashing, or consuming excessive memory.
8. Resource Consumption Tests:
o Ensure that critical resources like memory, CPU, file handles, or network connections are
properly managed and released, preventing a resource exhaustion DoS.
9. Timeouts and Limits:
o Set timeouts for long-running operations and limits on input size to prevent excessive
processing or resource hogging.
Example: Unit Test to Prevent DoS Attack via Large Input
Imagine a Java application has a method processInput(String input) that processes user input. A possible
DoS attack could involve passing an extremely large input string to overwhelm the system.
Unit Test for Input Validation Against Large Inputs
This test ensures that if an attacker tries to submit excessively large inputs, the system rejects them without
consuming excessive memory or CPU resources.

|''|'|''|''|''' 1 of 1
|||'|
// Check that processing such large input throws an exception
Exception exception =
assertThrows([Link], () -> {
processInput(largeInput);
});

// Verify that the exception contains the expected message


assertEquals("Input too large!", [Link]());
}

@Test
public void testNormalInput() {
// Test with a valid input size to ensure the method works as
expected
Explanation of the Unit Test:
1. Prevention Against Large Inputs:
o The processInput() method includes a check to prevent inputs larger than 1000 characters
from being processed. If an input exceeds this limit, the method throws an
IllegalArgumentException.
o The unit test testDoSAttackWithLargeInput() simulates a potential DoS attack by creating
an input string of 1,000,000 characters (far larger than the accepted 1000- character limit).
o The test asserts that an exception is thrown for this large input, preventing excessive
resource usage.
2. Normal Input Test:
o The testNormalInput() method ensures that valid inputs (under 1000 characters) are
processed successfully, verifying that the size limitation doesn’t affect normal functionality.
How This Unit Test Helps Prevent DoS:
 Early rejection of excessive input: The test confirms that overly large inputs are identified and
rejected immediately, preventing the system from consuming excessive memory or CPU time.
 Safe limits on input sizes: By enforcing a reasonable limit on input size, the system avoids
running into memory exhaustion or becoming unresponsive due to large inputs.
 Graceful error handling: Instead of crashing or becoming stuck in an infinite loop, the system
throws a controlled exception and continues operating normally, maintaining availability.
Further Enhancements in DoS Testing:
1. Simulating Concurrent Requests:
o To simulate a distributed DoS (DDoS) attack, unit tests can use multithreading to send
multiple requests simultaneously and check how the system handles them. Java’s
ExecutorService or parallel streams can be used to simulate heavy load in the tests.
2. Testing for Infinite Loops:
o If there are loops in the code that could be influenced by user input (e.g., parsing loops), unit
tests can be written to ensure that these loops terminate even with edge- case inputs.
3. Testing for Memory Leaks:
|''|'|''|''|''' 1 of 1
o Use tools like Java’s VisualVM or third-party memory profiling tools to run memory leak
|||'|
checks during the execution of unit tests, ensuring that inputs don’t lead to resource
exhaustion.
4. Timeouts:
o For long-running operations, unit tests can be designed to check that the system applies
reasonable timeouts. This prevents attackers from slowing down or stalling the system
with complex or slow inputs.

(OR)
8.a) Discuss the benefits of unit testing in secure software development. [7]

Ans. Here are the key benefits of unit testing in secure software development, presented point-wise:

 Catches vulnerabilities early Detects security flaws (e.g., injection, broken authentication, weak
cryptography) at the individual function or class level, when they are cheapest and easiest to fix.
 Enforces correct implementation of security controls Explicitly tests that input validation, output
encoding, sanitization, CSP headers, rate limiting, and other defenses work as intended in all code paths.
 Prevents security regressions Automated tests run on every code change, instantly alerting developers
if a commit accidentally weakens or bypasses a security mechanism.
 Verifies edge cases and malicious inputs Allows systematic testing of boundary conditions,
malformed inputs, extreme values, and attack patterns (e.g., SQLi payloads, XSS scripts, buffer
overflow attempts) that manual reviews often miss.
 Ensures cryptographic code is used correctly Tests for proper algorithm selection, key management,
secure random generation, constant-time comparisons, and avoidance of deprecated or broken functions.
 Validates authorization and access-control logic Confirms that every function and method correctly
enforces role-based, attribute-based, or resource-based permissions under various user contexts.
 Acts as executable security requirements Turns vague security policies (“all inputs must be
validated”) into concrete, passing tests that must not be removed or weakened.
 Improves code modularity and design Code that is easy to unit test tends to be loosely coupled and
highly cohesive—qualities that also make security auditing and maintenance simpler.
 Supports safe refactoring of security-critical code Provides confidence that changes to authentication,
crypto, or access-control modules do not introduce vulnerabilities.
 Enables property-based and fuzz testing at the unit level Finds entire classes of bugs (e.g., integer
overflows, format string issues, deserialization flaws) by generating thousands of malicious or
unexpected inputs.
 Provides evidence for compliance and audits High coverage of security-critical units serves as
objective proof to regulators, certifiers (e.g., Common Criteria, SOC 2, ISO 27001), and customers that
defenses are systematically verified.
 Raises the overall cost of introducing vulnerabilities Developers think twice before writing insecure
code when they know a failing unit test will immediately block their pull request.

b) Discuss the role of the Java sandbox model and class loaders in securing code. [7]

The Java sandbox model and class loaders are fundamental to Java's security architecture, working in concert to
secure code execution, particularly when dealing with untrusted sources.
Java Sandbox Model:
The Java sandbox model creates a restricted environment for running untrusted code, such as applets
downloaded from the internet. This isolation prevents malicious code from accessing or manipulating sensitive
system resources. Key aspects include:

 Resource Restriction: 1 of 1
|''|'|''|''|'''
|||'|
The sandbox limits access to critical system resources like the file system, network connections, and
system memory. For example, an applet cannot arbitrarily read or write local files without explicit
permission.

 Security Manager:

The Security Manager is a core component of the sandbox, enforcing security policies and checking
permissions before allowing sensitive operations. It acts as a gatekeeper, mediating interactions between
untrusted code and the underlying system.

 Policy-Based Access Control:

Java applications can define custom security policies, specifying what permissions different code
sources have. This allows for fine-grained control over resource access.

Class Loaders:
Class loaders play a crucial role in securing code by controlling how classes are loaded into the Java Virtual
Machine (JVM) and managing their namespaces. Their contributions to security include:

 Namespace Separation:

Class loaders create distinct namespaces, ensuring that classes loaded from different sources (e.g., local
files vs. network) are isolated from each other. This prevents malicious classes from impersonating or
interfering with trusted system classes.

 Preventing Class Spoofing:

The class loader hierarchy, particularly the delegation model, ensures that system classes are loaded by
the trusted bootstrap class loader, preventing untrusted code from loading malicious versions of core
Java classes (e.g., [Link]).

 Guarding Trusted Libraries:

Class loaders act as a "shield" for trusted class libraries like the Java API, preventing untrusted code
from directly manipulating or overriding their functionality.

 Dynamic Code Loading Control:

Class loaders enable the dynamic loading of code, allowing applications to load and execute code from
various sources while maintaining security by ensuring proper isolation and permission checks.

UNIT - V
9.a) Describe secure function design principles in Python with examples. [7]

[Link] and Sanitize All Inputs (Never Trust Input)

Principle: Treat every input — arguments, environment variables, file contents, database results — as
potentially malicious.

def transfer_money(from_account: str, to_account: str, amount: float):


if not (from_account.isalnum() and len(from_account) == 20):
raise ValueError("Invalid
|''|'|''|''|''' from_account") 1 of 1
if not (to_account.isalnum()
|||'| and len(to_account) == 20):
raise ValueError("Invalid to_account")
if not (0 < amount <= 1_000_000):
raise ValueError("Amount out of range")

# Safe: inputs are now guaranteed to be in expected format


execute_transfer_safely(from_account, to_account, amount)

2. Use Parameterized Queries – Never String Concatenation or f-strings for SQL

Bad (SQL Injection):

def get_user_bad(user_id):

query = f"SELECT * FROM users WHERE id = {user_id}" # DANGER

[Link](query)

Good (Parameterized):

def get_user_safe(user_id: int):

if not isinstance(user_id, int) or user_id <= 0:

raise ValueError("Invalid user_id")

[Link]("SELECT * FROM users WHERE id = ?", (user_id,))

3. Principle of Least Privilege

Give functions only the permissions they need.

import os

# Bad: runs everything as root

def write_log(message):

with open("/var/log/[Link]", "a") as f:

[Link](message + "\n")

# Good: drop privileges or use a restricted user/context

def write_log_safe(message: str):

# Validate/sanitize message first

message = [Link]('\x00', '')[:1000]

[Link](1000) # switch to non-privileged user

with open("/var/log/[Link]", "a") as f:

[Link](f"{[Link]()} {message}\n")
|''|'|''|''|''' 1 of 1
4. Avoid Eval(),|||'|
Exec(), and Dynamic Code Execution
Extremely dangerous
def bad_dynamic_code(user_input):
eval(user_input) # Can execute arbitrary code
exec(f"[Link]('{user_input}')") # Remote code execution
Safe alternatives:
import ast
def safe_calculator(expression: str) -> float:
# Only allow literal expressions (numbers, +, -, *, /, (), **)
tree = [Link](expression, mode='eval')
if not all(isinstance(node, ([Link], [Link], [Link],
[Link], [Link], [Link])) for node in [Link](tree)):
raise ValueError("Invalid expression")
# Use safe_eval or restrict further
return eval(compile(tree, filename="<ast>", mode="eval"), {"__builtins__": {}})

5. Avoid Hard-Coded Secrets


Bad:
def connect_db():
return connect("host=[Link] user=admin password=SuperSecret123!")

Good:

import os
from pathlib import Path
def connect_db():
password = [Link]("DB_PASSWORD") or (Path("/run/secrets/db_password").read_text().strip())
if not password:
raise RuntimeError("Database password not available")
return connect(f"host=[Link] user=admin password={password}")

6. Separation of Concerns:
Functions should have a single, well-defined responsibility. This improves maintainability and reduces the
likelihood of introducing security flaws when modifying unrelated parts of the code.

# Instead of one large function handling both data retrieval and processing:
# Bad example:
# def get_and_process_data(user_id):
# data = fetch_from_database(user_id)
# processed_data = transform_data(data)
# return processed_data

# Good example: Separate concerns


def fetch_user_data(user_id: int):
# Securely retrieve data from a database
return {"name": "John Doe", "email": "john@[Link]"}

def sanitize_and_process_data(raw_data: dict):


# Sanitize and process the fetched data
processed = {k: str(v).strip() for k, v in raw_data.items()}
return processed

8. Keep Functions Small, Focused, and Easy to Review


1 of 1
|''|'|''|''|'''
|||'|
# Good: single responsibility
def parse_user_id(user_input: str) -> int: ...
def validate_user_id(uid: int) -> bool: ...
def load_user(uid: int) -> User: ...

# All composed safely


def get_user_profile(user_input: str):
uid = parse_user_id(user_input)
if not validate_user_id(uid):
raise PermissionError()
return load_user(uid)

b) Describe best practices for writing secure web-request code in Python, including validation
of URLs, HTTPS enforcement, and timeout settings. [7]

Writing secure web-request code in Python involves several best practices to mitigate common vulnerabilities.
1. URL Validation:

 Sanitize and Validate Inputs:

Never trust user-provided URLs directly. Use a library like [Link] to parse and validate the URL
structure. Check for unexpected schemes, hosts, or paths that could lead to Server-Side Request Forgery
(SSRF) or other attacks.

 Whitelist Allowed Domains/Protocols:

If your application only needs to connect to specific domains or use certain protocols (e.g., HTTPS),
explicitly whitelist them and reject all others.

 Prevent Directory Traversal:

Ensure that any path components are properly sanitized to prevent attackers from accessing
unauthorized files or directories.

2. HTTPS Enforcement:

 Always Use HTTPS:

Never make requests over plain HTTP, especially when handling sensitive data. Enforce HTTPS for all
external requests to protect data in transit from eavesdropping and tampering.

 Verify SSL Certificates:

When making HTTPS requests, ensure that the SSL certificate of the remote server is properly
validated. Python's requests library does this by default, but be aware of the verify=False option, which
should only be used in very specific, controlled environments (e.g., internal testing with self-signed
certificates).

 Pin Certificates (Advanced):

For highly sensitive applications, consider certificate pinning to ensure that only specific, pre-approved
certificates are accepted. This adds an extra layer of security against compromised Certificate
Authorities.
|''|'|''|''|''' 1 of 1
3. Timeout Settings:
|||'|
 Implement Connection and Read Timeouts:

Always set explicit timeout values for both connecting to the remote server and receiving a response.
This prevents your application from hanging indefinitely due to slow or unresponsive servers, which can
lead to resource exhaustion and denial-of-service vulnerabilities.

 Choose Appropriate Timeout Values:


The optimal timeout values depend on the expected response time of the external service. Set them high
enough to allow for normal operation but low enough to prevent excessive delays.

(OR)
10.a) Write on interactive python script that asks the uses for their name and age. [7]

# Get the user's name


name = input("Please enter your name: ")

# Get the user's age and convert it to an integer


# Using a try-except block to handle potential ValueError if the user enters non-numeric input
while True:
try:
age_str = input("Please enter your age: ")
age = int(age_str)
break # Exit the loop if a valid integer is entered
except ValueError:
print("Invalid input. Please enter a valid number for your age.")

# Print a personalized greeting


print(f"Hello, {name}! You are {age} years old.")

b) Explain the importance of writing secure conditionals in Python. How can logical
errors in conditions lead to insecure code execution? [7]
Writing secure conditionals in Python is crucial for preventing security vulnerabilities and ensuring the integrity
and confidentiality of data. Conditionals, such as if, elif, and else statements, control program flow based on
specific conditions. If these conditions are not carefully crafted and evaluated securely, they can introduce
logical errors that attackers can exploit.
Importance of Secure Conditionals:

 Preventing Unauthorized Access:

Secure conditionals ensure that only authorized users or systems can access sensitive resources or
execute privileged operations. Flawed conditions might grant unintended access.

 Maintaining Data Integrity:

Correctly implemented conditionals validate input and control data modifications, preventing malicious
or erroneous data from corrupting your application's state.

 Protecting Against Injection Attacks:

Conditionals are often used to validate user input. Weak validation can lead to injection vulnerabilities
like SQL injection or command injection, allowing attackers to manipulate queries or execute arbitrary
code.
|''|'|''|''|''' 1 of 1
 Controlling
|||'| Resource Usage:
Secure conditionals can limit resource consumption, preventing denial-of-service (DoS) attacks where
attackers try to exhaust system resources.

How Logical Errors in Conditions Lead to Insecure Code Execution:


Logical errors in conditionals can create exploitable pathways:

 Incorrect Privilege Checks: If a conditional intended to check user roles or permissions is flawed, an
attacker might bypass authorization and gain elevated privileges.

 Bypassing Input Validation: Weak or missing input validation in conditionals can allow malicious
data to be processed, leading to various attacks.

An attacker could inject malicious commands within the length limit.

 Race Conditions:

In concurrent environments, poorly designed conditionals might not handle simultaneous access to
shared resources correctly, leading to race conditions that attackers can exploit to achieve unintended
outcomes.

 Time-of-Check to Time-of-Use (TOCTOU) Vulnerabilities:

If a condition checks a state, and then that state changes before the action dependent on the condition is
executed, a TOCTOU vulnerability can arise. An attacker can manipulate the state between the check
and the use to bypass security measures.

By meticulously designing and testing conditionals, and by adhering to secure coding practices like input
validation, least privilege, and robust error handling, developers can significantly reduce the risk of logical
errors leading to insecure code execution.

|''|'|''|''|''' 1 of 1
|||'|
Code No: R204105U R20 Set No. 2
IV [Link] I Semester Regular/Supplementary Examinations, Nov/Dec – 2025
SECURE CODING TECHNIQUES
(Open Elective-IV: CSE, CSE-AIML, CSE-AI, CSE-DS, CSE-AIDS, AIDS, AIML & CSD)
Time: 3 hours Max. Marks: 70
Answer any FIVE Questions
ONE Question from Each unit
All Questions Carry Equal
Marks
*****
UNIT - I
1 a) Describe various network communication types with suitable illustrations. [7]
Ans. Types of Networks: (4marks)
• Local Area Network (LAN):
• Metropolitan Area Network (MAN):
• Wide Area Network (WAN):
Topology:
Network Topology -.
There are two ways of defining network geometry:
1) Physical topology
2) Logical (or) signal topology.
Different Network Topologies: They are...
a. Bus Topology
b. Ring Topology
c. Star Topology
d. Mesh Topology
e. Tree Topology
f. Hybrid Topology
Characteristics of these networks: [3Marks]
LAN
MAN.
WAN

b) Define attack, threat, vulnerability, exploit and risk. Explain their


interrelationship.
(OR)
2 a) Discuss different categories of cyber-attacks with relevant examples. [7]

b) [7]

Ans. Cyber-attacks share several common characteristics, regardless of their specific type
or method of execution. These attacks aim to compromise systems, steal data, or disrupt
operations. Attackers typically exploit weaknesses in security measures, software, or
human behavior to gain unauthorized access to systems.
Common Characteristics of Most Cyber-Attacks:
Targeting of Vulnerabilities:
o Cyber-attacks often exploit vulnerabilities in software, hardware, or

|''|'|''|''|''' 1 of 1
|||'|
networks. These vulnerabilities may include unpatched software,
misconfigured systems, or insecure applications.
o Example: A hacker uses a known software vulnerability that hasn't been
patched to inject malicious code.
Use of Malicious Code or Software:
o Many cyber-attacks involve the use of malware (e.g., viruses,
ransomware, spyware) designed to harm or gain control of systems.
o Example: An attacker installs a trojan horse to create a backdoor into the
system.
Social Engineering:
o Attackers often use social engineering techniques to manipulate users into
revealing sensitive information or granting access. This is a non-technical
method that relies on human error.
o Example: Phishing attacks where users are tricked into providing
login credentials or downloading malware.
13. Unauthorized Access or Privilege Escalation:
o Attackers may seek to gain unauthorized access to systems by cracking
passwords, exploiting weak authentication methods, or escalating
privileges within a compromised system.
o Example: An attacker who gains user-level access then exploits
vulnerabilities to elevate privileges to an administrator.
14. Data Theft or Exfiltration:

o Many cyber-attacks focus on stealing sensitive information such as


personal data, financial records, or intellectual property.
o Example: A data breach where attackers steal customer data from a corporate
database.
15. Disruption of Services:
o Some attacks are aimed at disrupting services or taking down networks.
These types of attacks can cause downtime and financial losses.
o Example: Distributed Denial of Service (DDoS) attacks overwhelm servers
with traffic to make services unavailable.
16. Persistence:
o In advanced attacks, especially by nation-states or well-funded
organizations, attackers maintain long-term access to compromised
systems. These are known as Advanced Persistent Threats (APTs).
o Example: Hackers infiltrate a network and remain undetected for months,
exfiltrating data gradually.

|''|'|''|''|''' 1 of 1
|||'|
17. Use of Command and Control (C2) Channels:
o Many cyber-attacks involve attackers using C2 servers to remotely
control compromised systems or networks.
o Example: Malware that phones home to a C2 server to receive instructions
and send stolen data.

How Attackers Typically Gain Unauthorized Access to Systems:


11. Phishing and Social Engineering:

o Attackers trick users into divulging sensitive information (like


passwords) or performing actions that compromise security, such as
downloading malware or clicking on malicious links.
o Example: A phishing email masquerading as a legitimate organization
prompts the user to log into a fake website and provide their credentials.
12. Exploiting Software Vulnerabilities:

o Attackers exploit security flaws in software, operating systems, or


applications that haven't been patched or updated. These vulnerabilities
allow attackers to inject malicious code or gain unauthorized access.
o Example: Using a zero-day exploit in a web browser to take control of a system.
13. Weak or Stolen Credentials:

o Attackers often take advantage of weak passwords or reused


credentials. They may use brute-force attacks (trying many password
combinations) or obtain passwords from previous data breaches.
o Example: A weak or reused password is guessed or obtained through
credential stuffing, allowing the attacker access.
14. Insecure Networks or Devices:

o Attackers can intercept data from poorly secured networks (e.g., unencrypted
public Wi-Fi) or hack into insecure Internet of Things (IoT) devices.
o Example: A hacker gains access to a home network through an insecure
IoT device, then pivots to other devices connected to the same network.
15. Malware Infection:

o Attackers deliver malware via email attachments, infected websites, or


downloads. Once installed, malware can provide unauthorized access,
steal information, or compromise systems.
o Example: Ransomware encrypts the victim’s files, locking them out until a
ransom is paid.
16. Man-in-the-Middle (MITM) Attacks:

o Attackers intercept communications between two parties to gain


unauthorized access or steal data. This often occurs over insecure or
unencrypted networks.

|''|'|''|''|''' 1 of 1
|||'|
o Example: Intercepting login credentials during an online banking
session over an unencrypted Wi-Fi connection.
17. Insider Threats:

o Malicious insiders or employees with authorized access can misuse their


credentials to steal data, sabotage systems, or provide entry points to
external attackers.
o Example: A disgruntled employee exfiltrates sensitive data to sell on the dark
web.
18. Drive-by Downloads:

o Attackers compromise legitimate websites or create fake sites that


automatically download malicious software when a user visits the page.
o Example: A user visits an infected website, which silently downloads
malware onto their computer.
19. Privilege Escalation:

o Attackers exploit vulnerabilities in a system to elevate their access from a


lower-level user to an administrator with broader permissions.
o Example: An attacker with basic user access finds a vulnerability in the
system’s permission management, allowing them to gain administrative
rights.
20. SQL Injection:

 Attackers exploit vulnerabilities in web applications to insert malicious SQL queries,


allowing them to bypass authentication or retrieve, modify, or delete data from a
database.
 Example: An unprotected login form allows an attacker to enter a crafted SQL
statement that retrieves all user credentials from a database.

c) How do basic network concepts such as IP addressing, routing, switching and


network segmentation help improve security? [7]

Basic network concepts are fundamental to establishing a robust security posture. While secure
coding focuses on application-level vulnerabilities, network infrastructure provides essential layers of
defense.

Here's how IP addressing, routing, switching, and network segmentation contribute to improving
security:
1. IP Addressing
IP addressing is the basis for identity and access control at the network level:

 Access Control Lists (ACLs): IP addresses are used in firewalls and routers to create ACLs,
which explicitly allow or deny traffic from specific source or destination addresses. This
prevents unauthorized hosts from connecting to sensitive services [1].

|''|'|''|''|''' 1 of 1
|||'|
 Whitelisting/Blacklisting: Security configurations in applications can whitelist specific IP
addresses (e.g., only allowing the internal company VPN range to access an admin portal) or
blacklist known malicious IP addresses, directly impacting the attack surface [1].

2. Routing
Routing determines the paths data packets take. Secure routing ensures traffic goes only where it is
intended to go:

 Secured Data Paths: By controlling routing tables, administrators can ensure that sensitive
data only travels through trusted network segments and security inspection points (like
firewalls or intrusion prevention systems) [1, 2].
 Preventing Eavesdropping/Tampering: Routing configurations can prevent traffic from
being redirected to malicious third parties, which helps maintain data integrity and
confidentiality during transit [1].

3. Switching
Switching operates at the data link layer and connects devices within a local network (LAN):

 Port Security: Modern switches can enforce port security, limiting which specific device
(based on MAC address) can connect to a physical port. This prevents an attacker from
simply plugging their laptop into an unused wall jack and gaining internal network access [1].
 VLAN Hopping Prevention: Proper switch configuration mitigates VLAN hopping attacks,
ensuring that traffic intended for one secure network segment cannot "hop" to another (e.g., a
guest network hopping to an internal server network) [1].

4. Network Segmentation
Network segmentation is a critical architectural security practice that divides a network into smaller,
isolated subnets. This is perhaps the most significant concept for security:

 Containment of Breaches: If one segment is compromised, attackers are restricted from


easily moving laterally to other critical systems (like production databases or financial
systems). This is often referred to as limiting the "blast radius" [2].
 Principle of Least Privilege: Segmentation allows administrators to strictly enforce the
principle of least privilege, ensuring that users and systems only have connectivity to the
specific resources they absolutely need to perform their jobs [2, 1].
 Improved Monitoring: Smaller, isolated segments make it easier for security teams to
monitor traffic for anomalies and identify suspicious activity that deviates from normal
behavior, as the expected traffic patterns are highly restricted

UNIT - II
3 a) Explain secure coding practices and how they help prevent OWASP top 10
vulnerabilities. [7]
Ans: Secure coding practices are developer actions and standards to build software resilient against
attacks, focusing on preventing vulnerabilities like SQL injection or XSS by validating input, enforcing
least privilege, handling errors securely, and integrating security into the whole Software Development
Lifecycle (SDLC), not just patching later, using principles from OWASP & NIST to build security in
from the start.

The OWASP (Open Web Application Security Project) Top 10 list is a standard
awareness document for developers and organizations focused on web
application security. The primary purpose of the OWASP Top 10 list is to
|''|'|''|''|''' 1 of 1
|||'|
identify and rank the most critical security risks to web applications. It serves
as a guide to help organizations understand the most prevalent security
issues and prioritize their efforts to secure their applications.
Purpose of the OWASP Top 10:
8. Awareness and Education: The list raises awareness about the most
significant security risks that web applications face. It educates
developers, architects, and security professionals on common
vulnerabilities, helping them to understand the risks and the necessary
countermeasures.
9. Standardization: By providing a standardized list of vulnerabilities,
OWASP helps organizations focus on key security issues that should be
addressed. It acts as a benchmark for assessing the security posture of
web applications.
[Link] of Security Efforts: The OWASP Top 10 helps
organizations prioritize their security efforts by identifying the most critical
vulnerabilities. Addressing these issues can significantly reduce the risk of
security breaches.
[Link] for Secure Development: The list provides actionable
guidance on how to prevent and mitigate the listed vulnerabilities. This
includes recommendations for secure coding practices, security testing,
and risk management strategies.

|''|'|''|''|''' 1 of 1
|||'|
The inclusion or removal of vulnerabilities in the OWASP Top 10 list is influenced by several
key factors.
These factors ensure that the list remains relevant, accurate, and reflective of the
current web application security landscape. Here’s a detailed look at the factors that
contribute to the inclusion or removal of vulnerabilities:
Factors Contributing to the Inclusion of Vulnerabilities:
1. Prevalence of the Vulnerability: Vulnerabilities that are widely observed across a
large number of web applications are more likely to be included. If a particular
vulnerability is common, it becomes a priority for inclusion in the list.
2. Severity and Impact: Vulnerabilities that can cause significant damage, such as
data breaches, unauthorized access, or financial loss, are prioritized. The potential
impact of exploitation is a key factor in determining inclusion.
3. Emerging Threats and Attack Trends: New attack techniques and vulnerabilities
that have recently gained prominence are considered for inclusion. The list evolves to
capture emerging threats that pose significant risks to web applications.
4. Technological Relevance/ Advances: Vulnerabilities associated with widely
adopted technologies, frameworks, or development practices are likely to be
included. As the web ecosystem evolves, the OWASP Top 10 reflects vulnerabilities
that are relevant to current technology stacks.
5. Community and Industry Feedback: Input from the security community, including
experts and practitioners, helps identify new vulnerabilities that should be included.
Community-driven insights ensure the list addresses real-world concerns.
Factors Contributing to the Removal of Vulnerabilities:
1. Reduction in Prevalence: If a vulnerability becomes less common due to
widespread adoption of secure coding practices or improvements in technology, it
may be removed from the list. A decline in the frequency of a vulnerability’s
occurrence can lead to its exclusion.
2. Technological Advances: Advances in technology, frameworks, and development
practices can lead to certain vulnerabilities being mitigated by default. For example,
modern 1 of 1 against certain types of injection
frameworks might automatically protect
|''|'|''|''|'''
attacks,
|||'|making them less relevant.
3. Changes in Attack Trends: f attackers shift their focus away from a particular type of
vulnerability in favour of new methods, the older vulnerability may be removed from
the list. The OWASP Top 10 reflects the current focus of attackers, so vulnerabilities
that are no longer targeted may be excluded.
4. Overlap with other Categories: Sometimes, vulnerabilities may be consolidated
under broader categories to simplify the list and avoid redundancy. If a vulnerability
is similar to or overlaps with another, it may be removed or merged with a related
category.
5. Increased Awareness and Education: If a vulnerability is widely understood and
effectively mitigated by the majority of developers, it may no longer need to be
highlighted in the OWASP Top
10. The goal of the list is to address vulnerabilities that require more attention.

b) Explain A2: Broken Authentication and Session Management with suitable examples.
[7]
 Ans. Broken authentication and session management vulnerabilities can lead to
unauthorized access and compromise of user accounts.
 Weak or ineffective authentication mechanisms can allow attackers to bypass
authentication controls.
 Insecure session management can result in session hijacking, session fixation, or
session replay attacks.
12. Failure to Implement Secure Password Policies
 Description: Inadequate password policies, such as allowing weak or short
passwords, can make it easier for attackers to guess or brute force passwords.
 Risks:
o Weak password policies can lead to easy exploitation by attackers,
especially if password complexity requirements (e.g., a mix of letters,
numbers, and special characters) are not enforced.
o Reusing passwords across different applications can further increase the
risk of account compromise.
13. Session Hijacking
 Description: Attackers can steal or manipulate session tokens (used to track
logged-in users) to impersonate legitimate users and gain unauthorized access to
their accounts.
 Risks:
o Attackers can take over active user sessions, allowing them to perform
actions as the authenticated user (e.g., transferring money, changing
account settings).
o If session tokens are exposed via insecure transmission (e.g., lack of
HTTPS), they can be intercepted in transit through methods like packet
sniffing.
14. Session Fixation
 Description: In session fixation attacks, an attacker tricks a user into using a session
ID known to the attacker. If the session ID is not changed after login, the attacker can
hijack the session.
 Risks:|''|'|''|''|''' 1 of 1
|||'|
o Once the user logs in, the attacker can take over the session and gain full access
to the user’s account.
o This is particularly dangerous in systems where session IDs are predictable
or improperly regenerated after authentication.

|''|'|''|''|''' 1 of 1
|||'|
15. Session Expiration and Invalidation Issues
 Description: Sessions that are not properly expired after a user logs out or after a
period of inactivity pose a risk, as attackers can use the session token to continue
accessing the application.
 Risks:
o Attackers can reuse valid session tokens for an extended period if they are
not invalidated promptly.
o This is especially dangerous if session tokens are stored insecurely in
cookies or URL parameters.
16. Password Recovery or Reset Vulnerabilities
 Description: Weaknesses in the password recovery or reset processes (e.g., poorly
implemented security questions, weak email-based recovery) can allow attackers to
reset user passwords and gain access to accounts.
 Risks:
o Attackers can exploit poorly designed password reset flows to reset user
passwords and take over accounts.
o Use of easily guessable or insecure security questions can further exacerbate
the problem, allowing attackers to bypass authentication mechanisms.
17. Insufficient Multi-Factor Authentication (MFA)
 Description: If the authentication system does not support or enforce MFA,
attackers who gain access to credentials (via phishing, credential stuffing, or other
methods) can log in without additional verification.
 Risks:
o Lack of MFA increases the likelihood of successful account takeovers.
o Even if attackers obtain weak or compromised credentials, an additional
authentication factor could prevent unauthorized access.
18. Insecure Session Token Storage
 Description: Session tokens stored in insecure locations (e.g., URLs, client-side
storage like localStorage or sessionStorage without proper protections) can be
exposed and stolen by attackers.
 Risks:
o Attackers can steal tokens via cross-site scripting (XSS) attacks,
allowing them to impersonate users.
o Exposed session tokens can lead to session hijacking, allowing unauthorized
access without needing to know the user’s credentials.
Implementing Multi-Factor Authentication (MFA) can significantly mitigate issues
related to broken authentication by adding an additional layer of security beyond
traditional password-based authentication. Here’s how MFA helps prevent various
authentication vulnerabilities:
1. Protects Against Credential Theft: Even if passwords are compromised, MFA
requires an additional authentication factor, blocking unauthorized access.
2. Mitigates Brute Force Attacks: Attackers need more than just a
password, reducing the effectiveness of brute force attempts.
|''|'|''|''|''' 1 of 1
3. Prevents Damage from Password Reuse: MFA prevents access even if passwords
|||'|
from other sites are reused or leaked.
4. Reduces Session Hijacking Impact: Sensitive actions require additional
authentication, limiting the effect of stolen session tokens.
5. Counters Weak Passwords: MFA provides extra protection, even if users set
weak or guessable passwords.
6. Mitigates Phishing Attacks: Even if passwords are stolen via phishing, MFA blocks
access without the second factor.
7. Secures Account Recovery: MFA strengthens password reset processes, preventing
attackers from exploiting weak recovery flows.
8. Protects Privileged Accounts: Enforces additional security for high-value
accounts, reducing the risk of administrative account takeover.

(OR)
4 a) Discuss A5 Broken Access Control and explain horizontal and vertical privilege
escalation. [7]

Ans. Broken Access Control, ranked A05 in OWASP Top 10, occurs when an application fails to properly
restrict users from performing actions or accessing resources they are not authorized to use. Even if
authentication is perfect, weak or missing authorization checks allow attackers to operate outside their intended
privilege boundaries. This vulnerability manifests primarily through two distinct forms of privilege escalation:
horizontal and vertical, each exploiting different flaws in how applications enforce “who can do what.”

Vertical privilege escalation happens when an attacker elevates their privileges from a lower-privilege account
to a higher-privilege one, most commonly from an ordinary user to an administrator. A classic example is an
endpoint like /api/users/123/delete or /admin/dashboard that performs little or no server-side role checking and
simply trusts that only administrators would ever reach it. An attacker, authenticated as a regular user, can
directly invoke the admin function, modify a hidden form field like role=user to role=admin, tamper with a JSON
Web Token claim, or change a user ID to that of an admin in an Insecure Direct Object Reference (IDOR)
scenario, or exploit a mass-assignment vulnerability in which the API blindly accepts an “isAdmin=true”
parameter during profile updates. The result is often full administrative control—deleting users, changing system
configuration, exfiltrating all customer data, or deploying backdoors. Vertical escalation is usually rated critical
or catastrophic because a single successful attempt can lead to complete system compromise.

Horizontal privilege escalation, by contrast, occurs when an attacker remains at the same privilege level but
gains unauthorized access to another user’s resources or data within that same level. For instance, User A (ID
5001) modifies a request parameter from user_id=5001 to user_id=5002 and suddenly views or edits User B’s
profile, medical records, tax documents, private messages, or financial transactions. This is the most common
real-world manifestation of IDOR. In multi-tenant applications, horizontal escalation can cross organizational
boundaries: a customer from Company X alters a tenant_id or account_id and accesses Company Y’s sensitive
data. Other common vectors include predictable document identifiers (“view?file=[Link]” →
guessing [Link]), reusable sharing links without access checks), weak password-reset tokens that
allow enumeration, or collaboration features (shared folders, projects) that fail to validate membership on every
request. While horizontal escalation does not grant admin rights, its impact is still severe: it directly violates
confidentiality and privacy, triggers regulatory penalties (GDPR, HIPAA, PCI-DSS), and often enables large-
scale data breaches affecting thousands or millions of users.

Both types frequently stem from the same root causes: over-reliance on client-side hiding of functionality (e.g.,
disabling an “Admin” button for non-admins in JavaScript), missing or inconsistent server-side authorization
checks, use of predictable sequential identifiers, lack of ownership verification in database queries, and failure to
implement the principle of least privilege across the entire stack. Effective prevention requires enforcing
authorization at every layer—URL/route level, controller, business logic, and even in raw SQL/NoSQL queries
—using indirect references (UUIDs instead of sequential IDs), centralised policy engines
(RBAC/ABAC/ReBAC), and systematic testing for both vertical (trying to reach admin functions) and horizontal
1 of 1
(trying to access|''|'|''|''|'''
sibling accounts) scenarios. When properly implemented, strong access control acts as a safety
|||'|
net that renders many other vulnerabilities (SQL injection, XSS, SSRF, etc.) far less dangerous, because even if
an attacker gains code execution or steals a session, they are still confined to the privileges of the compromised
account. Broken Access Control therefore remains one of the highest-return areas for security investment: fixing
it prevents both total compromise (vertical) and massive privacy violations (horizontal) with relatively
straightforward, repeatable engineering discipline.

b) What is CSRF (A8)? Explain its attack mechanism and protection strategies. [7]
UNIT - III
5 a) Explain secure error-handling principles. Why must errors avoid exposing system
details? [7]
b) Explain memory vulnerabilities such as buffer overflow and their mitigation methods. [7]
(OR)
6 a) Describe the significance of exception handling in secure code. [7]
b) Discuss the importance of secure configuration management in software systems. [7]
UNIT - IV
7 a) Describe defensive coding principles in C/C++ with relevant examples. [7]
b) Discuss how Java ensures information security and data integrity. [7] (OR)
8 a) Explain why low-level design inspections are important in detecting security flaws. [7]
b) Explain secure exception handling practices in C/C++ and Java. [7]
UNIT - V
9 a) Explain the importance of secure conditional and loop structures in Python programs.
[7]
b) Discuss the security concerns associated with using external Python modules.
How can developers verify the trustworthiness of third-party packages? [7]
(OR)
10 a) Discuss secure file operations in Python and risks like directory traversal. [7]
b) Discuss Python variables and dynamic typing. How can improper handling of variable
types lead to security vulnerabilities? [7]

|''|'|''|''|''' 1 of 1
|||'|

You might also like