Sec+ Chapter 06: Secure Coding Flashcards
SDLC
Software development lifecycle
The process of designing, creating, supporting, and maintaining software. The eight phases of the SDLC are:
1) Feasibility
2) Analysis and requirements definition
3) Design
4) Development
5) Testing and integration
6) Training and transition
7) Ongoing operations and maintenance
8) Disposition
SDLC Feasibility phase
Where initial investigations into whether the effort should occur are conducted
Looks at alternative solutions and high-level costs for each solution proposed
Results in recommendation with a plan to move forward
SDLC Analysis and requirements definition phase
Get customer input to determine what the desired functionality is, what the current system or app does, what it doesn’t do, and what improvements are desired
SDLC Design phase
Design for functionality, architecture, integration points and techniques, dataflows, business processes, and other required elements
SDLC Development phase
The actual coding of the app
May involve unit testing, where small components are tested individually to ensure they function properly
SDLC Testing and integration phase
Formal testing with customers and others outside of the dev team
Individual units or software components are integrated and tested for proper functionality
Could also include connections to outside services, data sources, etc
UAT
User acceptance testing
A process to ensure that users are satisfied with the software and its functionality
SDLC Training and transition phase
Ensuring that end-users are trained on the software and that it has successfully entered general use
Also called acceptance, installation, and deployment phase
SDLC Ongoing operations and maintenance phase
Once the project has reached completion
Longest phase of the SDLC
Includes patching, updating, minor mods, and daily support
SDLC Disposition phase
When a product reaches the end of its life
Shutting down old products can save money, replacing existing tools may require specific knowledge or additional effort, and data and systems may need to be preserved or properly disposed of
Development environment
Used for devs to do their work
Sometimes each dev gets their own environment, sometimes it’s shared
Test environment
Software or systems can be tested here without impacting the production environment
QA takes place here
Staging environment
A transition environment for code that has successfully cleared testing and is waiting to be deployed into production
Real world environment that works and feels exactly like the production environment
Production environment
The live system where the work is rolled out to the user community
Software, patches, and other changes that have been tested and approved move to production
Waterfall development
A sequential SDLC methodology in which each phase is followed by the next
Phases don’t overlap, and each logically leads to the next
Not always the first choice due to its inflexibility, but still used for complex systems
Phases of waterfall development
1) Requirements are gathered and documented
2) Analysis to build business rules and models
3) Software architecture is designed
4) Coding and integration of software
5) Testing and debugging
6) Operational phase with support, maintenance, and ongoing operations activities
Spiral development
Uses the linear concepts from Waterfall and adds a flexible, iterative process that revisits four phases multiple times during the SDLC to gather more detailed requirements, design functionality guided by requirements, and build based on design
Heavy emphasis on risk assessment
Phases of spiral development
1) Identification / requirements gathering, which gathers business reqs, system reqs, and detailed reqs for subsystems or modules
2) Design, conceptual, architectural, logical, and sometimes physical or final design
3) Build, which produces an initial proof of concept and then further development releases until the final production build is produced
4) Evaluation, which involves risk analysis for the development project to monitor the feasibility of delivering the software from a technical and managerial viewpoint. Customer testing and feedback
Agile development
Breaks up work into smaller units, and work is broken up into sprints
Rooted in 4 premises:
1) Individuals and interactions are more important than processes and tools
2) Working software is preferable to comprehensive documentation
3) Customer collaboration replaces contract negotiation
4) Responding to change is key, don’t just follow the plan
12 Principles of Agile
1) Ensure customer satisfaction with early and continuous delivery of software
2) Welcome changing requirements, even late in the dev process
3) Deliver working software frequently (weeks > months)
4) Ensure daily cooperation between devs and businesspeople
5) Projects should be built around motivated individuals who get support, trust, and environment they need
6) Face-to-face convos are the most efficient way to convey information inside the dev team
7) Progress is measured by working software
8) Dev should be done at a sustainable pace that can be maintained daily
9) Pay attention to technical excellence and good design
10) Simplicity is essential
11) The best architectures, requirements, and designs emerge from self-organizing teams
12) Teams should reflect on how to be more effective, and then implement that behavior regularly
CI
Continuous integration
A development practice that checks code into a shared repository on a consistent, ongoing basis
The goal is to enable the use of automation and scripting to implement automated courses of action that result in continuous delivery of code
You also need automated security checks that evaluate the updated code with your existing security baselines
Ensure anything deployed to production is as safe as possible
CD
Continuous deployment
Rolls out tested changes into production automatically as soon as they’ve been tested
You can automate security checks during the testing process, and if a problem is found the app won’t be deployed
Security best practices in CI/CD
Logging, reporting, and continuous monitoring must be designed to fit into the CI/CD process to avoid rogue devs inserting flawed or malicious code
OWASP
Open web application security project
The home of a broad community of devs and security practitioners
Provides a regularly updated list of proactive controls that serve as best practices, but also how web app security threats change year to year
API
Application programming interface
Serves as interface between clients and servers, or apps and OS
Defines how a client should ask for info from the server and how the server responds
What does API security rely on?
Authentication
Authorization
Proper data scoping to ensure that too much data isn’t released
Rate limiting
Input filtering
Appropriate monitoring and logging
BONUS: Secure underlying systems, configure API endpoint server or service, and provide normal network layer security to protect the service
Pair programming
Agile dev technique that puts two devs at one workstation
One writes the code, the other reviews the code as it’s written
Provides real-time code review and ensures multiple devs are familiar with the code that’s written
Over the shoulder
Dev who writes the code explains it to the other dev
Allows peer review of code and can assist devs in understanding how the code works
Pass around code review
AKA: Email pass around code review
Form of manual peer review done by sending completed code to reviewers who check it for issues
Tool assisted reviews
This relies on formal or informal software-based tools to conduct code reviews
EX: Atlassian’s Crucible collaborative code review tool, Codacy’s static code review tool, and Phabricator’s Differential code review tool
Fagan inspection
A structured, formal code review intended to find a variety of problems during the dev process
It specifies entry and exit criteria for processes, ensuring that a process isn’t started before appropriate diligence has been performed
6 phases of the Fagan inspection
1) Planning: Prep of materials, attendees, location
2) Overview: Prepares a team by reviewing the materials and assigning roles like coder, reader, reviewer, and mod
3) Preparation: Review the code and document issues or questions
4) Meeting: Identify defects based on notes from prep phase
5) Rework: Resolve issues
6) Follow up: Ensure all issues identified have been found and that no new defects were created during resolution process
Static code analysis
AKA: source code analysis
Conducted by reviewing the code for an app
Can be a type of white box testing with full visibility to the testers
Can be conducted with automated tools, or manually by reviewing the code (code understanding)
Automation needs to be reviewed though, since you could turn false positives on issues
Dynamic code analysis
Relies on the execution of the code while providing it with input to test the software
Strong preference for automated testing due to the volume of tests needed
Fuzzing
AKA: Fuzz testing
Sends invalid or random data to an app to test its ability to handle unexpected data. The app is monitored to determine if it crashes, fails, or responds, in an incorrect manner
Usually automated
Useful for detecting input validation and logic issues as well as memory leaks and error handling
Injection vulnerabilities
One of the primary mechanisms an attacker will use to break through a web app and gain access to the systems supporting it
Attacker supplies code to the web app as input and tricks the web server into either executing that code or supplying it to another server to execute
SQL injection attack
Attack that interferes with the queries a web app makes to its database
Allows attackers access to sensitive data modify db data, execute admin operations on db, recover content of a file, and issue commands to the OS
Blind content-based SQL injection
When an attacker sends input to the web app that tests whether the app is interpreting injected code before attempting to carry out an attack
Blind timing-based SQL injection
Where an attacker uses the amount of time required to process a query as a channel for retrieving information from a database
The attack depends on delay mechanisms provided by different database platforms
Code injection attacks
Inserting malicious HTML code into web pages created by a dev
EX: XSS
Command injection attacks
When application code reaches back to the OS and tells it to execute a command
Allows attackers the ability to directly manipulate the OS
Session hijacking
Sidejacking
When an attacker gains access over a session ID to pose as the victim and communicate directly to a service without a username or password
Defense: Use SSL or TLS when communicating across the network
Cookie
A storage object maintained in the user’s browser that holds variables that may later be accessed by the website that created them
Cookie transmission
Transmitted as part of the HTTP header information provided by a site. EX:
1) User accesses a site’s login form and authenticates with their credentials
2) If user passes authentication, site provides browser with a cookie that can be used for future authentication
3) Once user has a valid cookie stored in browser, browser then transmits that cookie with all future requests made to the site
4) Site inspects the cookie and determines user has already authenticated, doesn’t need to reenter password or complete other authentication tasks
Ways to steal a cookie
1) Eavesdropping on unencrypted network connections and stealing a copy of the cookie as its transmitted between user and site
2) Installing malware on the user’s browser that retrieves the cookies and transmits them back to the attacker
3) Engaging in a man in the middle attack
How to protect against cookie theft
Have web devs mark cookies with a SECURE attribute so they’re never transmitted over unencrypted HTTP connections
Servers and web browsers understand that they must only be sent over encrypted channels to protect against session replay attacks.
Pass the hash attack
A replay attack where an attacker intercepts the hash value associated with a password that’s sent across the network during the authentication process
If they can get the hash, they can replay the hash back to server and pretend they’re the original workstation
Defense: Make sure the client and server are always communicating over an encrypted channel like SSL or TLS
Defense: Salt the hash with a session ID, which makes it a one-time authentication process
Unvalidated redirects
When attackers take advantage of URL redirects and send users to malicious sites
Insecure direct object reference
When an app doesn’t perform authorization checks on a user’s ability to access documents
Attackers will modify a URL to attempt to retrieve docs or other objects
Directory traversal
When a web server misconfiguration lets attackers navigate the directory substructure and access files that should remain secure
EX: ../../../../../../etc/psswd
File inclusion attacks
A level above directory traversal
Instead of retrieving a file from the local OS, this actually executes the code in a file
Local file intrusion
Attacks that seek to execute code stored in a file located elsewhere on the web server
Remote file intrusion
Attacks that seek to execute code stored on a remote server
Attackers can directly control the code being executed without having to first store a file on the local server
Privilege escalation
When attackers increase their access to more privileged accounts by exploiting vulnerabilities
Defense tactics:
Patch vulnerabilities that could give root access ASAP
Update antimalware software
Data execution prevention: Only allow apps to run in certain areas of memory where that function is allowed
Randomize where information is stored in memory
XSS
Cross site scripting
Can occur anywhere a web app uses input from a user
Injection attacks where attackers send malicious code, generally in the form of a browser side script, to a different end user
End user’s browser doesn’t know the script shouldn’t be trusted and will execute the script because it thinks it’s from a trusted source
XSS can access cookies, get session tokens, see sensitive info retained by the browser, or rewrite HTML content of a page
Reflected XSS
Non persistent
Found on a site that allows someone to run scripts within user input fields
Attacker needs an external delivery mechanism like email, text, or forum message
Web apps vulnerable to reflected XSS can unsafely display search results, error messages, or any other immediate response from a user’s query (reflected back to attacker)
Stored XSS
Persistent
When a malicious script injection is permanently stored on a target’s server and injected into a user’s session when they visit
When a user requests non-sanitized information that is stored in the database, the app sends the malicious script to the user
Attackers execute stored XSS by leaving the payloads in message forums, site posts, and comment fields
EX: HTML forum posts that contain links with XSS in it
Request forgery
Websites always make requests from servers, like text form a webserver, videos from YT, or pictures from IG
The HTML in your browser determines where the browser goes to make up that page
However, most of these requests are unauthenticated and the information is presented without any login credentials
Attackers will abuse this trust within your browser to gather information from a third party site, often without victim even knowing
That’s a request forgery
CSRF / XSRF
Cross site request forgery (sea surf), one-click attack, session riding
Takes advantage of the inherent trust your site has for your browser
Attackers can get your machine to create requests on their behalf using your credentials
Defense: Put anti-forgery techniques into the code, like cryptographic tokens
EX:
1) Attacker sends victim a funds transfer request (email link, etc)
2) Victim clicks the link, they’re already logged into bank-side server
3) After click, request is sent to bank’s webserver
4) Since victim is logged in properly, the request is performed as if it’s coming directly from them
5) If it’s a funds transfer, bank sends to the attacker. Forgery complete
SSRF
Server side request forgery
Similar to CSRF but instead of tricking a user’s browser into visiting a URL, this performs the forgery directly on the server
Attacker sends request to server which performs requests on their behalf
Allows attacker to access services they normally couldn’t
Defense: Input and output validation to ensure nothing is unexpected, WAF
EX:
1) Attacker sends a request to a server that controls a web app
2) Web server sends request to another service, like cloud file storage
3) Cloud storage sends response to webserver
4) Webserver forwards response to attacker
Input validation
Checks whether a user’s input complies with specific policies and constraints
EX: A zip code should only be a certain number of characters long and have a specific combo of numbers
If there’s no validation, nothing prevents an attacker from exploiting web apps by entering unexpected inputs or executing code directly
EX: Never allow single quotes or HTML </script> in the input field
Checking and correcting all input is called normalization
If the input doesn’t match validation, the app should post a message to correct the problem
Input whitelisting
The most effective form of input validation
Devs describe the exact type of input that’s expected from the user and then verifies that the input matches that spec before passing it to other processes or servers
Input blacklisting
Opposite input whitelisting
Devs describe potentially malicious input that must always be blocked
Parameter pollution
A technique that hackers use to bypass input validation controls
It thrives on defects in web platforms that don’t handle multiple copies of the same parameter properly
WAF
Web application firewalls
Similar to network firewalls, but operate at the Application layer in OSI model (layer 7)
Sits in front of a web server and receives all network traffic headed to that server
Scrutinizes the input headed to the app and performs input validation before passing input to the web server
Database normalization
Design principles for database designers to build and modify database
1) Prevents data inconsistency
2) Prevents update anomalies
3) Reduces the need for restructuring existing databases
4) Makes the database schema more informative
Parameterized Queries
A technique to protect apps against injection attacks
The client doesn’t directly send SQL code to the db server
Instead, they send arguments to the server which then inserts those arguments into a precompiled query template
Data minimization
Best defense against data exposure
The practice of never collecting sensitive info you don’t need, and disposing of any sensitive info they do collect as soon as it’s no longer needed
Tokenization
A technique to protect against data exposure
Take sensitive data and replace it with a completely different, unique identifier
This data can be confirmed as accurate by using a lookup table that holds the real values
EX: SSN goes from 266-12-1112 to 689-74-0987
Hashing
A technique to protect against data exposure
Uses a cryptographic hash to replace sensitive identifiers with an irreversible alternative identifier
Often, these values are salted with random characters prior to hashing, which, makes them resistant to rainbow tables
Code signing
Provides devs with a way to confirm the authenticity of their code to end-users
Devs use a cryptographic function to sign their code with a private key
Browsers use their public key to verify the signature and ensure the code is legit and unmodified by unauthorized individuals
SDK
Software development kit
Collections of software libraries combined with documentation, examples, special utilities to test and design code, and other resources that help programmers get up and running in a dev environment
Code reuse
Devs will often Reuse code between different apps
If the old code has a security vulnerability, copying that to multiple apps spreads the vulnerability to all those apps
Also need to avoid dead code, which is code that runs and processes logic, but the results aren’t used anywhere else in the app
Always ensure that reused code goes through the same rigor as internally developed code
Code integrity measurement
Uses cryptographic hash functions to verify that the code being released into production matches the code that was previously approved
Resource exhaustion
Type of DoS
When a system consumes all of its memory, storage, and processing time
Renders the system disabled
Memory leak
When an app requests memory from the OS, but never returns it
Eventually, causes the system to crash
Memory pointers
When apps use memory, they store info into a section of that memory. When they reference it, they point to that area of memory
If an attacker can make it point to a null section where nothing exists, you get a null pointer dereference
If you point to nothing in memory, it causes the app to crash that displays debugging info, ways to bypass security, or DoS
Buffer overflow
When an attacker manipulates a program into placing more data into an area of memory than is allocated for that program’s use
The goal is to overwrite one section in memory so that it spills over into another section in memory
This allows attackers to gain elevated rights for a section of the OS, or they can crash whenever they like creating DoS
Defense: Perform bounds checking to ensure nobody can overwrite sections of memory
Race conditions
When two or more operations that should be done in sequence are attempted simultaneously
EX: When two or more threads can access shared data and they try to change it at the same time, like two users adding $50 to their bank accounts at the same time but User 1 gets -$50 and User 2 gets +$50
TOCTTOU
Time of check to time of use attack
A race condition vulnerability that attackers can exploit
Hacker is able to access a file and make harmful changes between the time of check (first time the program accesses the file) and the time of use (when the software uses the file)
The opportunity window is very short due to that near simultaneous overlap
Ways to protect APIs
APIs not intended for public use should always be secured with an authentication mechanism like API key
APIs should only be accessed over encrypted channels that protect credentials like API keys from eavesdropping attacks
Driver manipulation
When an attacker convinces a user to install a malicious device deriver on their machine, which would give them complete control of the system
Shimming
A technique that takes a legit driver and wraps a malicious driver around the outside of it
The malicious driver, known as a shim, receives reqs from the OS and passes them on to the legit driver
However, the driver can also carry out its malware payload in the background
DOM based XXS
An attack that hides the attack code within the document object model
This code wouldn’t be visible to someone viewing the HTML source of the page
Other XXS attacks would leave visible traces
Input sanitization
Removing any unsafe characters from user input and modifying it to ensure it’s in a valid format for display or insertion into a database
Replay attack
When an attacker captures information that can be replayed across the network to make it seem like it’s coming from you
They want session IDs, credentials and use them later on across the network
This is not an on-path attack
Integer overflow
Where a large number is placed into a smaller section of memory, and the extra space has to go somewhere else, usually an overflow
DHCP Starvation
When attackers flood a network with IP address requests and MAC address changes each time
Causes the DHCP server to run out of addresses in its pool
Anyone else who tries to connect won’t receive an IP because it’s all been exhausted
Server side validation
All input validation checks occur on the server
Helps protect against malicious users
Third party libraries and SDKs
Code that’s already been written by others
It can extend the functionality of the programing language, speeds up dev process, and gets the app built faster
But how secure is the library? Could be filled with vulnerabilities
Version control
Allows devs to write software, check it into a version control system, and next time they want to update they can keep track of anything that’s changed between iterations
You see this in OS, file systems, wiki, etc
Effective for security to look at a file today, and see how it’s changed over time
Software diversity
Everyone runs the same software, but their binaries are slightly different from one machine to another
Use tricks in the compiler to change where the paths go during the compilation process, which makes the final binary different every time you compile
Doesn’t change functionality, just the final binary
HTTPS Headers
A way to configure a web server so that it restricts the capabilities of a browser to perform certain functions
We can tell the end user’s browser to either allow or disallow certain actions while an app is in use
EX: A header that tells a browser to only communicate with the webserver over HTTPS, and restricts all other comms
EX: Only allow scripts, stylesheets, or images from the local site to prevent XSS
EX: Prevent data from loading into an iframe to prevent XSS