0% found this document useful (0 votes)
9 views54 pages

Lecture 9 - Secure Implementation 2 - Coding 2023

Uploaded by

Aqil Syahmi
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)
9 views54 pages

Lecture 9 - Secure Implementation 2 - Coding 2023

Uploaded by

Aqil Syahmi
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

SIT Internal

ICT3103/ICT3203:
Secure Software Development
Secure Software Implementation
Part 2: References for Secure Coding
SIT Internal

SQLite?

2
SIT Internal

Leap seconds?

3
SIT Internal

What is leap seconds?

4
SIT Internal

Leap seconds

Are you using Regular Expression (Regex) for checking time input?

5
SIT Internal

Proprietary Info, Source Code Stolen in LastPass Data Breach

“Our investigation determined that


the threat actor gained access to the
Development environment using a
developer’s compromised endpoint.

While the method used for the initial


endpoint compromise is inconclusive,
the threat actor utilized their
persistent access to impersonate the
developer once the developer had
successfully authenticated using
multi-factor authentication. ”

Anyone is using LastPass? 1password?


Why or Why not?
How is it related to SSD? 6
SIT Internal

MS Teams…

7
SIT Internal

Problem details

• Microsoft Teams is an Electron app, meaning that it runs


in a browser window, complete with all the elements
required by a regular web page (cookies, session strings,
logs, etc.).

• Electron does not support encryption or protected file


locations by default, so while the software framework is
versatile and easy to use, it is not considered secure
enough for developing mission-critical products unless
extensive customization and additional work is applied.

• Vectra analyzed Microsoft Teams while trying to find a


way to remove deactivated accounts from client apps,
and found an ldb file with access tokens in clear text.

8
SIT Internal

Problem details

• Additionally, the analysts discovered that the "Cookies" folder also contained valid
authentication tokens, along with account information, session data, and marketing
tags.

Authentication token on the Cookies directory (Vectra)

• Vectra developed an exploit by abusing an API call that allows sending messages to
oneself. Using SQLite engine to read the Cookies database, the researchers received
the authentication tokens as a message in their chat window.

Token received as text in the attacker's personal chat (Vectra)


9
SIT Internal

Reply from Microsoft

“The technique described does not meet our bar for immediate servicing
as it requires an attacker to first gain access to a target network.
We appreciate Vectra Protect’s partnership in identifying and responsibly
disclosing this issue and will consider addressing in a future product
release.”

Do you accept such reply?


Will you continue using MS Team?

10
SIT Internal

Open-source vs Closed-source

• Which one you prefer?


• Which one is more “secure”?

11
SIT Internal

Agenda
OWASP
• Top 10 Proactive Controls
• [Link]
• Cheat Sheet Series
• [Link]
• Security Knowledge Framework
• [Link]
• Secure Coding Practices Quick Reference Guide
• [Link] practices-quick- reference-
guide/migrated_content

And more …
12
SIT Internal

OWASP Top 10 Proactive Controls


• Describes the most important security controls that should be adopted in every
secure software development project
• The OWASP Top 10 Proactive Controls is similar to the OWASP Top 10 but is focused
on defensive techniques and controls as opposed to risks.
– C1: Define Security Requirements
– C2: Leverage Security Frameworks and Libraries
– C3: Secure Database Access
– C4: Encode and Escape Data
– C5: Validate All Inputs
– C6: Implement Digital Identity
– C7: Enforce Access Control
– C8: Protect Data Everywhere
– C9: Implement Security Logging and Monitoring
– C10: Handle All Errors and Exceptions
13
SIT Internal

OWASP Top 10 Proactive Controls

• OWASP Top 10 Proactive


A description of each
Controls serves as the proactive control
starting point to building
secure software with
Best practices to implement the
recommended proactive control
implementation best Vulnerabilities or risks addressed by the
practices and tools. proactive control

References for further study

Tools to introduce/integrate into your secure


software development
14
SIT Internal

C2: Leverage Security Frameworks and Libraries

Description: A developer might not have sufficient knowledge or time to properly


