修复反序列化漏洞的常规方法是升级第三方依赖库和JDK版本,或者修改java.io.ObjectInputStream类的resolveClassresolveProxyClass方法,检测传入的类名是否合法。

3.1 升级JDK版本

JDK6u141JDK7u131JDK 8u121开始引入了JEP 290,JEP 290: Filter Incoming Serialization Data限制了RMI类反序列化,添加了安全过滤机制,在一定程度上阻止了反序列化攻击。
4. 3. 反序列化攻击防御 - 图1
ObjectInputStream在序列化对象时是会调用java.io.ObjectInputStream#filterCheck->sun.rmi.registry.RegistryImpl#registryFilter,检测合法性:
4. 3. 反序列化攻击防御 - 图2
当攻击者向一个实现了JEP 290的服务端JDK发送反序列化对象时会攻击失败并抛出:java.io.InvalidClassException: filter status: REJECTED异常。
4. 3. 反序列化攻击防御 - 图3
JDK9中ObjectInputStream可以设置ObjectInputFilter,可实现自定义对象过滤器,如下:

  1. ObjectInputStream ois = new ObjectInputStream(bis);
  2. ois.setObjectInputFilter(new ObjectInputFilter() {
  3. @Override
  4. public Status checkInput(FilterInfo filterInfo) {
  5. // 序列化类名称
  6. String className = filterInfo.serialClass().getName();
  7. // 类名检测逻辑
  8. return ALLOWED;
  9. }
  10. });

除此之外,还可以添加JVM启动参数:-Djdk.serialFilter过滤危险的类,参考:JDK approach to address deserialization Vulnerability

3.2 重写ObjectInputStream类resolveClass

