0% found this document useful (0 votes)
4 views63 pages

Essential Guide to Secure Coding Practices

Module 1

Uploaded by

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

Essential Guide to Secure Coding Practices

Module 1

Uploaded by

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

Secure Coding

Dr Adarsh Rag S
Department of CSE
Contact: 8951172344

Secure Coding Dr Adarsh Rag S 1


Security Concepts

▪ Computer security is preventing attackers from achieving


objectives through unauthorized access or unauthorized use
of computers and networks
▪ Programs are constructed from software components and
custom- developed source code.
▪ Software components are the elements from which larger
software programs are composed
▪ Software components include shared libraries such as
dynamic-link libraries (DLLs), ActiveX controls, Enterprise
JavaBeans, and other compositional units
▪ Software components are not directly executed by an end
user
▪ Software components cannot have vulnerabilities because
they are not executable outside of the context of a program.
Secure Coding Dr Adarsh Rag S 2
Security Concepts

▪ Source code comprises program instructions in their original


form

▪ A programmer is concerned with properties of source code


such as correctness, performance, and security.

▪ A system integrator is responsible for integrating new and


existing software components to create programs or systems
that satisfy a particular set of customer requirements.

▪ System administrators are responsible for managing and


securing one or more systems, including installing and
removing software, installing patches, and managing system
privileges.

▪ Network administrators are responsible for managing the


Securesecure
Coding operations of networks. Dr Adarsh Rag S 3
Security Concepts

▪ A security analyst is concerned with properties of security


flaws and how to identify them.

▪ A vulnerability analyst is concerned with analyzing


vulnerabilities in existing and deployed programs.

▪ A security researcher develops mitigation strategies and


solutions and may be employed in industry, academia, or
government.

▪ The attacker is a malicious actor who exploits vulnerabilities


to achieve an objective. These objectives vary depending on
the threat. The attacker can also be referred to as the
adversary, malicious user, hacker, or other alias.
Secure Coding Dr Adarsh Rag S 4
Security Concepts

Secure Coding Dr Adarsh Rag S 5


Security Policy

▪ A set of rules and practices that specify or regulate how a


system or organization provides security services to
protect sensitive and critical system resources.

Security Flaws
▪ A security flaw is a software defect that poses a potential
security risk.
▪ Eliminating software defects eliminate security flaws.
▪ To identify and prioritize security flaws according to the risk
they pose, existing tools and methods must be extended
or supplemented to assume the existence of an attacker

Secure Coding Dr Adarsh Rag S 6


Vulnerabilities

▪ A set of conditions that allows an attacker to violate an


explicit or implicit security policy.
▪ Not all security flaws lead to vulnerabilities.
▪ A security flaw can cause a program to be vulnerable to
attack.
▪ Vulnerabilities can also exist without a security flaw.

Secure Coding Dr Adarsh Rag S 7


Exploits

▪ Vulnerabilities in software are subject to exploitation.


▪ Exploits can take many forms, including worms, viruses,
and trojans.
▪ Exploit: A technique that takes advantage of a security
vulnerability to violate an explicit or implicit security policy.
▪ Proof-of-concept exploits may be necessary
▪ proof-of-concept exploit in the wrong hands can be quickly
transformed into a worm or virus or used in an attack

Secure Coding Dr Adarsh Rag S 8


Mitigations
▪ A mitigation is a solution for a software flaw or a
workaround that can be applied to prevent exploitation of a
vulnerability.
▪ At the source code level, mitigations can be as simple as
replacing an unbounded string copy operation with a
bounded one.
▪ At a system or network level, a mitigation might involve
turning off a port or filtering traffic to prevent an attacker
from accessing a vulnerability.
▪ The preferred way to eliminate security flaws is to find and
correct the actual defect.
▪ However, in some cases it can be more cost-effective to
eliminate the security flaw by preventing malicious inputs
Secure Coding Dr Adarsh Rag S 9
Mitigations

▪ Mitigation: Methods, techniques, processes, tools, or


runtime libraries that can prevent or limit exploits against
vulnerabilities.

Secure Coding Dr Adarsh Rag S 10


Strings

Character Strings
▪ Strings from sources such as
▪ command-line arguments,
▪ environment variables,
▪ console input,
▪ text files, and network connections
▪ are of special concern in secure programming because
they provide means for external input to influence the
behavior and output of a program

Secure Coding Dr Adarsh Rag S 11


Strings

