OSI seven-layer model and HTTP request
OSI: Physical layer - Data link layer - Network layer - Transport layer - Session layer - Presentation layer - Application layer
Five-layer protocol: Physical layer - Data link layer - Network layer - Transport layer - Application layer

HTTP request types:
The data of the GET request is in the URL header
The data of the POST request is in the request body
PUT updates the resource
DELETE deletes
CONNECT is reserved in the HTTP/1.1 protocol for proxy servers that can change the connection to a pipeline mode
OPTIONS describes the communication options of the target resource
TRACE echoes the requests received by the server, mainly used for testing or diagnosis
PATCH and PUT requests will replace all the content of the target resource, while PATCH requests will only modify part of the content. PATCH requests are also a new method added in HTTP/1.1.
If QQ and WeChat can be used but web pages cannot be opened, what is the problem?
It is usually a problem with the .DNS server
ping 127.0.0.1 to check if the TCP/IP protocol on the local machine is normal;
ping the local IP to check if the network card or network card driver is normal;
ping IP in the same network segment to check the working mode of the switch port and VLAN division
ping the network segment gateway to check if the host to the local network is normal;
ping public IP to check if the routing is normal;
XSS
1. Principle
XSS is a passive attack
Cross-site Scripting (XSS) refers to malicious attackers inserting malicious Script code into web pages. When users browse the page, the Script code embedded in the web page will be executed, achieving the purpose of maliciously attacking users. XSS vulnerabilities are usually caused by output functions of PHP outputting JavaScript code to the html page, which is executed by the user's local browser, so the key to XSS vulnerabilities is to find output functions with unfiltered parameters. Common output functions
HTML is a markup language for hyper-text, which distinguishes text from markup by treating certain characters specially, for example, the less than symbol (<) is considered the start of an HTML tag, the characters between <title> and </title> are the title of the page, etc. When the content inserted into a **dynamic page** contains these special characters (such as <), the user's browser may misinterpret them as HTML tags. When these HTML tags introduce a JavaScript script, these scripts will be executed in the user's browser. Therefore, when these special characters cannot be checked by the dynamic page or the check is incorrect, XSS vulnerabilities may occur.
echo printf printprint_r sprintf dievar-dump var_export
2.2. Classification
(1) Reflective Passed through the back-end without passing through the database, generally appears in message boards, user posts and replies
(2) Stored type Passed through the back-end and the database, generally appears in url, search box, and may also appear in GET, POST parameters
(3) DOM type A type of XSS based on the DOM document object model, which does not interact with the back-end server, and forms XSS vulnerabilities through the front-end dom nodes
3.3. Common XSSplaylod construction and bypass
Reflective
(1) No filtering<script>alert(1)</script>
(2) Double write bypass<sc<script>alert(1)</script>
(3) Case-insensitive bypass<ScRIpt>alert(1)</sCriPt>
(4) <img> bypass, filtered script, <><img src=https://www.freebuf.com/articles/es/1onerror=alert(1)
How to perform penetration testing on a login box
Try weak passwords
SQL injection
Observe if there is user registration or password reset
First dig web vulnerabilities, then brute force
Common logical vulnerabilities
Captcha vulnerability
Captcha reuse
Captcha bypass
Captcha echo
Automatic recognition of captcha
Unauthorized access vulnerability
Vertical unauthorized access: users can access or operate accounts with higher permissions than their own
Horizontal unauthorized access: users can access or operate accounts with the same permissions as their own
Password vulnerability
Password change vulnerability: you can change the password without verifying the old password
Password reset vulnerability: verification logic is not strict
Payment vulnerability
Modify payment amount
Unauthorized payment
Payment interface vulnerability
Common crawling libraries
requests sends HTTP requests
BeautifulSoup or lxml are used for parsing html
import requests
from bs4 import BeautifulSoup
def fetch_webpage_title(url):
"""
Fetch the title of the webpage from the specified URL
"""
try:
# Send an HTTP GET request
response = requests.get(url)
# Check if the request is successful
if response.status_code == 200:
Use BeautifulSoup to parse HTML content
soup = BeautifulSoup(response.text, 'html.parser')
# Find and return the content of the <title> tag
title = soup.title.string
return title
else:
return f"Failed to retrieve content (HTTP {response.status_code})"
except requests.RequestException as e:
return f"Network request failed: {e}"
# Example URL
url = "https://www.example.com"
# Call the function and print the result
title = fetch_webpage_title(url)
print(title)
General website penetration testing process
1. Information Collection
a. Relevant information about the server (real IP, system type, version, open ports, WAF, etc.)
b. Website fingerprint recognition (including CMS, CDN, certificate, etc.), DNS records
c. Whois information, name, record, email, phone reverse search (email to social engineering library, social engineering preparation, etc.)
e. Subdomain collection, side stations, C段, etc.
f. Google hacking for specialized search, PDF files, middleware version, weak password scanning, etc.
g. Scanning website directory structure, revealing the background, website banner, test files, backup, and other sensitive file leaks, etc.
h. Transmission protocols, general vulnerabilities, exp, GitHub source code, etc.
2. Vulnerability Mining
a. Browsing the website to see the scale, function, characteristics, etc. of the website
b. Port scanning, weak password, directory scanning, etc., and perform vulnerability detection on the corresponding ports, such as rsync, Heartbleed, MySQL, FTP, SSH weak password, etc.
c. XSS, SQL injection, upload, command injection, CSRF, cookie security detection, sensitive information, communication data transmission, brute force attack, etc.
Any file upload, unauthorized access, unauthorized access, directory traversal, file inclusion, replay attack (SMS bombing), server vulnerability detection, and finally using漏扫 tools, etc.
3. Vulnerability Exploitation & Privilege Escalation
a. MySQL privilege escalation, Serv-U privilege escalation, Oracle privilege escalation
b. Windows overflow privilege escalation
c. Linux Dirty COW, kernel vulnerability privilege escalation e
4. Clear test data and output reports
Cleaning logs and test data
Summarize and output the penetration test report, attach the repair plan
5. Retest
Verify and discover new vulnerabilities, output reports, and archive
Intrusion penetration process
1. Information Collection
Firstly, collect server asset information to understand which IPs are alive, which ports are open on the alive IPs, and the services corresponding to the ports.
Recommended tools: F-NAScan
2. Weak password detection
Among the open port services of these servers, the main services are system services, database services, and web services. It is very necessary to perform weak password detection on common port services.
Common system service weak passwords:
1. IPC$, SSH, Telnet, etc. weak passwords, basically equal to obtaining system permissions
2. MSSQL database SA weak password can directly call stored procedures to execute system commands
3. mysql database root weak password, can try udf direct privilege escalation, the first key step of mysql5.1 and above versions is whether to create the plugin directory, by default it generally does not exist.
Weak password -- privilege escalation -- read cached password
Common Web application port services:
1. WebLogic Default port: 7001 Weak password, console background deployment webshell Java deserialization
2. Tomcat Default port: 8080 Weak password, manager background deployment WAR package upload
3. jboss Default port: 8080 Weak password, unauthorized access, Java deserialization
Taking the open Tomcat service of a certain system as an example, its IP address is 192.1.33.133:8080. Through the weak password detection of iscan, it was found that Tomcat has a weak password, and the Tomcat console can be successfully logged in directly using the weak password, as shown in the figure.
NAT protocol
Address multiplexing: Share a public IP
Address hiding: External networks can only see the public IP of the NAT device, but cannot directly see the private IP addresses accessing the internal network
Simplify network management
Load balancing
Transparent proxy
ARP protocol and ARP spoofing
The ARP protocol's role is to convert IP addresses to MAC addresses
ARP欺骗原理
The attacker sends forged ARP packets so that the victim's computer mistakenly considers the attacker's MAC address as the gateway or target host's MAC address. As a result, all data packets that should have been sent to the target host or gateway will be forwarded to the attacker's computer, thereby achieving malicious behaviors such as data theft, tampering, or impersonation.
General steps
Scan the networkThe attacker first scans the IP addresses and MAC addresses in the network to understand the network topology and device information.
Construct forged ARP packetsThe attacker constructs forged ARP packets based on the scanning results. These packets contain the IP addresses of other devices in the network and the attacker's own MAC address.
Send forged ARP packetsThe attacker sends forged ARP packets to the network, broadcasting or unicasting them to the target device or gateway.
Update ARP cacheUpon receiving forged ARP packets, the target device or gateway will update its ARP cache table, associating the attacker's MAC address with the target IP address.
Capture data packets: After that, when the target device or gateway sends data packets, they will send the data packets to the attacker's computer according to the updated ARP cache table, instead of the actual target device or gateway.
Preventive measures
Use static ARP cache: Add the IP address and MAC address of the target host to the static ARP cache to prevent the ARP cache from being maliciously modified.
IP and MAC address binding: Configure the binding of IP and MAC addresses on network devices such as routers and switches to ensure that data packets can only be sent to the specified MAC address.
Use ARP defense tools: Deploy defense tools such as ARP firewalls to monitor and prevent ARP spoofing attacks in real time.
Regularly update and patch the system: Timely update the security patches of the operating system and applications, and patch known vulnerabilities.
Use encrypted protocols: Use encrypted protocols such as HTTPS, SSL/TLS to protect the transmitted data and prevent data from being intercepted or tampered with.
IP protocol
Connectionless and unreliable
ipv6
ipv4
TCP protocol
Connection-oriented, byte stream-oriented, reliable, protocol number 6, transport layer
TCP is suitable for application scenarios that require high data integrity, such as HTTP, FTP, SMTP protocols, and services that require reliable transmission, such as file transfer and web browsing.
Message Format
PSH, RST, SYN, FIN.
URG: This flag indicates that the TCP urgent pointer field (to be discussed later) is valid, used to ensure that the TCP connection is not interrupted and to urge intermediate layer devices to process these data as soon as possible;
ACK: This flag indicates that the acknowledgment field is valid, that is, the TCP acknowledgment number mentioned earlier will be included in the TCP data packet; there are two values: 0 and 1. When it is 1, the acknowledgment field is valid, otherwise it is 0;
PSH: This flag represents the Push operation. The Push operation refers to sending the data packet to the application immediately after it arrives at the receiving end, rather than queuing it in the buffer;
RST: This flag indicates a connection reset request. It is used to reset connections that have generated errors and is also used to reject erroneous and illegal data packets;
SYN: It represents the synchronization number, used to establish a connection. The SYN flag and ACK flag are used together. When a connection request is made, SYN=1, ACK=0; when the connection is responded to, SYN=1, ACK=1; this flag of the data packet is often used for port scanning. The scanner sends a data packet with only SYN, and if the other host responds with a data packet, it indicates that this host has this port; however, since this scanning method only performs the first handshake of the TCP three-way handshake, this successful scan indicates that the scanned machine is not very secure, and a secure host will require a strict TCP three-way handshake for a connection.
Three-way handshake
The first handshake: Establishing a connection. The client sends a connection request segment, with the SYN bit set to 1 and the Sequence Number set to x; then, the client enters the SYN_SEND state, waiting for the server's confirmation. (The client establishes a connection and waits for confirmation)
The second handshake: The server receives the SYN segment. The server receives the SYN segment from the client and needs to acknowledge it, setting the Acknowledgment Number to x+1 (Sequence Number + 1); at the same time, it also needs to send a SYN request message, with the SYN bit set to 1 and the Sequence Number set to y. The server puts all the above information into a segment (i.e., the SYN+ACK segment) and sends it to the client at once, at this time, the server enters the SYN_RECV state. (The server sends relevant segment information and waits for the connection)
The third handshake: The client receives the SYN+ACK segment from the server. Then, it sets the Acknowledgment Number to y+1 and sends an ACK segment to the server. After this segment is sent, both the client and the server enter the ESTABLISHED state, completing the TCP three-way handshake. (The client receives information from the server and establishes a connection)
Then data transmission can be performed
Four handshakes
The first分手:Host 1 (can be either the client or the server), sets the Sequence Number and Acknowledgment Number, and sends a FIN segment to Host 2; at this time, Host 1 enters the FIN_WAIT_1 state; this indicates that Host 1 has no data to send to Host 2. (One party has completed data transmission)
The second分手:Host 2 receives the FIN segment sent by Host 1, sends an ACK segment back to Host 1, with the Acknowledgment Number being Sequence Number + 1; Host 1 enters the FIN_WAIT_2 state; Host 2 informs Host 1 that it has no data to send and can proceed to close the connection. (The other party has completed data transmission)
The third分手:Host 2 sends a FIN segment to Host 1 to request closing the connection, and at the same time, Host 2 enters the CLOSE_WAIT state. (Request to close the connection and wait)
The fourth分手:Host 1 receives the FIN segment sent by Host 2, sends an ACK segment to Host 2, and then Host 1 enters the TIME_WAIT state; after Host 2 receives the ACK segment from Host 1, it closes the connection; at this time, if Host 1 still does not receive a reply after waiting for 2MSL, it proves that the Server end has closed normally, so Host 1 can also close the connection. (Close the connection)
UDP
Connectionless, unreliable, packet-oriented, protocol number 17
Connectionless means: UDP transmission knows the corresponding IP and port number and can directly transmit without the need to establish a connection.
UDP has only a receiving buffer, no sending buffer
Cannot transmit large data
Message Format
TCPUDP Difference
Characteristics TCP UDP
Connection-Oriented/Connectionless Connection-Oriented Connectionless
Reliability Provides reliable data transmission services Does not provide reliability guarantees
Flow Control and Congestion Control Yes No
Byte Stream-Oriented/Packet-Oriented Byte Stream-Oriented Packet-Oriented
Transmission Speed Relatively slow (due to the need for confirmation and retransmission mechanisms) Relatively fast (due to the absence of confirmation and retransmission mechanisms)
Applicable Scenarios Applications with high requirements for data integrity (such as HTTP, FTP, SMTP, etc.) Applications with high requirements for real-time performance (such as VoIP, video conferencing, online games, etc.)
DNS Protocol
UDP53
Domain Name Resolution Service
Windows Path C:\Windows\System32\drivers\etc\hosts
Linux Path /etc/hosts
Parsing Method Iterative Recursive
PKI
Public Key Infrastructure
PKI is a security framework and architecture used to establish, manage, and distribute public keys, and provide secure and reliable communication and data transmission. It is a widely used encryption technology framework based on asymmetric encryption algorithms, which implements authentication and trust through digital certificates and certificate authorities (Certificate Authority, CA).
(1) Authentication: Your envelope will be attached with your identity information, so the recipient can confirm that you are the legitimate sender. (Similarly, PKI provides digital certificates issued by CA institutions for participants in communication to prove the credibility of their identity.)
(2) Encrypted Communication: The post office will encrypt the letter in your envelope, so only the recipient can open it. (Using asymmetric encryption algorithms with PKI, the data in communication will also be encrypted, and only the legitimate recipient can decrypt the content.)
(3) Digital Signature: The post office will stamp your name on the envelope, and verify your authenticity at the recipient's end. (Using digital signatures with PKI, communication data can be signed to ensure that the communication content has not been tampered with during transmission.)
Deserialization Vulnerability
1. Serialization and Deserialization Process
Serialization: The process of converting an object into a byte stream, so that it can be saved to a file, database, or transmitted over a network.
Deserialization: The process of reconstructing the original object from the byte stream.
2. Reason for Vulnerability
When an application deserializes data from an untrusted source, if there are no appropriate validation and security measures, attackers can manipulate these data to execute malicious code.
Trust external inputs: The application blindly trusts external input data for deserialization.
Lack of input validation: Lack of strict validation and cleaning of deserialized data.
Use insecure libraries or methods: Use serialization/deserialization libraries that have known vulnerabilities.
Deserialization vulnerability exploitation methods
1. Execute remote code
Through remote object serialization, attackers can execute remote code on the local computer.
2. Scan ports
Attackers can use this vulnerability to scan for ports of other systems and services that the application depends on.
3. Add malicious queries to the database
Attackers can change the state of the database by adding controlled queries to the session.
4. Modify access control
Attackers can change access control strategies by modifying the authorization and authentication of the application.
Specific exploitation methods (take PHP as an example)
__wakeup() bypass: In PHP, if the value representing the number of object properties during deserialization is greater than the actual number of properties, the execution of the __wakeup() method is skipped. Attackers can exploit this to bypass certain security restrictions.
Session vulnerability: PHP sessions are stored after serialization and deserialized during reading. If session data is not properly protected, attackers can inject malicious data into the session and execute malicious code during the user's next session.
PHAR exploitation: PHAR is a packaging file similar to JAR in PHP, which is enabled by default in PHP 5.3 or higher versions. Attackers can create PHAR files containing malicious code and execute these codes on the target system through deserialization vulnerabilities.
Defensive measures
Avoid using insecure serialization methods: Use more secure serialization methods, such as JSON or XML, which are not easily susceptible to such attacks.
Input validation: Conduct strict input validation on deserialized data to ensure data security.
Use whitelist: Only allow specific classes to be deserialized to avoid processing any unauthorized classes.
Minimize usage: Try to minimize the use of serialization and deserialization to reduce vulnerability risks.
Minimize permissions: Ensure that the application runs with the minimum necessary permissions to limit the damage that malicious code may cause.
Code audit: Conduct security audits on code to find and fix potential deserialization issues.
Use secure configuration: Use secure configuration options to limit deserialization operations.
Common vulnerabilities: shiro deserialization, weblogic deserialization vulnerability
LINUX user password storage location
/etc/passwd and /etc/shadow
Common penetration testing tools
Burpsuite: Used for packet capture and modification operations on requests, which can further test front-end parameters, such as testing logic vulnerabilities, brute-forcing weak passwords, and finding page parameter passing points, etc.
Sqlmap: Can detect or inject the background database of the site as a relational database, and can also access the file system. You can use -file-read 'xxx.txt' to read the xxx.txt file in the target directory, and you can also use -os-cmd to execute operating system commands, -os-shell to use an interactive operating system shell. It is very powerful, and its rich tamper provides great help for bypassing some WAFs. Of course, in most cases, manual judgment of WAF rules is still necessary.
Yujian: A very excellent target scanning tool. In a real scenario, I obtained the opponent's database file through Yujian scanning, saw the database IP, port, and account password, directly connected to the database, and all the information I wanted was presented in front of me.
Mimikatz: Capture the plaintext passwords of all users in the current system. When escalating privileges, you may use Owasp Zap/AWVS: vulnerability scanning tools. I don't like to use vulnerability scanning tools much. Using vulnerability scanning without understanding the situation of the opponent may lead to IP being banned. And I have participated in some crowdsourced projects, where many white hats use vulnerability scanning to scan the target疯狂, causing the target to have problems with normal access, a bit of a dislike for these operations. But vulnerability scanning tools can also give us a general understanding of the target's information, such as paths, possible vulnerabilities, etc., so as not to miss any points.
Nmap/masscan: Target open service scanning, vulnerability port scanning, operating system identification, belongs to information collection. If -p specifies the port, -sV identifies the service version, -O identifies the operating system, -sS (implicit scanning without establishing a three-way handshake), sT (TCP scanning, information relatively accurate), for sites that are disabled for ping, you can use -Pn, etc. In addition, the powerful scripts of nmap can also provide multiple ways, such as dos (which may cause denial of service), exploit (detect security vulnerabilities). Compared to masscan, which is faster and more effective (in my opinion), the two can be used together, with masscan quickly scanning out ports and nmap identifying services through these ports.
HTTP protocol
80
1. Simple and fast: When a client requests a service from the server, only the request method and path need to be transmitted. Common request methods include **GET, HEAD, POST**. Each method specifies a different type of contact between the client and the server. Due to the simplicity of the HTTP protocol, the program size of the HTTP server is small, making the communication speed very fast.
2. Flexible: HTTP allows the transmission of any type of data object. The type of data being transmitted is marked by Content-Type.
3. No connection: The meaning of no connection is to limit each connection to handle only one request. After the server processes the customer's request and receives the customer's response, the connection is disconnected. This method can save transmission time.
4.无状态:HTTP协议是无状态协议。无状态是指协议对于事务处理没有记忆能力。缺少状态意味着如果后续处理需要前面的信息,则它必须重传,这样可能导致每次连接传送的数据量增大。另一方面,在服务器不需要先前信息时它的应答就较快。
4. Stateless: The HTTP protocol is a stateless protocol. Stateless means that the protocol has no memory of transaction processing. The lack of state means that if subsequent processing needs information from before, it must be resent, which may result in an increase in the amount of data transmitted with each connection. On the other hand, the response is faster when the server does not need previous information.
5. Support B/S and C/S modes.
Fields: host, referer, orgin, content-type, accept-lnguage, accept-encoding, connection, if-modified-since, cookie, xff, user-agent, request method, ...
Referer is the URL you want to visit, xff is where you come from, showing the IP address, referer also shows where you come from, showing the URL.
xff is the HTTP request header field that tells the server the final IP of the current requestor
It is usually possible to forge the final IP of the request by directly modifying the X-Forwarded-For field in the http header
Referer is used to tell the server which URL address the current visitor jumps to, just like xff, referer can also be modified directly
HTTPS
443 Encryption, SSL/TLS
The working principle of HTTPS mainly includes the following steps:
Establishing an SSL Connection: The client accesses the server through the HTTPS URL and requests to establish an SSL connection with the server.
Certificate Verification: The server sends the website's SSL certificate (including the public key) to the client, and the client verifies the validity of the certificate.
Key Exchange: The client and server exchange key information using public key encryption technology to generate a session key.
Encrypted Communication: Use session keys to encrypt communication data between the client and server, ensuring the security of data transmission.
OWAS TOP10 2023
1. Object Level Authorization Failure (Horizontal Privilege)
2. Invalid Authentication
3. Object Attribute Level Authorization Failure
4. Unrestricted Resource Consumption, DDoS
5. Functional Authorization Failure (Vertical Privilege)
6. Unrestricted Access to Sensitive Business Flows, Brute Force, and Spiders
SSRF
Cause of SSRF Vulnerability:
(1) The server provides the function of obtaining data from other server applications;
(2) The server filters and restricts the target address.
Attack Target: Generally, the target of SSRF attacks is the internal system that is inaccessible from the external network (since the request is initiated by the server, the server can request systems connected to itself but isolated from the external network).
Port Scanning (Scanning Internal Network)
Fingerprint identification and vulnerabilities in attacking web applications, tools: whatweb; wafw00f
8. Security Configuration Errors
9. Poor Inventory Management
10. Insecure API Usage
WAF
Web Application Firewall
WAF can filter and monitor the traffic of web applications to identify and block potential security threats. WAF can detect various attacks in web applications, such as SQL injection, cross-site scripting attacks (XSS), cross-site request forgery (CSRF), and take appropriate measures, such as intercepting requests, blocking access, and recording events.
The working principle of WAF usually includes the following steps:
Traffic Identification: WAF identifies requests from clients and analyzes them. WAF can check request headers, request bodies, Cookies, URL parameters, and identify attacks within them.
Attack Detection: WAF performs attack detection on identified requests. WAF can use various technologies to detect attacks, such as regular expressions, feature matching, and behavior analysis. WAF can detect various attacks, including SQL injection, XSS, CSRF, command injection, etc.
Attack Response: WAF takes appropriate measures based on detection results, such as intercepting requests, blocking access, and recording events. WAF can use various technologies to respond to attacks, such as redirection, error reporting, and interception.
Log Recording: WAF records all details of requests and responses, including request headers, request bodies, response headers, and response bodies. WAF can send logs to a central log management system for analysis and auditing.
IDS and IPS
IDS Intrusion Detection System is passive; it monitors network or system resources to find behaviors that violate security policies or attacks
IPS Intrusion Prevention System is proactive; by directly embedding into network traffic, it uses a network port to receive external traffic, checks and confirms that it does not contain abnormal activities or suspicious content, and then forwards it to the internal system through another port (which is actually cleaning malicious traffic).
IDS Basic Principles:
1. IDS is divided into real-time intrusion detection and post-intrusion detection:
#1 Real-time intrusion detection: Performed during the network connection process, immediately disconnects the current connection upon detecting intrusion signs, and collects evidence and implements data recovery.
#2 Post-intrusion detection: Detected by security personnel.
2. Intrusion Detection Classification:
#1 Network-based: Captures data packets through sites connected to the network to analyze whether they have known attack patterns.
#2 Host-based: Detects suspicious activities by analyzing system audit data, such as changes in memory and files; input data must come from system logs.
3. Intrusion Detection Techniques:
#1 Information Collection: Abnormal changes in system logs, directories, and files, abnormal behaviors during program execution, and physical intrusion information
#2 Data Analysis:
IPS basic principle:
1, IPS has a large number of filters that can prevent various attacks; IPS checks 2-7 layers, checking each byte one by one.
2, IPS classification:
#1 Host-based Intrusion Prevention System (HIPS): Prevents network attacks from入侵ing the operating system and applications by installing software agents on the host/server.
#2 Network-based Intrusion Prevention System (NIPS): Provides security protection for network systems by detecting network traffic.
Firewall
Functions
Zone isolation, access control, routing exchange, VPN, attack protection, logging
CSRF
Principle
Cross-site Request Forgery is an attack where the attacker deceives the user's browser to visit a previously authenticated site and perform some operations (such as sending emails, sending messages, or even property operations such as transferring money and purchasing goods). Because the browser has been authenticated before, the visited site will think that this is a real user operation and execute it.
Common means of defense against CSRF
Many modern applications include CSRF tokens in requests to defend against such attacks. You can check the following aspects:
Token verification: Check whether all requests to modify user data include CSRF tokens. Typically, CSRF tokens are randomly generated values that are included in the request (usually in the request header or body).
in the HTML form.
Hidden field in the form: Look for the existence of
**csrf\_token**such hidden fields.
Token in the request header: Some applications use custom request headers (such as
**X-CSRF-Token**)to pass CSRF tokens.
**SameSite**
attribute: Set for Cookies**SameSite**
attributes to limit the ability of cross-site requests.Verify the Referer header: Check the Referer header in the HTTP request to ensure that the request comes from a trusted page.
After understanding the principle and defense mentioned above, you can test it
If you suspect that a feature point may have a CSRF vulnerability and no defense has been implemented, you can perform the following tests:
Perform modification operations, capture packets, and use bp to generate a poc to forge requests (transfer the captured packets from BP to Repeater, then in the Repeater interface, right-click -> Engagement tools -> Generate CSRF POC to generate POC). This page can include requests for the target application, and try different request methods (such asPOST
、GET
)to verify whether the operation can be executed successfully.
Consider for a moment, how do hackers' websites utilize the cookies of logged-in users in CSRF attacks? Isn't there a same-origin policy restriction?
the server will set one or more Cookies in the user's browser, which are usually used to maintain the user's session state, such as
https://example.com
When a user logs into a website (such assession_id
.The browser will store these Cookies locally and attach them to subsequent requests for
https://example.com
These Cookies will be automatically attached to the requests.This is the default behavior of the browser, used for session management between a user and a specific website.
When a user visits a malicious website while logged in (such as
http://malicious.com
). The malicious website can include malicious requests (such as hidden forms or JavaScript) on its page, pointing to the target website (https://example.com
).When a malicious website initiates such a request, the browser will automatically send the Cookies related to the target website (such as
session_id
) to be attached to this request.Cross-site Cookies: Cookies are isolated by domain, which means
http://malicious.com
Cannot be accessed directlyhttps://example.com
However, the browser will automatically handle Cookies related to the request. Therefore, malicious websites cannot directly view or extract Cookies, but will automatically attach the matching Cookies to the request.Domain restriction of Cookies: The domain attribute of Cookies determines which domains can access the Cookie. Although Cookies cannot be read across sites, they are automatically sent to the matching domain with the request. (This mainly refers to cross-domain resources, where the samesite attribute determines which resources carry cookies and which do not. The essence is the difference between resources such as (a img).
How to get shell through SQL injection
1. into outfile
Utilization conditions
1. Prerequisites
The web directory has write permission and can use single quotes
Know the absolute path of the website (either the root directory or any subdirectory below the root directory is fine)
secure_file_priv does not have a specific value (check in mysql/my.ini)
2. secure_file_priv
secure_file_priv is one of the MySQL server system variables, used to limit the file system paths that can be accessed by the load data infile, SELECT ... INTO OUTFILE, and LOAD_FILE() functions. The purpose of this variable is to enhance the security of the database server by restricting the file locations that these functions can access, thereby preventing potential malicious file access or data leakage.
The default value of secure_file_priv is empty (""), indicating that these functions are not restricted and can read and write files in any path on the server.
If secure_file_priv is set to a specific directory (such as /var/lib/mysql-files/), then the LOAD DATA INFILE, SELECT ... INTO OUTFILE, and LOAD_FILE() functions can only access or write files in that directory.
If secure_file_priv is set to 'NULL', these functions will be disabled
View secure_file_priv
show global variables like '%secure%';
Set secure_file_priv
Set in the mysql configuration file:
[mysqld]
secure_file_priv='';
Runtime settings:
SET GLOBAL secure_file_priv='';
Write a one-line Trojan horse
Secondly, --os-shell
--os--shell is a parameter in SQLmap, used to execute operating system commands and obtain their output after successfully injecting the database.
Principle
Relying on the database SQL injection vulnerability and the file operation function of the database, use statements like into...outfile or similar to write malicious code to the file system of the server. Generally, two files are written to the server, one that can directly execute system commands, and one for uploading files.
Specifically, SQLMap will perform the following steps:
Inject SQL statements: SQLMap first injects an SQL statement through a SQL injection vulnerability, which uses INTO OUTFILE or other file writing functions to create a PHP file on the server. This file usually contains code for uploading and executing other files.
Upload execution file: Through the PHP file created in the first step, SQLMap can upload another PHP file to the server. This new file contains code to execute operating system commands.
Execute the command: Once a file containing command execution code is uploaded, SQLMap can trigger the file through an HTTP request, execute operating system commands, and obtain the output of the command.
Prerequisite
Prerequisite: To check if the current website connection account to the database is a DBA such as root in the mysql user table, use --is-dba. If it is, then it is a DBA.
secure_file_priv does not have a specific value
Know the absolute path of the website

评论已关闭