https://github.com/ikkisoft/SerialKiller是一个非常简单的反序列化攻击检测工具,利用的是继承ObjectInputStream重写resolveClass方法,为了便于理解,这里把SerialKiller改成了直接读取规则的方式检测反序列化的类名。
示例 - SerialKiller:

  1. /*
  2. * 修改自:https://github.com/ikkisoft/SerialKiller
  3. */
  4. import java.io.*;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7. public class ObjectInputStreamFilter extends ObjectInputStream {
  8. // 定义禁止反序列化的类黑名单正则表达式
  9. private static final String[] REGEXPS = new String[]{
  10. "bsh\\.XThis$", "bsh\\.Interpreter$",
  11. "com\\.mchange\\.v2\\.c3p0\\.impl\\.PoolBackedDataSourceBase$",
  12. "org\\.apache\\.commons\\.beanutils\\.BeanComparator$",
  13. "org\\.apache\\.commons\\.collections\\.Transformer$",
  14. "org\\.apache\\.commons\\.collections\\.functors\\.InvokerTransformer$",
  15. "org\\.apache\\.commons\\.collections\\.functors\\.ChainedTransformer$",
  16. "org\\.apache\\.commons\\.collections\\.functors\\.ConstantTransformer$",
  17. "org\\.apache\\.commons\\.collections\\.functors\\.InstantiateTransformer$",
  18. "org\\.apache\\.commons\\.collections4\\.functors\\.InvokerTransformer$",
  19. "org\\.apache\\.commons\\.collections4\\.functors\\.ChainedTransformer$",
  20. "org\\.apache\\.commons\\.collections4\\.functors\\.ConstantTransformer$",
  21. "org\\.apache\\.commons\\.collections4\\.functors\\.InstantiateTransformer$",
  22. "org\\.apache\\.commons\\.collections4\\.comparators\\.TransformingComparator$",
  23. "org\\.apache\\.commons\\.fileupload\\.disk\\.DiskFileItem$",
  24. "org\\.apache\\.wicket\\.util\\.upload\\.DiskFileItem$",
  25. "org\\.codehaus\\.groovy\\.runtime\\.ConvertedClosure$",
  26. "org\\.codehaus\\.groovy\\.runtime\\.MethodClosure$",
  27. "org\\.hibernate\\.engine\\.spi\\.TypedValue$",
  28. "org\\.hibernate\\.tuple\\.component\\.AbstractComponentTuplizer$",
  29. "org\\.hibernate\\.tuple\\.component\\.PojoComponentTuplizer$",
  30. "org\\.hibernate\\.type\\.AbstractType$", "org\\.hibernate\\.type\\.ComponentType$",
  31. "org\\.hibernate\\.type\\.Type$", "com\\.sun\\.rowset\\.JdbcRowSetImpl$",
  32. "org\\.jboss\\.(weld\\.)?interceptor\\.builder\\.InterceptionModelBuilder$",
  33. "org\\.jboss\\.(weld\\.)?interceptor\\.builder\\.MethodReference$",
  34. "org\\.jboss\\.(weld\\.)?interceptor\\.proxy\\.DefaultInvocationContextFactory$",
  35. "org\\.jboss\\.(weld\\.)?interceptor\\.proxy\\.InterceptorMethodHandler$",
  36. "org\\.jboss\\.(weld\\.)?interceptor\\.reader\\.ClassMetadataInterceptorReference$",
  37. "org\\.jboss\\.(weld\\.)?interceptor\\.reader\\.DefaultMethodMetadata$",
  38. "org\\.jboss\\.(weld\\.)?interceptor\\.reader\\.ReflectiveClassMetadata$",
  39. "org\\.jboss\\.(weld\\.)?interceptor\\.reader\\.SimpleInterceptorMetadata$",
  40. "org\\.jboss\\.(weld\\.)?interceptor\\.spi\\.instance\\.InterceptorInstantiator$",
  41. "org\\.jboss\\.(weld\\.)?interceptor\\.spi\\.metadata\\.InterceptorReference$",
  42. "org\\.jboss\\.(weld\\.)?interceptor\\.spi\\.metadata\\.MethodMetadata$",
  43. "org\\.jboss\\.(weld\\.)?interceptor\\.spi\\.model\\.InterceptionModel$",
  44. "org\\.jboss\\.(weld\\.)?interceptor\\.spi\\.model\\.InterceptionType$",
  45. "java\\.rmi\\.registry\\.Registry$", "java\\.rmi\\.server\\.ObjID$",
  46. "java\\.rmi\\.server\\.RemoteObjectInvocationHandler$",
  47. "net\\.sf\\.json\\.JSONObject$", "javax\\.xml\\.transform\\.Templates$",
  48. "org\\.python\\.core\\.PyObject$", "org\\.python\\.core\\.PyBytecode$",
  49. "org\\.python\\.core\\.PyFunction$", "org\\.mozilla\\.javascript\\..*$",
  50. "org\\.apache\\.myfaces\\.context\\.servlet\\.FacesContextImpl$",
  51. "org\\.apache\\.myfaces\\.context\\.servlet\\.FacesContextImplBase$",
  52. "org\\.apache\\.myfaces\\.el\\.CompositeELResolver$",
  53. "org\\.apache\\.myfaces\\.el\\.unified\\.FacesELContext$",
  54. "org\\.apache\\.myfaces\\.view\\.facelets\\.el\\.ValueExpressionMethodExpression$",
  55. "com\\.sun\\.syndication\\.feed\\.impl\\.ObjectBean$",
  56. "org\\.springframework\\.beans\\.factory\\.ObjectFactory$",
  57. "org\\.springframework\\.core\\.SerializableTypeWrapper\\$MethodInvokeTypeProvider$",
  58. "org\\.springframework\\.aop\\.framework\\.AdvisedSupport$",
  59. "org\\.springframework\\.aop\\.target\\.SingletonTargetSource$",
  60. "org\\.springframework\\.aop\\.framework\\.JdkDynamicAopProxy$",
  61. "org\\.springframework\\.core\\.SerializableTypeWrapper\\$TypeProvider$",
  62. "java\\.util\\.PriorityQueue$", "java\\.lang\\.reflect\\.Proxy$",
  63. "javax\\.management\\.MBeanServerInvocationHandler$",
  64. "javax\\.management\\.openmbean\\.CompositeDataInvocationHandler$",
  65. "org\\.springframework\\.aop\\.framework\\.JdkDynamicAopProxy$",
  66. "java\\.beans\\.EventHandler$", "java\\.util\\.Comparator$",
  67. "org\\.reflections\\.Reflections$"
  68. };
  69. public ObjectInputStreamFilter(final InputStream inputStream) throws IOException {
  70. super(inputStream);
  71. }
  72. @Override
  73. protected Class<?> resolveClass(final ObjectStreamClass serialInput) throws IOException, ClassNotFoundException {
  74. classNameFilter(new String[]{serialInput.getName()});
  75. return super.resolveClass(serialInput);
  76. }
  77. @Override
  78. protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
  79. classNameFilter(interfaces);
  80. return super.resolveProxyClass(interfaces);
  81. }
  82. private void classNameFilter(String[] classNames) throws InvalidClassException {
  83. for (String className : classNames) {
  84. for (String regexp : REGEXPS) {
  85. Matcher blackMatcher = Pattern.compile(regexp).matcher(className);
  86. if (blackMatcher.find()) {
  87. throw new InvalidClassException("禁止反序列化的类:" + className);
  88. }
  89. }
  90. }
  91. }
  92. }