Character Strings
▪ Graphics-and Web-based applications, make extensive
use of text input fields
▪ Also, standards like XML, data exchanged between
programs is increasingly in string form.
▪ As a result, weaknesses in
▪ string representation,
▪ string management, and
▪ string manipulation have led to a broad range of
software vulnerabilities and exploits.

Secure Coding Dr Adarsh Rag S 12


Strings
String Data Type
▪ A string consists of a contiguous sequence of characters
terminated by and including the first null character.
▪ A pointer to a string points to its initial character.
▪ The length of a string is the number of bytes preceding the
null character, and the value of a string is the sequence of
the values of the contained characters, in order.
▪ Strings are implemented as arrays of characters and are
susceptible to the same problems as arrays.

Secure Coding Dr Adarsh Rag S 13


Common String Manipulation Errors

▪ Manipulating strings in C or C++ is error prone.


▪ Four common errors are
▪ Unbounded string copies,
▪ off-by-one errors,
▪ Null-termination errors, and
▪ String truncation.

Secure Coding Dr Adarsh Rag S 14


Improperly Bounded String Copies

▪ Improperly bounded string copies occur when data is


copied from a source to a fixed-length character array (for
example, when reading from standard input into a
fixed-length buffer).

Secure Coding Dr Adarsh Rag S 15


Improperly Bounded String Copies
▪ This code has a potential security vulnerability due to the
use of the gets() function on line 07, which can cause
buffer overflow.
▪ gets() does not check the size of the buffer, allowing input
that can exceed the buffer's allocated space, potentially
leading to undefined behavior or security breaches.

Secure Coding Dr Adarsh Rag S 16


Improperly Bounded String Copies

#include <stdio.h>
#include <stdlib.h>

void get_y_or_n(void) {
char response[8];
puts("Continue? [y] n: ");
fgets(response, sizeof(response), stdin);
// safer alternative to gets()
if (response[0] == 'n')
exit(0);
return;
}

“Do not copy data from an unbounded source to a fixed-length


array.”

Secure Coding Dr Adarsh Rag S 17


Improperly Bounded String Copies
▪ strcpy(), strcat(), and sprintf(), perform unbounded copy
operations.
▪ Risks and Safer Alternatives:
▪ strcpy(): Risk of buffer overflow if the destination buffer is
smaller than the source string.
▪ Use strncpy() for safety.
▪ strcat(): Risk of buffer overflow if the destination buffer
can't hold the concatenated result.
▪ Use strncat() for safety.
▪ sprintf(): Risk of buffer overflow if the formatted string
exceeds the buffer size.
▪ Use snprintf() for safety.
Secure Coding Dr Adarsh Rag S 18
Improperly Bounded String Copies

Secure Coding Dr Adarsh Rag S 19


Improperly Bounded String Copies

▪ For example, if argc = 3,


▪ argv will look something like this:
▪ argv[0] – Points to the program name (e.g., ./program).
▪ argv[1] – Points to the first argument (e.g., arg1).
▪ argv[2] – Points to the second argument (e.g., arg2).
▪ argv[3] – Is always NULL (this is argv[argc]).

Secure Coding Dr Adarsh Rag S 20


Improperly Bounded String Copies

▪ The program contains a vulnerability because it uses


strcpy() to copy the program name (stored in argv[0]) into
the prog_name buffer, which is 128 bytes long.
▪ two potential issues:
▪ 1. Buffer Overflow Vulnerability
▪ The strcpy() function does not check the size of the source
string or the destination buffer.

Secure Coding Dr Adarsh Rag S 21


Improperly Bounded String Copies

▪ If the string in argv[0] is larger than 128 bytes, it will


overflow the prog_name buffer, potentially overwriting
adjacent memory.
▪ This overflow could lead to unpredictable behavior,
including crashes, data corruption, or security
vulnerabilities that an attacker could exploit to execute
arbitrary code.
▪ NULL argv[0] IssueAlthough argv[0] conventionally
contains the program name, it’s possible for an attacker to
invoke the program with argv[0] set to NULL.
▪ If this happens, the program will pass a NULL pointer to
strcpy(), which leads to undefined behavior and can cause
the program to crash.
Secure Coding Dr Adarsh Rag S 22
Off-by-One Errors

Secure Coding Dr Adarsh Rag S 23


Off-by-One Errors

▪ Off-by-one errors are similar to unbounded string copies in