implement security features. Leveraging security frameworks and libraries helps
accomplish security goals more efficiently and accurately.

Implementation Best Practices:


• Use trusted sources that are actively maintained
• Create and maintain an inventory catalogue of all third-party libraries
• Proactively keep libraries up to date with the help of tools if available
• Reduce attack surface by encapsulating the libraries and expose only required
behaviour into your application
15
SIT Internal

C2: Leverage Security Frameworks and Libraries

Vulnerabilities Prevented:
• OWASP Top 10 – A06:2021-Vulnerable and Outdated Components
Tools:
• OWASP Dependency Check – a Software Component Analysis (SCA) tool
to detect publicly disclosed vulnerabilities in dependencies
• [Link] – scanner for JavaScript libraries

16
SIT Internal

OWASP Dependency Check

17
SIT Internal

[Link]

18
SIT Internal

C3: Secure Database Access

Description: Secure access to database includes secure communication,


secure authentication, secure queries and secure configuration.

Implementation Best Practices:


• Secure communication – use encrypted secure channel
• Secure authentication – access to database should be properly
authenticated within a secure channel
• Secure queries – apply query parameterization
• Secure configuration – follow available standards, guides or benchmarks

19
SIT Internal

C3: Secure Database Access


Vulnerabilities Prevented:
• OWASP Top 10 – A03:2021-Injection

References:
• OWASP Cheat Sheet Series:
• [Link]
ml
• [Link]
ml
• [Link]
• Bobby Tables – [Link]

20
SIT Internal

C9: Implement Security Logging and Monitoring

Logging: Debugging and diagnostic purposes.


Security logging: To log security information during the
runtime operation of an application.
Monitoring is the live review of application and security
logs using various forms of automation. The same tools
and patterns can be used for operations, debugging and
security purposes.

Security logging can be used for:


• Feeding intrusion detection systems
• Forensic analysis and investigations
• Satisfying regulatory compliance requirements
21
SIT Internal

Secure Logging design and implementation

• Encode and validate any dangerous characters before logging to prevent log
injection attacks.
• Do not log sensitive information. For example, do not log password, session
ID, credit cards, or social security numbers.
• Protect log integrity. An attacker may attempt to tamper with the logs.
Therefore, the permission of log files and log changes audit should be
considered.
• Forward logs from distributed systems to a central, secure logging service.
This will sure log data cannot be lost if one node is compromised. This also
allows for centralized monitoring.
• PDPA!

22
SIT Internal

Secure Logging Library

• Log4J?
• winston
• Pino

And more…

23
SIT Internal

OWASP Cheat sheet series


SIT Internal

OWASP Cheat Sheet Series

• It was created by various application security professionals to provide


security guidance on specific security topics.

25
SIT Internal

OWASP Cheat Sheet Series

• In total there are 78 cheat


sheets (Keep increasing)
• For this lecture, we will focus on
Input Validation Cheat Sheet
and SQL Injection Prevention
Cheat Sheet

26
SIT Internal

Input Validation Cheat Sheet

• Input validation is performed to ensure only


properly formed data is entering the workflow in
an information system, preventing malformed
data from persisting in the database and triggering
malfunction of various downstream components.

• It should happen as early as possible in the data


flow, preferably as soon as the data is received
from the external party.

• It should not be used as the primary method of


preventing XSS, SQL Injection and other attacks.
27
SIT Internal

Implementing input validation


• Data type validators available natively in web application frameworks (such
as Django Validators, Apache Commons Validators etc).
• Validation against JSON Schema and XML Schema (XSD) for input in these
formats.
• Type conversion (e.g. [Link]() in Java, int() in Python) with strict
exception handling
• Minimum and maximum value range check for numerical parameters and
dates, minimum and maximum length check for strings.
• Array of allowed values for small sets of string parameters (e.g. days of week).
• Regular expressions for any other structured data covering the whole input
string (^...$)and not using "any character" wildcard (such as . or \S)
28
SIT Internal

Allow list vs block list


