Docsity

Input Validation and Sanitization in Web Applications, Exams of Equine Science and Management

Toggle sidebar
bg1
SC EST (110 Questions and Answers)
What is vulnerability - Correct answer a quality defect, based on bad
security practices, notably a flaw in a system design
What is threat - Correct answer anything that is able to be exploited by a
known vulnerability, intentionally or accidentally, that could potentially hurt
an asset
What is exploit - Correct answer a piece of code that utilises a known
vulnerability to cause unintended or unanticipated behaviour
What is authentication - Correct answer the process or action of proving or
showing to be true, genuine or valid
What is authorization - Correct answer to gain official permission or
privelleges to resources (aka access control within infosec)
Types of attackers and definition - Correct answer 1. Hacktivist - loosely
organised groups with political motivations
2. Script Kiddies - steals pre-existing scripts to wreck havoc
3. State Sponsored - gathered intelligence, unlimited budget and resources
All likes doing: Denial of Service, information theft, defacement
Why secure web applications? (possible consequences) - Correct answer
(4 reasons)
1. Business
- several organisation/business related implications when these entities are
attacked.
- sensitive info, intellectual properties damage, business continuity and
other factors are potentially vulnerable
2. Data Theft
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15

Partial preview of the text

Download Input Validation and Sanitization in Web Applications and more Exams Equine Science and Management in PDF only on Docsity!

SC EST (110 Questions and Answers)

What is vulnerability - Correct answer a quality defect, based on bad security practices, notably a flaw in a system design What is threat - Correct answer anything that is able to be exploited by a known vulnerability, intentionally or accidentally, that could potentially hurt an asset What is exploit - Correct answer a piece of code that utilises a known vulnerability to cause unintended or unanticipated behaviour What is authentication - Correct answer the process or action of proving or showing to be true, genuine or valid What is authorization - Correct answer to gain official permission or privelleges to resources (aka access control within infosec) Types of attackers and definition - Correct answer 1. Hacktivist - loosely organised groups with political motivations

  1. Script Kiddies - steals pre-existing scripts to wreck havoc
  2. State Sponsored - gathered intelligence, unlimited budget and resources All likes doing: Denial of Service, information theft, defacement Why secure web applications? (possible consequences) - Correct answer (4 reasons)
  3. Business
  • several organisation/business related implications when these entities are attacked.
  • sensitive info, intellectual properties damage, business continuity and other factors are potentially vulnerable
  1. Data Theft
  • sensitive info such as usernames, passwords and credit card info can be stolen
  • includes trade secrets too, giving away competitive advantage
  1. Sabotage
  • hacking can have effects on digital data or physical equipment
  • could corrupt info, or encrypted, withheld info as part of ransom
  • impersonation attacks could ruin reputation or trust in a person or company
  1. Legal requirements
  • legal requirements that company needs to follow
  • eg. Personal Data Protection Act (PDPA), Basel II, SOX, PCI-DSS 3 common misconceptions - Correct answer 1. Encryption
  • Encrypted channels protect from eavesdropping by third parties like 256 bit TLS v1.2 is not enough
  • Certificates are not protecting against attacks
  1. Intrusion Detection
  • Various security information and event management (SIEM) tools can help identify attacks but require training, and specified signatures and configuration
  • They do not prevent attacks as well
  1. Firewall
  • Firewalls do not protect the web application, it only blocks traffic on other ports What is blackbox pentest - Correct answer -No detailed knowledge of the target system, identical to a hacker attack
  • Less than 10% of vulnerabilities are exposed What is glassbox pentest - Correct answer - knowledge of the target system, Administrative access to the target system and therefore able to access to logs and internal system information, partial analysis of the source code
  • Up to 25% of vulnerabilities are found