that both involve writing outside the bounds of an array.
▪ In strcpy_s(s1, sizeof(s2), s2) (Line 11):
▪ Problem: You are passing the size of s2 (which is 11
bytes) as the size of the destination buffer s1 (which is
only 10 bytes, including the null terminator).
▪ This creates an off-by-one error where one additional
character could be copied, leading to buffer overflow.
▪ Fix: The size argument for strcpy_s should be the size of
the destination buffer (s1), not the source string (s2).

Secure Coding Dr Adarsh Rag S 24


Null-Termination Errors

▪ Another common problem with strings is a failure to


properly null-terminate them.
▪ A string is properly null-terminated if a null terminator is
present at or before the last element in the array.
▪ If a string lacks the terminating null character, the program
may be tricked into reading or writing data outside the
bounds of the array.
▪ Strings must contain a null-termination character at or
before the address of the last element of the array before
they can be safely passed as arguments to standard
string-handling functions, such as strcpy() or strlen().

Secure Coding Dr Adarsh Rag S 25


Null-Termination Errors

▪ Null-terminated strings: The last element of the string array


must be '\0’.
▪ Safety in functions: Functions like strcpy() and strlen() rely
on this null character to know where the string ends.
▪ Common mistake: Forgetting to add a null-termination
character, especially when manipulating strings manually
or allocating fixed-size arrays, can lead to dangerous
bugs.

Secure Coding Dr Adarsh Rag S 26


String Truncation

▪ String truncation can occur when a destination character


array is not large enough to hold the contents of a string.
▪ String truncation may occur while the program is reading
user input or copying a string and is often the result of a
programmer trying to prevent a buffer overflow.
▪ Although not as bad as a buffer overflow, string truncation
results in a loss of data and, in some cases, can lead to
software vulnerabilities.

Secure Coding Dr Adarsh Rag S 27


String Errors without Functions

▪ Most of the functions defined in the standard string-handling


library <string.h>, including strcpy(), strcat(), strncpy(),
strncat(), and strtok(), are susceptible to errors.
▪ Microsoft Visual Studio, for example, has consequently
deprecated many of these functions.
▪ The program accepts a string argument, copies it character
by character into a buffer of 128 characters, and prints the
result.
▪ However, if the input string exceeds 127 characters (to
account for the null terminator), it will write beyond the bounds
of the buffer, leading to a potential buffer overflow vulnerability

Secure Coding Dr Adarsh Rag S 28


String Errors without Functions

Secure Coding Dr Adarsh Rag S 29


String Vulnerabilities and Exploits

▪ These errors become dangerous when code operates on


untrusted data from external sources such as command-line
arguments, environment variables, console input, text files,
and network connections.
▪ Depending on how a program is used and deployed, external
data may be trusted or untrusted.
▪ However, it is often difficult to predict all the ways software
may be used.
▪ Frequently, assumptions made during development are no
longer valid when the code is deployed.
▪ Changing assumptions is a common source of vulnerabilities.

Secure Coding Dr Adarsh Rag S 30


Secure Coding Dr Adarsh Rag S 31
String Vulnerabilities and Exploits

Secure Coding Dr Adarsh Rag S 32


Security Flaw: IsPasswordOK

▪ The security flaw in the IsPasswordOK program that allows


an attacker to gain unauthorized access is caused by the call
to gets().
▪ The gets() function, as already noted, copies characters from
standard input into Password until endof-file is encountered or
a newline character is read.
▪ The Password array, however, contains only enough space
for an 11-character password and a trailing null character.
▪ This condition results in writing beyond the bounds of the
Password array if the input is greater than 11 characters in
length.

Secure Coding Dr Adarsh Rag S 33


Security Flaw: IsPasswordOK

Secure Coding Dr Adarsh Rag S 34


Security Flaw: IsPasswordOK

▪ The condition that allows an out-of-bounds write to occur is


referred to in software security as a buffer overflow.
▪ A buffer overflow occurs at runtime; however, the condition
that allows a buffer overflow to occur (in this case) is an
unbounded string read, and it can be recognized when the
program is compiled.
▪ Before looking at how this buffer overflow poses a security
risk, we first need to understand buffer overflows and process
memory organization in general.

Secure Coding Dr Adarsh Rag S 35


Security Flaw: IsPasswordOK

▪ The IsPasswordOK program has another problem: it does not


check the return status of gets().
▪ This is a violation of “FIO04-C. Detect and handle input and
output errors.”
▪ When gets() fails, the contents of the Password buffer are
indeterminate, and the subsequent strcmp() call has
undefined behavior.
▪ In a real program, the buffer might even contain the good
password previously entered by another user.