• It is a common mistake to use block list validation in order to try to detect possibly
dangerous characters and patterns like the apostrophe ' character, the string 1=1, or
the <script> tag, but this is a massively flawed approach as it is trivial for an attacker to
bypass such filters.
• Plus, such filters frequently prevent authorized input, like O'Brian, where
the ' character is fully legitimate.
• Allow list validation is appropriate for all input fields provided by the user. Allow list
validation involves defining exactly what IS authorized, and by definition, everything
else is not authorized.
• If it's well structured data, like dates, social security numbers, zip codes, email
addresses, etc. then the developer should be able to define a very strong validation
pattern, usually based on regular expressions, for validating such input.
• If the input field comes from a fixed set of options, like a drop-down list or radio
buttons, then the input needs to match exactly one of the values offered to the user in
the first place.
29
SIT Internal

Validating free-form Unicode text


Free-form text, especially with Unicode characters, is perceived as difficult to validate
due to a relatively large space of characters that need to be allowed.
It's also free-form text input that highlights the importance of proper context-aware
output encoding and quite clearly demonstrates that input validation is not the primary
safeguards against Cross-Site Scripting.

The primary means of input validation for free-form text input should be:
• Normalization: Ensure canonical encoding is used across all the text and no invalid
characters are present.
• Character category allow-listing: Unicode allows listing categories such as "decimal
digits" or "letters" which not only covers the Latin alphabet but also various other
scripts used globally (e.g. Arabic, Cyrillic, CJK ideographs etc).
• Individual character allow-listing: If you allow letters and ideographs in names and
also want to allow apostrophe ' for Irish names, but don't want to allow the whole
punctuation category.
Your application support emoji?

30
SIT Internal

Regular expressions
• Developing regular expressions can be complicated, and is well beyond the scope of this
cheat sheet.
• There are lots of resources on the internet about how to write regular expressions,
including the cheatsheet and the OWASP Validation Regex Repository.
• When designing regular expression, be aware of RegEx Denial of Service (ReDoS) attacks.
These attacks cause a program using a poorly designed Regular Expression to operate very
slowly and utilize CPU resources for a very long time.

In summary, input validation should:


• Be applied to all input data, at minimum.
• Define the allowed set of characters to be accepted.
• Define a minimum and maximum length for the data (e.g. {1,25}).

31
SIT Internal

Allow List Regular Expression Examples

Validating a U.S. Zip Code (5 digits plus optional -4)


• ^\d{5}(-\d{4})?$

Validating U.S. State Selection From a Drop-Down Menu


• ^(AA|AE|AP|AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|
HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|
NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|
TX|UT|VT|VI|VA|WA|WV|WI|WY)$

32
SIT Internal

Regular expression Denial of Service - ReDoS

• The Regular expression Denial of Service


(ReDoS) is a Denial of Service attack, that
exploits the fact that most Regular
Expression implementations may reach
extreme situations that cause them to work
very slowly (exponentially related to input
size).

• An attacker can then cause a program using


a Regular Expression (Regex) to enter these
extreme situations and then hang for a very
long time.

33
SIT Internal

Regular expression Denial of Service - ReDoS

For example, the Regex pattern or quantifier ^(a+)+$ is represented by the following non-deterministic finite
automata (NFA):

• For the input aaaaX there are 16 possible paths in the above graph. But
for aaaaaaaaaaaaaaaaX there are 65536 possible paths, and the number is double for each
additional a. This is an extreme case where the naïve algorithm is problematic, because it must pass
on many paths to find a non-matching input.

• The root-cause of the above example is in a Regex engine feature called backtracking. Simply, if the
input (token) fails to match, the engine goes back to previous positions where it could take a
different path. The engine tries this many times until it explores all possible paths. In the above
example, this feature create a long running loop because there were many paths to explore due to
inefficient Regex pattern.
34
SIT Internal

Evil Regex
A Regex pattern is called Evil Regex if it can get stuck on crafted input.
Evil Regex contains:
• Grouping with repetition
• Inside the repeated group:
– Repetition
– Alternation with overlapping
Examples of Evil Regex:
• (a+)+
• ([a-zA-Z]+)*
• (a|aa)+
• (a|a?)+
• (.*a){x} for x \> 10
• All the above are susceptible to the input aaaaaaaaaaaaaaaaaaaaaaaa! (The minimum input length might
change slightly, when using faster or slower machines).