not secure as people can disable JS checking or modify the input data with tools like burp suite)

  • As a security measure, on the client side (If the user supplied data is further processed by JS, input validation is needed on the client side as well) What is output sanitisation - Correct answer - Refers to how an application cleans and modifies the output data so that it is not interpreted in a way that the application developer do not want
  • If an application has improper output handling, the output data may be consumed leading to vulnerabilities and actions never intended by the application developer (eg. Xss attacks, json injection, showing sensitive info) Output Sanitization Techniques - Correct answer Filter/middleware that modifies the output before it is returned to the user Eg. Remove string functions, string replace functions to convert sensitive characters like '>' When should output sanitization be done? - Correct answer - As late as possible
  • Sanitise the final version of the data that is returning Where should we sanitise output - Correct answer - Always on the server side (Where the final output for the user is created)
  • On the client side (If user supplied data is further processed by JS (DOM based XSS) output sanitization is needed on the client side as well) What is XSS - Correct answer - Cross Site Scripting (XSS) is a type of code injection attack that enables attacker to inject client side scripts, typically JS, into web pages to be viewed by others
  • affects client side but usually harmless for server, can be very visual XSS categories - Correct answer 1. Non-persistent (Reflected)
  1. Persistent (Stored)

What is non-persistent (reflected) XSS - Correct answer - The malicious code is executed by a victim's browser, and the payload is not stored anywhere

  • It is returned as part of the response from the HTML that a server sends What is persistent (stored) XSS - Correct answer - Occurs when a web application stores user input (e.g. Comments, reviews) and later serves to others
  • The malicious code is executed by a victim's browser, and the payload is stored on the victim server
  • It is returned as part of the response from the HTML that server ends
  • The attack is relatively more dangerous as it is self-propagating, and anyone that now visits the site is at risk Best practices for xss - Correct answer 1. Take precaution when using frameworks, there might be unexpected results
  • Perform strict client side input sanitization and/or output sanitization DOM based attacks do not reach servers
  • Understand JS well and the potentially harmful actions What is sql injection - Correct answer - A subset of the an unverified/unsanitized user input vulnerability by convincing the application to run SQL code that was not intended
  • can be used to update records like password or modify data, insert fake records like login credentials, and delete records Sqli VS XSS - Correct answer - XSS is a type of computer security vulnerability typically found in Web application that enables attackers to inject client-side script into web pages viewed by other users
  • An XSS scripting vulnerability may be used by attackers to bypass access controls such as the same origin policy
  • When condition is true, a noticeable time lag is observed
  • IF ([some_condition], SLEEP(10), 0) - Correct answer - Tools for sqli - Correct answer BSQL Sqlmap Sqlninja Havi Tools to prevent sqli - Correct answer Burp proxy Sqlix HP Scrawlr HP webinspect What is logging - Correct answer - Collection and storing of data over a time period for analysis
  • Used to gain insights, resolve bugs and detect problems of an application What to log - Correct answer - timestamp/log entry
  • Timing data for request
  • Request endpoint data (eg. "/users" or "GET", "POST", "PUT", "DELETE")
  • IP of requesting party -Exceptions What is Morgan logging - Correct answer - a HTTP request logger middleware for node.js
  • Simplifies the process of logging requests to application How to use morgan - Correct answer - Install with npm install morgan -- save
  • Import library with var morgan = require('morgan') Morgan predefined tokens - Correct answer :date The current date and time in UTC :http-version The HTTP version of the request :method The HTTP method of the request

:referrer The Referrer header of the request :remote-addr The remote IP address of the request :remote-user The user authenticated as part of Basic Auth for the request :req[header] The given header of the request :res[header] The given header of the response :response-time The time between the request coming into morgan and when the response headers are written, in ms :status The status code of the response :total-time The time between the request coming into morgan and when the response has finished being written out to the connection, in ms :url The URL of the request :user-agent The contents of the User-Agent header of the request Predefined log formats - Correct answer combined: Apache standard combined format Common: Apache standard common format Dev:

Why log file rotation - Correct answer - The log file can grow to a very large size for applications hosted on the cloud

  • Need to create multiple log files
  • Make use of rotating-file-stream module (npm install rotating-file-stream --save) Log file rotation example - Correct answer var rfs = require('rotating-file- stream'); // create a rotating write stream var applogstream = rfs.createstream('access.log', { interval: '1d', // rotate daily path: path.join(__dirname, 'log') //write to a subdir log }) ... App.use(morgan("combined", { stream: applogstream})); What is a middleware - Correct answer a function that will receive the request and response objects. As a third argument you have another function that will call the next middleware function (if you have) What is a middleware chain - Correct answer a chain of functions that are called one after another, with the last function sending the response block back to the browser You must call next() (unless it is the last function in the chain) or the request will just hang there and eventually timeout - Correct answer - How to secure node js app - Correct answer - Middleware to validate input before the input is processed
  • Middleware to sanitize the output before the output is returned to client 2 Standard Controls against XSS - Correct answer 1. Validate all user controlled input including form fields, GET & POST parameters, headers, and cookies.
  • Only whitelisted characters should be allowed and special HTML characters should not be allowed
  1. Escape all strings output to the page
  • Any HTML special characters will be HTML encoded and interpreted by the browser literally rather than as HTML markup Regular expression
  • Applications frequently require text processing for features like word searches, email validation, or XML document integrity (involves pattern matching) - Correct answer - Forming Regex - Correct answer All regex starts and end with '/', then starts with "^" and end with '$' 0 Match 0 or more occurrences ? Match 0 or 1 occurrences

Match 1 or more occurrences {x} Match exactly x times {x,y} Match between x to y occurrences (inclusive) [123x] Match a single instance of any character in the bracket [0-9] Shortcut for [0123456789], often used with [a-za-Z] [^0-9] Match a single character except those specified in the brackets . Any character \d A digit (0-9) \D A non digit [^0-9] \s A whitespace character (space, tab, line break) \S A non whitespace character [^\s] \w A word character [a-za-Z_0-9] \W A non word character [^\w] XY

Validator.isurl(); What is Sanitization - Correct answer - Process of removing or replacing submitted data

  • After validation and processing, we can sanitize data to ensure output data is safe
  • The validator library provides function to sanitize data
  • Characters such as <, >, &, ', ", / should be converted to the corresponding HTML entities, so that they will not be interpreted as code like JS in XSS attacks Sanitisation example - Correct answer const validator = require('validator'); Var sanitizedoutput = validator.escape(input); // removes ASCII control characters, which are normally invisible in HTML var sanitizedoutput = validator.striplow(input); Securing Input & Output - Correct answer - Perform validation on input data
  • Perform sanitization on output data
  • Apply validation/sanitization middleware accordingly to the API routes Preventing sqli - Correct answer The approach is to 'clean' the input by escaping it such that e.g. The column's value will remain as the value when the SQL statement is run With mysql query() function, it is possible to auto escape the user inputs with placeholders represented by? When the query is run All the? Must be replaced in sequential order with values represented in an array in the same order (Parameterized query [?] Vs Dynamic query) - Correct answer example: Var sql = SELECT userid,email,username FROM user WHERE userid=? And role=?; conn.query(sql, [userid,role], function(err, result){...

