java反序列化漏洞原理
1.首先是序列化的过程
序列化: ObjectOutputStream类 --> writeObject()
将对象进行序列化,把字节序列写到一个目标输出流中.ser
2.反序列化
反序列化: ObjectInputStream类 --> readObject()
从一个源输入流中读取字节序列,再把它们反序列化为一个对象
如果序列化字节序列内容可控,那么即可执行恶意类
参考代码:
这段代码中exec本来是去序列化一个String类型对象,并存储序列化流文件,之后读取序列化流文件展示。
如果对象改变,变成一个恶意类evil,则反序列化,还原对象时则会还原成恶意类,而执行构造函数中的恶意代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import java.io.*; public class main { public static void main(String[] args) throws IOException, ClassNotFoundException { new main().exec(); } public void exec() throws IOException, ClassNotFoundException { //String s="hello"; evil s= new evil(); byte [] ObjectBytes=serialize(s); File file = new File( "test.ser" ); FileOutputStream fos = new FileOutputStream(file); fos.write(ObjectBytes); File file2 = new File( "test.ser" ); FileInputStream fis = new FileInputStream(file); byte [] byteArray = new byte [( int ) file.length()]; fis.read(byteArray); String s2=(String)deserialize(byteArray); System. out .println(s2); } private byte [] serialize(final Object obj) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream( out ); objOut.writeObject(obj); return out .toByteArray(); } private Object deserialize(final byte [] serialized) throws IOException, ClassNotFoundException { ByteArrayInputStream in = new ByteArrayInputStream(serialized); ObjectInputStream objIn = new ObjectInputStream( in ); return objIn.readObject(); } } |
1 2 3 4 5 6 7 8 | import java.io.IOException; public class evil { public evil() throws IOException { Runtime rt = Runtime.getRuntime(); rt.exec( "calc" ); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】