35
SIT Internal

Evil Regex attack


• The attacker might use the above knowledge to look for applications that use Regular Expressions,
containing an Evil Regex, and send a well-crafted input, that will hang the system.
• Alternatively, if a Regex itself is affected by a user input, the attacker can inject an Evil Regex, and
make the system vulnerable.
• An attacker can hang a WEB-browser (on a computer or potentially also on a mobile device), hang a
Web Application Firewall (WAF), attack a database, and even stack a vulnerable WEB server.

36
SIT Internal

SQL Injection Prevention Cheat Sheet

• Defenses to prevent SQL injection in OWASP Cheat Sheet Series:


[Link]
[Link]

37
SIT Internal

SQL Injection Prevention Cheat Sheet

Primary Defenses:
• Option 1: Use of Prepared Statements (with Parameterized Queries)
• Option 2: Use of Properly Constructed Stored Procedures
• Option 3: Allow-list Input Validation
• Option 4: Escaping All User Supplied Input

Additional Defenses:
• Also: Enforcing Least Privilege
• Also: Performing Allow-list Input Validation as a Secondary Defense

38
SIT Internal

Bobby Tables

• Bobby Tables is a guide to preventing SQL injection.

39
SIT Internal

Bobby Tables

• Code examples to prevent SQL injection in Bobby Tables:


• [Link]

40
SIT Internal

OWASP Security Knowledge Framework (SKF)

• It contains best practice code examples showing how to prevent hackers


gaining access and running exploits in your application.

41
SIT Internal

OWASP Security Knowledge Framework (SKF)

• Code examples for different languages and frameworks in OWASP


Security Knowledge Framework

42
SIT Internal

OWASP Secure Coding Practices Quick Reference Guide

It defines a set of security coding practices in a checklist format that can be adopted into building secure
software.
• Input validation
• Output encoding
• Authentication and password management
• Session management
• Access control
• Cryptographic practices
• Error handling and logging
• Data protection
• Communication security
• Database security
• File management
• General coding practices
43
SIT Internal

OWASP Secure Coding Practices Quick Reference Guide

44
SIT Internal

OWASP Secure Coding Practices Quick Reference Guide

45
SIT Internal

Question time

• Remember the question “how to secure your database credential?”

46
SIT Internal

(Maybe) Solution

47
SIT Internal

Jenkins

48
SIT Internal

Development workflow for Docker apps

Developing a Docker application is similar to the way you develop an application


without Docker.
The difference is that while developing for Docker, you're deploying and testing
your application or services running within Docker containers in your local
environment. 49
SIT Internal

Dockerfile

• Previous lab introduce the concept to


execute docker image.
• It is possible to write the team’s own
docker image to simply the
development and deployment process.
• A Dockerfile is a text document that
contains all the commands a user could
call on the command line to assemble
an image.
50
SIT Internal

docker-compose

• Compose is a tool for defining and


running multi-container Docker
applications.
• Compose use a YAML file to configure
application’s services.
• With a single command, it can create and
start all the services from the
configuration.

51
SIT Internal

Practical Test

• 15 November during the lab session.


• 2.5 hours.
• First section: 1:15 p.m. – 3:45 p.m.
• Second section: 4:15 p.m. – 6:45 p.m.
• Scope: Lab 2 – Lab 10, open book and open internet.
• You can use your laptop / Lab PC to conduct the test, please come 15
minutes earlier to ensure you have enough time to setup.

52
SIT Internal

QUESTION AND COMMENTS?


SIT Internal

Reference

• [Link]
lastpass-password-manager-data-breach
• [Link]
• [Link]
community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
• [Link]
auth-tokens-as-cleartext-in-windows-linux-macs/
• [Link]
us/dotnet/architecture/microservices/docker-application-development-
process/docker-app-development-workflow

54

You might also like