Assuming a user tries to do sqli and supplies a payload like 1' or 1=1;-- - for the userid With the placeholders, the query function will escape the input from the user such that the SQL query will search for userid with the value as "1' or 1=1;-- -" which does not exist - Correct answer With placeholders, escaping which is a form of sanitization is done on the input before the query is executed on the database server Placeholders may also be provided as a key value pair in an array where the key is the column name and value is the value (duh) of the column - Correct answer example: Var sql = SELECT userid,email,username FROM user WHERE? And ?; Conn.query(sql, [userid:${userid},role:${role}], function(err, result){... What is stored prodecures - Correct answer - can restrict access to sensitive columns data if you utilize stored procedures

  • a function/method and works like an interface to specific restricted parts of the DB Example of stored procedure - Correct answer CREATE PROCEDURE finduser -- name of stored procedure (IN useridin int, IN rolein varchar(50)) -- Parameters BEGIN SELECT userid, email, username FROM user WHERE userid = useridin and role = rolein; END Calling Stored Procedures in NODE JS - Correct answer var sql=call finduser(?,?); conn.query(sql, [userid,role], function(err, result){... Best practices for preventing sqli - Correct answer - Use placeholders in mysql node library to escape inputs
  • Use stored procedures

Applying middleware authorisation - Correct answer app.get('/users', verifytoken, (req, res) => { If (!Req.decodedtoken.role !== 'admin') Return res.status(403) .send({ message: 'you dont have sufficient permissions' }); // handle processing Res.status(200).send({ users }); }); Viewing Restricted Content - Correct answer let token = localstorage.getitem('jwt_token'); Var xhr = new xmlhttprequest(); Xhr.open('GET', '/api/users', true); Xhr.setrequestheader('Authorization', Bearer ${jwt_token}); Xhr.onload = function () { If (this.readystate === xmlhttprequest.DONE) { Let response = JSON.parse(this.response); // handle response } }; Xhr.send(); Logout - Correct answer localstorage.removeitem('jwt_token'); What are Cookies - Correct answer help a web application trace visits and activity. When a user has been authenticated, a new session cookie is issued to the client, and the server will maintain some information about each client in its memory JSON web tokens vs session cookies - Correct answer jwt

  • Client retains authentication information
  • Immune to CSRF attack
  • Truly stateless REST endpoints

Session cookies

  • Both server and client retains session information
  • Vulnerable to CSRF attack
  • REST endpoints state based
  • Easy to destroy session Plaintext Communication - Correct answer HTTP (Hyper Text Transfer Protocol) packets are a standard of communicating information. This information is sent in plaintext, such that attacker listening to the network traffic may 'sniff' out information Secure Channels - Correct answer HTTPS (HTTP Secure) uses TLS (Transport Layer Protocol) security or SSL (Secure Socket Layer) to cryptographically secure text Hashing VS Encryption - Correct answer - Hashing is a one way function where data is mapped to a fixed length value
  • Hashing is primarily used for authentication
  • Salting is an additional step during hashing, typically seen in association to hashed passwords that adds an additional value to the end of the password that changes the hash value produced
  • Encryption on the other hand, is a 2 way function where information is scrambled in such a way that it can be unscrambled later Steps for Password Hashing - Correct answer 1. Generate a long random string (aka salt)
  1. Append the salt to the password
  2. Hash the string from step 2 using a strong hashing function (bcrypt)
  3. Save the salt and the hash in the user's database record Example for hashing and comparing - Correct answer // hashing bcrypt.hash(password, saltrounds, function(err, hash) { // comparing bcrypt.compare(password,hashpwd,function(err,success){ Asymmetric Encryption - Correct answer - One key encrypts, the other decrypts (priv/pub)

Session users cookies to store session id which uniquely identifies the user A session... - Correct answer - usually corresponding to one client

  • Identifies a user throughout his usage of web application
  • Stores user information (bind data to sessions)
  • Should be cleared when user logs out to prevent session fixation attacks Express-Session - Correct answer A node module to manage session activities, which will help you store data for different users, issue session id and clear session etc. Example: Var session = require('express-session'); App.use(session({ Secret: 'yoursecretkey', Store: sessionstore, // using mysql store Saveuninitialized: false, Resave: false }); Get/Set Session Values - Correct answer Get session values by calling Req.session.varname To retrieve the role of the user Var role = session.role Logging Out - Correct answer - req.session.destroy() will clear the session for the relevant user and also initiate the removal of the session id cookie at client side
  • prevents session related attacks Checking User Roles example - Correct answer // middleware to check user has logged in with admin role verifysession:function(req, res, next) { Var session = req.session If (session.role) next() Else { Res.status(403) Res.send({"Message": "Not Authorized"} }

Possible attack scenarios for csrf - Correct answer - Modifying product's information in backend

  • Change password function (if old one is not required)
  • Deleted of data in backend For a CSRF attack to be possible, 3 key conditions must be in place - Correct answer 1. A relevant action
  • There is an action within the application that the attacker has a reason to induce
  • This might be a privileged action (such as modifying permissions for other users) or any action on user-specific data (such as changing the user's own password)
  1. Cookie-based session handling
  • Performing the action involves issuing one or more HTTP requests, and the application relies solely on session cookies to identify the user who has made the requests
  • This is no other mechanism in place for tracking sessions or validating user requests
  1. No unpredictable request parameters
  • The requests that perform the action do not contain any parameters whose value the attacker cannot determine or guess
  • For example, when causing a user to change their password, the function is not vulnerable if an attacker needs to know the value of the existing password How to Prevent CSRF Attacks - Correct answer - Embed a CSRF token in the form field
  • A CSRF Token is a piece of data that is random, unique, and attached to a form (Often, this data is included in a hidden input tag within the form)
  • The token should be unpredictable Generating CSRF Tokens - Correct answer - You can implement your own middleware to generate and check your CSRF token with Node JS Crypto Library/ Csurf library