Secure Coding Dr Adarsh Rag S 36


Buffer Overflows

▪ Buffer overflows occur when data is written outside of the


boundaries of the memory allocated to a particular data
structure.
▪ C and C++ are susceptible to buffer overflows because these
languages
■ Define strings as null-terminated arrays of characters
■ Do not perform implicit bounds checking
■ Provide standard library calls for strings that do not enforce
bounds checking
▪ Depending on the location of the memory and the size of the
overflow, a buffer overflow may go undetected but can corrupt
data, cause erratic behavior, or terminate the program
Secure Coding Dr Adarsh Rag S
abnormally. 37
Buffer Overflows

▪ Buffer overflows: they are not always discovered during the


development and testing of software applications.
▪ Not all C and C++ implementations identify software flaws
that can lead to buffer overflows during compilation or report
out-of-bound writes at runtime.

Secure Coding Dr Adarsh Rag S 38


Process Memory Organization

▪ Process: A program instance that is loaded into memory and


managed by the operating system.

Secure Coding Dr Adarsh Rag S 39


Stack Management

▪ The stack supports program execution by maintaining


automatic process-state data.
▪ If the main routine of a program, for example, invokes function
a(), which in turn invokes function b(), function b() will
eventually return control to function a(), which in turn will
return control to the main() function

Secure Coding Dr Adarsh Rag S 40


Stack Smashing
▪ Stack smashing occurs when a buffer overflow overwrites
memory in the execution stack, which can compromise a
program's reliability and security.
▪ This type of vulnerability often leads to the modification of
automatic variables or even the execution of arbitrary code,
typically by altering crucial values such as the return address
on the stack.
▪ In the IsPasswordOK program, the password is stored on the
stack alongside the return address of the main function.
▪ If the password buffer overflows, it can overwrite the return
address, allowing an attacker to control the program’s
execution.
▪ This is a classic example of how stack-smashing attacks
Secure Coding Dr Adarsh Rag S 41
Secure Coding Dr Adarsh Rag S 42
This flaw can easily be demonstrated by entering a 20-character password of
“12345678901234567890” that causes the program to crash
Secure Coding Dr Adarsh Rag S 43
Mitigation Strategies for Strings

▪ Due to the prevalence of buffer overflows caused by string


manipulation errors in C and C++, several mitigation
strategies have been developed.
▪ These strategies either aim to prevent buffer overflows or
detect and recover from them securely to avoid exploitation.
▪ Instead of relying on just one approach, it is often beneficial to
use a defense-in-depth strategy, which combines prevention
techniques, such as secure string handling, with runtime
detection and recovery methods to enhance security.

Secure Coding Dr Adarsh Rag S 44


String Handling

▪ The CERT C Secure Coding Standard recommends adopting a consistent


approach to handling strings throughout a project to avoid inconsistencies
caused by individual programmer choices.

▪ String-handling functions can be categorized by how they manage


memory:

▪ Caller allocates, caller frees (C99, OpenBSD, C11 Annex K) – Ensures


clarity regarding memory management, helping prevent memory leaks.

▪ Callee allocates, caller frees (ISO/IEC TR 24731-2) – Ensures sufficient


memory allocation but depends on successful malloc() calls.

▪ Callee allocates, callee frees (C++ std::basic_string) – Considered the


most secure approach but is only available in C++.

▪ Each model has its own advantages in terms of security and memory
management.
Secure Coding Dr Adarsh Rag S 45
Dynamic Memory Management

Secure Coding Dr Adarsh Rag S 46


Secure Coding Dr Adarsh Rag S 47
String

▪ A character array
▪ ASCII values

Secure Coding Dr Adarsh Rag S 48


Secure Coding Dr Adarsh Rag S 49
Secure Coding Dr Adarsh Rag S 50
Secure Coding

▪ A programmable

Secure Coding Dr Adarsh Rag S


Secure Coding Dr Adarsh Rag S 52
Secure Coding Dr Adarsh Rag S 53
Secure Coding Dr Adarsh Rag S 54
Secure Coding Dr Adarsh Rag S 55
Secure Coding Dr Adarsh Rag S 56
Secure Coding Dr Adarsh Rag S 57
Secure Coding Dr Adarsh Rag S 58
Secure Coding Dr Adarsh Rag S 59
Secure Coding Dr Adarsh Rag S 60
Secure Coding Dr Adarsh Rag S 61
Secure Coding Dr Adarsh Rag S 62
Thank you

Secure Coding Dr Adarsh Rag S 63

You might also like