How to Become a Great Script Kid Diary - 0x001-JAVA Code Audit Top half (2023829-...

How to Become an Awesome Script Kid - Diary of a Script Kid

·0x001-JAVA code audit Top half (2023/8/29-2023/9/1)

此记录是在拥有一定的java基础下进行的,java基础类,反射,继承,filter,servlet,calssLoader,Dynamic agent等基础知识点将不再进行阐述,TopHalf主要集中描述除了java反序列化之外的基础漏洞,BottomHalf会集中描述java反序列化,CC/CB,weblogic,fastjson反序列化等各种反序列化审计和kWAF/绕过的姿势

·JAVA auditing from 0 to knowing everything

· Inject

·SQL-Inject The cliche SQL injection

What causes injection:

1. Improper splicing of classic sql statements

String sql_command="select * from db_name where id = " + req.getParamenter("id") // inject on id

1.1. Splicing of Statement

String sql_command ="select * from db_name where id = " + req.getParamenter("id");
try{
Statement st = con.createStatement(); // inject on id
ResultSet rs = st.executeQuery(sql_command);
while (rs.next()){
out....... // rs.getObject("id");
}
}

1.2. Improper splicing with prepareStatement precompilation

String sql_command ="select * from db_name where id = " + req.getParamenter("id");
try{
	PreparedStatement pstt = con.prepareStatement(sql_command);
	ResultSet rs = pstt.executeQuery(); //Inject on id 
	while(rs.next()){
		out ....... // rs.getObkect("id");
		}
}catch (SqlException throables) {
throables.printStackTrace();
}

2. Improper use of frameworks

Such as MyBatis, Hibernate

2.1 Injection caused by improper use of MyBaits ${parameter}

<select id ="getUsername" resultType = "com.sqltest.bean.user">
select * from user where name = ${name} //inject on name
</select>

2.2 Improper use of HQL parameter syntax

List user = session.createQuery("from user where name= '" + req.getParament("insert") + "'",User.class).getResultList(); //inject on insert 

So how to audit SQL-Inject in java?

Track the keywords sql sql_command sql_query to find the entry point of sql splicing

Track the sql chain to find the entry point of sql splicing

Look for con.prepareStatement, req.getParamenter, st.executeQuery, pstt.executeQuery and other backtracking construction chains


·command-Inject

The common situation of command injection is basically directly splicing exec to cause command injection.

String Cmd = req.getParament("cmd");
Process process = Runtime.getRuntime().exec(Cmd);

Command injection pitfalls that need attention

1.1 Interception of whitespace characters by StringTokenizer in Runtime.exec causes command injection to fail

ping 127.0.0.1&whoami
```
String[1] = "ping"
String[2] = "127.0.0.1&whoami"

```

It can be seen that the interception of blank characters by StringTokenizer in Runtime.exec causes String[2] to become the subsequent parameter of ping instead of the command to continue execution, causing the command injection to fail.

Of course, you can use multiple space splicing parameters to bypass

ping 127.0.0.1 & whoami
```
String[1] = "ping"
String[2] = "127.0.0.1"
String[3] = "&"
String[4] = "whoami"
```

·code-Inject

·EL-Inject

expression injection

EL expressions can obtain data from the four major scopes of JSP: page/request/session/application

You can perform some basic relational operations, logical operations and arithmetic operations in JSP pages

Common objects for web development can be obtained

Can call java methods, allowing developers to customize EL functions to call java methods in custom JSPs

The four major scopes of JSP are as follows:

page:only save data on one page [Javax.servlet.jsp.PageContext]

request:only save data on one request [ Javax.servlent.httpServletRequest]

session:save data on one dialogue , only support to one user [Javx.servlet.http.HttpSesssion]

application:save data in hole server and all user shared [Javax.servlet.ServletContext]

EL uses {} in JSP to represent EL expressions such as ${name} to obtain the name variable. When no scope is specified, the default search is in the scope of the page.

<@page contentType="text/html;charset=UTF-8" language="Java" %>
<html>
<center>
<h3>name is : ${param.name} </h3>
</center>
<html>

EL expression injection in Springboot

Spring Expression Language (SpEl for short) is a powerful expression language that supports querying and manipulating runtime object navigation graphs. Its syntax is similar to traditional EL, but provides additional features, the most outstanding of which are function calls and simple characters String template function.

SpEL uses #{…} as delimiters. All characters in curly brackets will be considered as SpEL expressions, in which we can use operators, variables and reference beans, properties and methods such as:

1. Reference other objects: #{car} Reference attributes of other objects: #{car.brand} Call other methods, and you can also chain operations: #{car.toString()}

The property name reference can also use symbols such as: {someProperty}

In addition, in SpEL, using the T() operator will call methods and constants of the class scope. For example, using Java's Math class in SpEL, we can use the T() operator like the following example: #{ T(java.lang.Math)} 1 #{T(java.lang.Math)}

The result of the T() operator will return a java.lang.Math class object.

The vulnerability form is similar to command injection, so this vulnerability was previously classified as command injection.

@RequestMapping("/test")
    @ResponseBody
    public String test(String input){
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(input);
        return expression.getValue().toString();
    }

The input parameters are directly used as parameters for expression parsing, which will cause command execution during the parsing process.

http://127.0.0.1:8080/test?input=new%20java.lang.ProcessBuilder(%22/Applications/Calculator.app/Contents/MacOS/Calculator%22).start()

Of course, you can also use T() to call a static method of a class, which will return a Class Object, and then call the corresponding method or property, which can also achieve the same function.


·SSTI

freemark template injection

The cause is still unfiltered template rendering, a truth

Freemarker.template.utility.Execute needs to be searched carefully, or the entry position can be deduced based on the call chain.

From version 2.3.17 onwards, the official version provides three TemplateClassResolvers to parse classes:

1. UNRESTRICTED_RESOLVER: ClassUtil.forName(className)Any class can be obtained.

2. SAFER_RESOLVER: These three classes cannot be loaded freemarker.template.utility.JythonRuntime. 3. ALLOWS_NOTHING_RESOLVER: No classes can be parsed. It can be set through methods to limit the parsing of these three classes through functions .freemarker.template.utility.Executefreemarker.template.utility.ObjectConstructorfreemarker.core.Configurable#setNewBuiltinClassResolverTemplateClassResolvernew()freemarker.template.utility.JythonRuntimefreemarker.template.utility.Executefreemarker.template.utility.ObjectConstructor

But we still don’t rule out the possibility of bypass (I may look at the code later)


·Invalid authentication
·This part mainly focuses on JWT authentication. The part about JWT is not difficult, so the description is simplified.

The basic audit method is to reverse the create method of cookieORsession and then combine it with the jwt decryption that has been obtained (decrypting a lot of websites) and then exceed the authority.


· XXE

XXE (XML External Entity), when processing unsafe external entity data, the vulnerability may cause malicious behavior to read arbitrary files, detect intranet ports, attack intranet websites, and launch DoS denial of service attacks. , issues such as executing system commands. Simply put, if the system can receive and parse the user's XML, but DTD and Entity are not disabled, XXE vulnerabilities may occur. Common scenarios include PDF online parsing, word online parsing, customized protocols, or other API interfaces that can parse XML.

The vulnerability points that are more likely to occur are as follows:

javax.xml.parsers.DocumentBuilder
javax.xml.parsers.DocumentBuildFactory
org.xml.sax.EntityResolver
org.dom4j.*
javax.xml.parsers.SAXParser
javax.xml.parsers.SAXParserFactory
TransformerFactory
SAXReader
DocumentHelper
SAXBuilder
SAXParserFactory
XMLReaderFactory
XMLInputFactory
SchemaFactory
DocumentBuilderFactoryImpl
SAXTransformerFactory
DocumentBuilderFactoryImpl
XMLReader
Xerces: DOMParser, DOMParserImpl, SAXParser, XMLParser
·XML

XML (eXtensible Markup Language) is called an extensible markup language, and all tags can be customized. Usually xml is used for recording and transmitting information, so xml is often used for configuration files.

<?xml version="1.0" encoding="UTF-8"?>
</source1>
<source id="1"> 
<name>asd</name>
</source1>
·TDT

DTD (Document Type Definition), DTD is used to constrain the document format of xml and ensure that xml is a valid xml. DTD can be divided into internal DTD and external DTD.

·Internal TDT, just give an example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE scores [
        <!ELEMENT scores (student*) >
        <!ELEMENT student (name, course, score)>
        <!ATTLIST student id CDATA #REQUIRED>
        <!ELEMENT name (#PCDATA)>
        <!ELEMENT course (#PCDATA)>
        <!ELEMENT score (#PCDATA)>
        ]>
<scores>
    <student id="1">
        <name>张三</name>
        <course>java</course>
        <score>90</score>
    </student>
    <student id="2">
        <name>李四</name>
        <course>xml</course>
        <score>99</score>
    </student>
</scores>
·External TDT
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE scores SYSTEM "scores.dtd" >
<scores>
//中间部分省略
</scores>

I won’t go into the usage method with/without echo. The SSRF set + dnslog/server set can be directly moved over and used. I searched a lot online and found nothing to talk about.


·Leakage of sensitive information

User permissions were not verified when outputting data (also considered improper permission control in disguise)

A very simple example (copied because it’s so classic)

public static void show(boolean bAjax, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* 38 */     PMInterface pm = null;
/*    */     
/* 40 */     StringBuffer sb = new StringBuffer();
/*    */     
/* 42 */     for (int i = 0; i < alPM.size(); i++) {
/* 43 */       pm = alPM.get(i);
/* 44 */       sb.append(pm.PM());
/*    */       
/* 46 */       sb.append("\r\n");
/*    */     } 
/*    */ 
/*    */     
/* 50 */     String str = sb.toString();
/* 51 */     response.getOutputStream().write(str.getBytes(SysConts.New_InCharSet));
/*    */   }
/*    */ }

·Invalid access control

·The horizontal/vertical override plan will be described in the subsequent actual audit. Override should be seen more clearly in combination with the code. The cause is basically that the user identity is not verified. The focus of the audit is also to focus on the http parameter transmission structure. Chain and pom.xml can process the incoming data.

·CSRF

·Lack of strict control over referer leads to CSRF

The following is a link to getReferer > check referer “www.example.com”

public class RefererInterceptor extends HandlerInterceptorAdapter {
	private Bollen check = true;
	@override
  public bollen preHandle(HttpServlentRequest req),
  HttpServlentRequest resp, Object handler) throws Exception{
    if(!check){
      return true;
    }
  String referer=request.getHeader("Referer");
    if((referer!=null)&&(referer.trim().startsWith("www.example.com"))){
      chain.doFilter(request, response);
    }else {
      request.getRequestDispatcher("index.jsp").forward(request,response);
    }
}
·Token reusability leads to CSRF

It is still a step in making Token (generateToken()) > If it is not deleted, if it causes the Token to leak, the Token can be reused directly.

String sToken = generateToken();
String pToken = req.getPrameter("csrf-token");
if(sToken!=null && pToken !=null && sToken.equals(pToken)){
  chain.doFilter(request,response)
}else{
  request.getRequestDispatcher("index.jsp").forward(request,response);
}	

·SSRF

Sensitive functions that need attention

HttpClient.execute()
HttpClitne.executeMethod()
HttpURLConnection.connect()
HttpUrlConnection.getInputStream()
URL.openStream()
HttpServerRequest()
BasicHttpEntityEnclosingRequest()
DefaultBHttpClientConnection()
BasicHttpRequest()

The idea of ​​auditing is basically to look for the interface point of the following function to see if the interface point can be used to call back the intranet resources. The example here will be described in the subsequent audit practice combination boxing. In fact, from the perspective of audit + practice, it is blind typing. Network survival information and reading intranet files are common methods.

I won’t go into details here about how SSRF can penetrate the intranet, survive, and read files. There are a lot of things to infiltrate.


·File operations

·File contains
<%@include file="test.jsp"%> //静态包含
<jsp:include page="<%=file%>"></jsp:include>
<jsp:include page ="<%=file%>"/>  //动态包含

Let's take a look at the first form. This form is a bit more complicated than static inclusion, because in static inclusion it only belongs to one include directive element and has only one attribute of file. Just write the path. The path can be It can be a relative path or an absolute path, but it cannot be a <%=...%>representative expression, but here, the file attribute can be <%=...%>a representative expression.

The second form is actually not essentially different from the first form. Like the core library, <c:import>it <jsp:include>is also a request-time operation. Its purpose is to insert the contents of some other Web resources into the current JSP page. These Web resources are specified through the url attribute, which is also <c:import>the only required attribute. It is worth mentioning that relative URLs are allowed here, and this relative URL is parsed based on the URL of the current page.

For example, if the URL address of our current page is http://127.0.0.1/admin/index.jsp, then if the URL attribute value we refer to is /user/edit.jsp, then in fact, the final resolved URL ishttp://127.0.0.1/admin/user/edit.jsp

So, if the value of the url attribute starts with a slash, then it is interpreted as an absolute URL within the local JSP container . If no contextvalue is specified for the property, then such an absolute URL is assumed to refer to a resource within the current servlet context. If contextthe context is specified explicitly through the attribute, the absolute (local) URL is resolved based on the specified servlet context.

Of course, <c:import>operations are not limited to accessing local content, but can also be full URIs for specific protocols and hostnames. And in fact, the protocol isn't even limited to HTTP. <c:import>The url attribute value can use java.net.URLany protocol supported by the class (that is http, https, ftp, file, jar, mailto, netdoc).

Due to these characteristics, dynamic inclusion may cause file inclusion vulnerabilities , but this kind of inclusion is very different from inclusion in PHP. For Java's local file inclusion, the harm caused is only file reading or downloading, 一般情况下not Causing command execution or code execution . Because under normal circumstances, the inclusion of files in Java does not treat non-jsp files as Java code to execute. If the JSP file is a one-sentence Trojan horse file, we can directly access and use it, and there is no need to include it for use. , unless in some special scenarios, such as insufficient permissions in some directories, you can try to use inclusion to bypass it (theoretically).

Normally, Java will not parse and execute non-jsp files as Java, but you can use some features of the service container itself (such as parsing all files in a specified directory as jsp files) to include files with any suffix, such as The Apache Tomcat Ajp (CVE-2020-1938) vulnerability uses Tomcat's AJP (Directed Packet Protocol) protocol to parse files with arbitrary suffix names as jsp files, resulting in an RCE vulnerability.

In addition, another point to mention is that there 执行时间上is a big difference between static inclusion and dynamic inclusion. Static inclusion is executed during the translation phase , that is, the included file and the inserted page will be synthesized and compiled by the JSP compiler, and there is actually only one final compiled file. Dynamic inclusion is actually executed during the request processing phase . The JSP program will forward the request to (note that it is not redirected) the included page, output the execution result to the browser, and then return to the page to continue executing the following code, that is, it will be The included files and inserted pages will be compiled separately by the JSP compiler.

Alternative remote file inclusion

The Yidian link does not restrict the parameters passed in the URL, so you can directly request various files under the remote server. Generally, you can cooperate to read the files.

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> 
 <title>远程文件包含测试</title>
 <%  String url = request.getParameter("url"); %>
 <c:import url="<%=url%>"></c:import>  
 
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
</head>
<body>
This is my JSP page. <br>
</body>
</html>
·File Upload

I won’t talk about how to circumvent restrictions on file uploads here. There are functions that need to be paid attention to and audited.

File
lastIndexOf
indexOf
FileUpload
getRealPath
getServletPath
getPathInfo
getContentType
equalsLgnoreCase
FileUtils
MutilpartFile
MutilpartRequestEntiry
UploadHandleServlet
FileLoadServlet
FileOutputStream
getInputStream
DiskFileItemFactory
·Read/download any file

Mainly focus on the FileInputStream backtracking construction chain.
As long as you like my article today, my private collection of network security learning materials will be shared with you for free. Come and see what is there.

Network security learning resource sharing:

Finally, I would like to share with you a complete set of network security learning materials that I have studied myself. I hope it will be helpful to friends who want to learn network security!

Getting Started with Zero Basics

For students who have never been exposed to network security, we have prepared a detailed learning and growth roadmap for you. It can be said to be the most scientific and systematic learning route. It will be no problem for everyone to follow this general direction.

[Click to receive] CSDN gift package: "Hacking & Network Security Introduction & Advanced Learning Resource Package" free sharing

1. Learning roadmap

Insert image description here

There are a lot of things to learn about attack and defense. I have written down the specific things you need to learn in the road map above. If you can learn them all, you will have no problem taking on private work.

2. Video tutorial

Although there are many learning resources on the Internet, they are basically incomplete. This is an Internet security video tutorial I recorded myself. I have accompanying video explanations for every knowledge point in the roadmap above. [Click to get the video tutorial]

Insert image description here

I also compiled the technical documents myself, including my experience and technical points in participating in large-scale network security operations, CTF, and digging SRC vulnerabilities. There are also more than 200 e-books [Click to receive technical documents ]

Insert image description here

(They are all packaged into one piece and cannot be expanded one by one. There are more than 300 episodes in total)

3. Technical documents and e-books

I also compiled the technical documents myself, including my experience and technical points in participating in large-scale network security operations, CTF and digging SRC vulnerabilities. There are also more than 200 e-books [click to receive the book ]

Insert image description here

4. Toolkit, interview questions and source code

"If you want to do your job well, you must first sharpen your tools." I have summarized dozens of the most popular hacking tools for everyone. The scope of coverage mainly focuses on information collection, Android hacking tools, automation tools, phishing, etc. Interested students should not miss it.

Insert image description here

Finally, here are the interview questions about network security that I have compiled over the past few years. If you are looking for a job in network security, they will definitely help you a lot.

These questions are often encountered when interviewing Sangfor, Qi Anxin, Tencent or other major companies. If you have good questions or good insights, please share them.

Reference analysis: Sangfor official website, Qi’anxin official website, Freebuf, csdn, etc.

Content features: Clear organization and graphical representation to make it easier to understand.

Summary of content: Including intranet, operating system, protocol, penetration testing, security service, vulnerability, injection, XSS, CSRF, SSRF, file upload, file download, file inclusion, XXE, logical vulnerability, tools, SQLmap, NMAP, BP, MSF…

Insert image description here

Due to limited space, only part of the information is displayed. You need to click on the link below to get the
CSDN gift package: "Hacking & Network Security Introduction & Advanced Learning Resource Package" for free sharing

Guess you like

Origin blog.csdn.net/web22050702/article/details/133030663