调用方式:

  1. // 存在恶意攻击的反序列化类输入流
  2. ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
  3. // 包装原来的ObjectInputStream,校验反序列化类
  4. ObjectInputStream ois = new ObjectInputStreamFilter(bis);
  5. // ObjectInputStream ois = new ObjectInputStream(bis);
  6. // 反序列化
  7. ois.readObject();

反序列化包含恶意Payload的输入流时会抛出异常:
4. 3. 反序列化攻击防御 - 图4
重写ObjectInputStream类方法虽然灵活,但是必须修改每一个需要反序列化输入流的实现类,比较繁琐。

3.3 RASP防御反序列化攻击

RASP可以利用动态编辑类字节码的优势,直接编辑ObjectInputStream类的resolveClass/resolveProxyClass方法字节码,动态插入RASP类代码,从而实现检测反序列化脚本攻击。

  1. package java.io;
  2. public class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants {
  3. // .. 省略其他代码
  4. protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
  5. // 插入RASP检测代码,检测ObjectStreamClass反序列化的类名是否合法
  6. }
  7. protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
  8. // 插入RASP检测代码,检测动态代理类接口类名是否合法
  9. }
  10. }

RASP防御反序列化攻击流程图:
4. 3. 反序列化攻击防御 - 图5
使用RASP检测反序列化攻击,可以不用受制于请求协议、服务、框架等,检测规则可实时更新,从而程度上实现反序列化攻击防御。
示例 - whoami.jsp:

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <%@ page import="org.apache.commons.codec.binary.Base64" %>
  3. <%@ page import="java.io.ByteArrayInputStream" %>
  4. <%@ page import="java.io.ObjectInputStream" %>
  5. <%
  6. // 定义一个使用ysoserial生成的执行本地系统命令的Payload:java -jar ysoserial-0.0.6.jar CommonsCollections5 "whoami" |base64
  7. byte[] classBuffer = Base64.decodeBase64("rO0ABXNyAC5qYXZheC5tYW5hZ2VtZW50LkJhZEF0dHJpYnV0ZVZhbHVlRXhwRXhjZXB0aW9u1Ofaq2MtRkACAAFMAAN2YWx0ABJMamF2YS9sYW5nL09iamVjdDt4cgATamF2YS5sYW5nLkV4Y2VwdGlvbtD9Hz4aOxzEAgAAeHIAE2phdmEubGFuZy5UaHJvd2FibGXVxjUnOXe4ywMABEwABWNhdXNldAAVTGphdmEvbGFuZy9UaHJvd2FibGU7TAANZGV0YWlsTWVzc2FnZXQAEkxqYXZhL2xhbmcvU3RyaW5nO1sACnN0YWNrVHJhY2V0AB5bTGphdmEvbGFuZy9TdGFja1RyYWNlRWxlbWVudDtMABRzdXBwcmVzc2VkRXhjZXB0aW9uc3QAEExqYXZhL3V0aWwvTGlzdDt4cHEAfgAIcHVyAB5bTGphdmEubGFu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qCk94GHOAIAAUkABXZhbHVleHIAEGphdmEubGFuZy5OdW1iZXKGrJUdC5TgiwIAAHhwAAAAAXNyABFqYXZhLnV0aWwuSGFzaE1hcAUH2sHDFmDRAwACRgAKbG9hZEZhY3RvckkACXRocmVzaG9sZHhwP0AAAAAAAAB3CAAAABAAAAAAeHg=");
  8. ObjectInputStream bis = new ObjectInputStream(new ByteArrayInputStream(classBuffer));
  9. bis.readObject();
  10. %>

在使用RASP防御的情况下请求示例程序后Java会执行Runtime.getRuntime().exec("whoami");,如下图:
4. 3. 反序列化攻击防御 - 图6
当启动RASP后再次请求示例程序后会发现示例程序已无法正常访问,因为当RASP发现正在反序列化的类存在恶意攻击时候会立即阻断反序列化行为,如下图:
4. 3. 反序列化攻击防御 - 图7