首页
社区
课程
招聘
3
[原创] CVE-2023-4069:Type confusion in VisitFindNonDefaultConstructorOrConstruct of Maglev
发表于: 2024-4-13 21:07 12112

[原创] CVE-2023-4069:Type confusion in VisitFindNonDefaultConstructorOrConstruct of Maglev

2024-4-13 21:07
12112

@

目录

前言

最近在学习 Maglev 相关知识,然后看了一些与其相关的 CVE,感觉该漏洞比较容易复现,所以先打算复现一下,本文还是主要分析漏洞产生的原因,基础知识笔者会简单说一说,更多的还是需要读者自己去学习

这里说一下为什么笔者不愿意在漏洞分析中写过多的前置知识,因为笔者认为读者都已经开始复现漏洞了,那么对基础知识应当是有一定的了解了,并且笔者的基础也比较差,所以不希望误人子弟,网上的资料很多,自己学学就 OK 啦

环境搭建

1
2
git checkout 7f22404388ef0eb9383f189c1b0a85b5ea93b079
gclient sync -D

前置知识

new 关键字new func() 效果为:

  • 创建一个默认对象 this,然后进行初始化 this.prop = val
  • func 本身返回一个对象,则抛弃默认对象;否则返回默认对象

这里给一个示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class A {
        constructor() {
                this.x = 1;
        }
}
 
class B {
        constructor() {
                this.x = 1;
                return [1.1, 2.2];
        }
}
 
var a = new A();
var b = new B();
print(a); // [object Object]
print(b); // 1.1,2.2

new.target 这里自行看资料

Reflect.construct(target, argument, new_target) 函数以 target 为构造函数创建对象,这里 new_target 提供原型,然后行为跟 new func() 类似

上面的知识都比较简单,所以也不想细说了,如果读者不是很清楚的话,请自行查阅下相关资料吧,这里主要关注 JS 引擎层面的实现

对于默认对象,其是通过 FastNewObject 函数创建的,其调用链如下:

1
2
3
4
5
6
7
8
9
10
TF_BUILTIN(FastNewObject, ConstructorBuiltinsAssembler)
TNode ConstructorBuiltinsAssembler::FastNewObject(
                                                TNode context,
                                                TNode target,
                                                TNode new_target)
        ⇒ TNode ConstructorBuiltinsAssembler::FastNewObject(
                                                TNode context,
                                                TNode target,
                                                TNode new_target,
                                                Label* call_runtime)

先来看看 TF_BUILTIN(FastNewObject, ConstructorBuiltinsAssembler)

1
2
3
4
5
6
7
8
9
10
11
12
13
TF_BUILTIN(FastNewObject, ConstructorBuiltinsAssembler) {
  auto context = Parameter(Descriptor::kContext);
  auto target = Parameter(Descriptor::kTarget);
  auto new_target = Parameter(Descriptor::kNewTarget);
 
  Label call_runtime(this);
  // 先调用 FastNewObject
  TNode result = FastNewObject(context, target, new_target, &call_runtime);
  Return(result);
 
  BIND(&call_runtime);
  TailCallRuntime(Runtime::kNewObject, context, target, new_target);
}

该函数比较简单,其主要就是调用了 ConstructorBuiltinsAssembler::FastNewObject 函数:

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
38
39
40
41
42
43
44
45
46
47
48
49
TNode ConstructorBuiltinsAssembler::FastNewObject(
    TNode context, TNode target,
    TNode new_target, Label* call_runtime) {
  // Verify that the new target is a JSFunction.
  Label end(this);
  // 检测 new_target 是否是 JSFunction
  TNode new_target_func = HeapObjectToJSFunctionWithPrototypeSlot(new_target, call_runtime);
  // Fast path.
  // 快速路径
  // Load the initial map and verify that it's in fact a map.
  // 加载 new_target_func 的 initial_map or proto
  TNode initial_map_or_proto = LoadJSFunctionPrototypeOrInitialMap(new_target_func);
  // 如果 initial_map_or_proto 是 Smi,则调用 call_runtime 运行时函数(相当于慢速路径了)
  GotoIf(TaggedIsSmi(initial_map_or_proto), call_runtime);
  // 检查  initial_map_or_proto  是否是 Map
  GotoIf(DoesntHaveInstanceType(CAST(initial_map_or_proto), MAP_TYPE), call_runtime);
  // initial_map 是一个 Map
  TNode initial_map = CAST(initial_map_or_proto);
 
  // Fall back to runtime if the target differs from the new target's initial map constructor.
  // 加载 initial_map 的构造函数 new_target_constructor
  TNode new_target_constructor = LoadObjectField(initial_map, Map::kConstructorOrBackPointerOrNativeContextOffset);
  // 如果 target != new_target_constructor,则走慢速路径
  GotoIf(TaggedNotEqual(target, new_target_constructor), call_runtime);
 
  TVARIABLE(HeapObject, properties);
  Label instantiate_map(this), allocate_properties(this);
  GotoIf(IsDictionaryMap(initial_map), &allocate_properties);
  {
    // 分配 properties (非字典模式)
    properties = EmptyFixedArrayConstant();
    Goto(&instantiate_map);
  }
  // 字典模式
  BIND(&allocate_properties);
  {
    if (V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL) {
      properties = AllocateSwissNameDictionary(SwissNameDictionary::kInitialCapacity);
    } else {
      properties = AllocateNameDictionary(NameDictionary::kInitialCapacity);
    }
    Goto(&instantiate_map);
  }
 
  BIND(&instantiate_map);
  // 最后根据 initial_map 创建 JSObject
  return AllocateJSObjectFromMap(initial_map, properties.value(), base::nullopt,
                                 AllocationFlag::kNone, kWithSlackTracking);
}

可以看到 ConstructorBuiltinsAssembler::FastNewObject 分为快速路径和慢速路径:

  • 快速路径:直接根据 new_targetinitial_map 进行默认对象的创建
    • initial_map 的构造函数与 target 相同
    • new_targetinitial_map 为一个有效 map
  • 慢速路径:调用 Runtime::kNewObject 运行时函数

这里的快速路径可能有点奇怪?因为这里 target 才是构造函数,所以默认对象的 map 再怎么说也不应该与 new_targetinitial_map 相同,但这其实是一个优化,其会将 targetinitial_mapnew_targetprototype 缓存在 new_targetinitial_map 域,这个后面再说

然后可以看到走快速路径是存在两个条件的,不满足则会走慢速路径 Runtime::kNewObjec

1
2
3
4
5
6
7
8
9
RUNTIME_FUNCTION(Runtime_NewObject) {
  HandleScope scope(isolate);
  DCHECK_EQ(2, args.length());
  Handle target = args.at(0);
  Handle new_target = args.at(1);
  RETURN_RESULT_OR_FAILURE(
      isolate,
      JSObject::New(target, new_target, Handle::null()));
}

可以看到其直接调用了 JSObject::New 函数:

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
MaybeHandle JSObject::New(Handle constructor,
                                    Handle new_target,
                                    Handle site) {
  // 这里可以看下注释:其对 new / Reflect.construct 的 new.target 存在不同的要求
  // If called through new, new.target can be:
  // - a subclass of constructor,
  // - a proxy wrapper around constructor, or
  // - the constructor itself.
  // If called through Reflect.construct, it's guaranteed to be a constructor.
  Isolate* const isolate = constructor->GetIsolate();
  DCHECK(constructor->IsConstructor());
  DCHECK(new_target->IsConstructor());
  DCHECK(!constructor->has_initial_map() ||
         !InstanceTypeChecker::IsJSFunction(constructor->initial_map().instance_type()));
 
  Handle initial_map;
  //【1】
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, initial_map,
      JSFunction::GetDerivedMap(isolate, constructor, new_target), JSObject);
   
  constexpr int initial_capacity = V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL
                                       ? SwissNameDictionary::kInitialCapacity
                                       : NameDictionary::kInitialCapacity;
   
  Handle result = isolate->factory()->NewFastOrSlowJSObjectFromMap(
      initial_map, initial_capacity, AllocationType::kYoung, site);
   
  return result;
}

【1】 处会调用 JSFunction::GetDerivedMap 函数,这里的 constructor 传入的是 target

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
MaybeHandle JSFunction::GetDerivedMap(Isolate* isolate,
                                           Handle constructor,
                                           Handle new_target) {
  // 为 constructor 即 target 分配 initial_map
  EnsureHasInitialMap(constructor);
 
  Handle constructor_initial_map(constructor->initial_map(), isolate);
  // 如果 target == new_target,则直接返回
  if (*new_target == *constructor) return constructor_initial_map;
 
  Handle result_map;
  // Fast case, new.target is a subclass of constructor. The map is cacheable
  // (and may already have been cached). new.target.prototype is guaranteed to
  // be a JSReceiver.
  // 否则为 new_target 创建 initial_map
  if (new_target->IsJSFunction()) {
    Handle function = Handle::cast(new_target);
    if (FastInitializeDerivedMap(isolate, function, constructor, constructor_initial_map)) {
      return handle(function->initial_map(), isolate);
    }
  }

可以看到其会调用 FastInitializeDerivedMapnew_target 创建 initial_map

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
bool FastInitializeDerivedMap(Isolate* isolate, Handle new_target,
                              Handle constructor,
                              Handle constructor_initial_map) {
  // Use the default intrinsic prototype instead.
  // new_target 不是一个 JSFunction,返回 false 表示失败
  if (!new_target->has_prototype_slot()) return false;
  // Check that |function|'s initial map still in sync with the |constructor|,
  // otherwise we must create a new initial map for |function|.
  // 如果 new_target 存在 initial_map,并且 initial_map.constructor 就是 target
  //    则说明之前已经缓存过了,所以直接返回 true
  if (new_target->has_initial_map() &&
        new_target->initial_map().GetConstructor() == *constructor) {
    DCHECK(new_target->instance_prototype().IsJSReceiver());
    return true;
  }
  // 否则创建新的 map
......
  // 【1】
  Handle map =
      Map::CopyInitialMap(isolate, constructor_initial_map, instance_size, in_object_properties, unused_property_fields);
  map->set_new_target_is_base(false);
  Handle prototype(new_target->instance_prototype(), isolate);
  // 【2】
  JSFunction::SetInitialMap(isolate, new_target, map, prototype, constructor);
  DCHECK(new_target->instance_prototype().IsJSReceiver());
  map->set_construction_counter(Map::kNoSlackTracking);
  map->StartInobjectSlackTracking();
  return true;
}

可以看到在 【2】 处设置了 new_targetinitial_mapmap,但是修改了 prototypenew_targetprototypeconstructortarget。而该 map【1】 处是通过复制 constructor_initial_map 来的,看到这里可能就明白了之前快速路径的逻辑

所以在快速路径中,当 new_target.initial_map.constructor = target 时,则说明 new_target.initial_maptarget.initial_map 是相同的,所以这里就会直接使用 new_target.initial_map

OK,以上就是后面漏洞分析需要的一些基础知识

漏洞分析

还是先从 patch 入手:

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
38
39
40
41
42
43
44
diff --git a/src/maglev/maglev-graph-builder.cc b/src/maglev/maglev-graph-builder.cc
index d5f6128..2c5227e 100644
--- a/src/maglev/maglev-graph-builder.cc
+++ b/src/maglev/maglev-graph-builder.cc
@@ -5347,6 +5347,14 @@
   StoreRegister(iterator_.GetRegisterOperand(0), map_proto);
 }
  
+bool MaglevGraphBuilder::HasValidInitialMap(
+    compiler::JSFunctionRef new_target, compiler::JSFunctionRef constructor) {
if (!new_target.map(broker()).has_prototype_slot()) return false;
if (!new_target.has_initial_map(broker())) return false;
+  compiler::MapRef initial_map = new_target.initial_map(broker());
return initial_map.GetConstructor(broker()).equals(constructor);
+}
+
 void MaglevGraphBuilder::VisitFindNonDefaultConstructorOrConstruct() {
   ValueNode* this_function = LoadRegisterTagged(0);
   ValueNode* new_target = LoadRegisterTagged(1);
@@ -5380,7 +5388,9 @@
               TryGetConstant(new_target);
           if (kind == FunctionKind::kDefaultBaseConstructor) {
             ValueNode* object;
-            if (new_target_function && new_target_function->IsJSFunction()) {
+            if (new_target_function && new_target_function->IsJSFunction() &&
+                HasValidInitialMap(new_target_function->AsJSFunction(),
+                                   current_function)) {
               object = BuildAllocateFastObject(
                   FastObject(new_target_function->AsJSFunction(), zone(),
                              broker()),
diff --git a/src/maglev/maglev-graph-builder.h b/src/maglev/maglev-graph-builder.h
index 0abb4a8..d92354c 100644
--- a/src/maglev/maglev-graph-builder.h
+++ b/src/maglev/maglev-graph-builder.h
@@ -1884,6 +1884,9 @@
   void MergeDeadLoopIntoFrameState(int target);
   void MergeIntoInlinedReturnFrameState(BasicBlock* block);
  
bool HasValidInitialMap(compiler::JSFunctionRef new_target,
+                          compiler::JSFunctionRef constructor);
+
   enum JumpType { kJumpIfTrue, kJumpIfFalse };
   enum class BranchSpecializationMode { kDefault, kAlwaysBoolean };
   JumpType NegateJumpType(JumpType jump_type);

从补丁打的位置可以知道该漏洞应该发生在 Maglev 的图构建阶段,并且其主要打在了 MaglevGraphBuilder::VisitFindNonDefaultConstructorOrConstruct 函数中,根据函数名大概知道其主要就是处理 FindNonDefaultConstructorOrConstruct 字节码的,而该操作的功能为“寻找非默认构造函数”,这里结合 chatGPT 食用:

在 V8 引擎中,FindNonDefaultConstructorOrConstruct 字节码指令用于查找非默认构造函数或构造器函数。这个字节码指令在 JavaScript 代码中的类构造过程中使用。

当在 JavaScript 中创建一个类并调用 new 关键字来实例化对象时,V8 引擎会执行相应的字节码指令序列。其中,FindNonDefaultConstructorOrConstruct 字节码指令用于查找适当的构造函数或构造器函数。

具体而言,该指令会检查类的原型链以查找适合的构造函数。它首先尝试查找类自身的 constructor 属性,如果找到则使用该构造函数。否则,它会沿着原型链向上查找,直到找到一个非默认构造函数或构造器函数。

这个过程是为了确保在类继承链中正确地选择构造函数,以便在实例化对象时执行相应的初始化逻辑。

所以可以写出如下代码去生成目标字节码:

1
2
3
class A {}
class B extends A {}
var b = new B();

来看下 B 产生的字节码:


[注意]看雪招聘,专注安全领域的专业人才平台!

最后于 2024-4-13 21:22 被XiaozaYa编辑 ,原因:
收藏
免费 3
支持
分享
赞赏记录
参与人
雪币
留言
时间
PLEBFE
为你点赞~
2024-5-31 01:27
霸气压萝莉
为你点赞~
2024-4-13 23:19
tank小王子
为你点赞~
2024-4-13 22:11
最新回复 (7)
雪    币: 3972
活跃值: (31426)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
2
感谢分享
2024-4-14 22:06
1
雪    币: 214
能力值: ( LV1,RANK:0 )
在线值:
发帖
回帖
粉丝
3
感谢师傅的分享,最近也在研究Maglev,但我似乎不太能理解其SSA的表现性(区别于llvm的ssa,我感觉llvm的ir似乎更好理解),还有其phi节点的untag过程有所疑惑,也没有找到比较好的资料。希望师傅可以给一点启发,不胜感激。
2024-4-19 17:56
0
雪    币: 5930
活跃值: (2935)
能力值: ( LV9,RANK:250 )
在线值:
发帖
回帖
粉丝
4
远岚沐秋 感谢师傅的分享,最近也在研究Maglev,但我似乎不太能理解其SSA的表现性(区别于llvm的ssa,我感觉llvm的ir似乎更好理解),还有其phi节点的untag过程有所疑惑,也没有找到比较好的资 ...
跟llvm的ir是类似的,你看llvm的ir其实也就够了,至于你说的表现性,我没理解是什么意思。对于 phi 节点的 untag 过程,你并没有说你疑惑的点是什么,所有笔者也不知道你疑惑的点是什么。个人理解:笔者认为是因为 V8 使用了指针标记,而有的操作需要 tag 值,有的操作需要 untag 值,而 untag 值相对而言是比较危险的,因为 untag 后,其无法再区分指针和Smi,所以在生成 IR 图时,所有的 phi 节点都进行了 tag,后面进行 untag 其实就是一种优化,其根据输入输出去除 tag 与 untag 之间的转换,对于使用 untag 的操作,其直接使用 untag 值
2024-4-19 21:28
0
雪    币: 5930
活跃值: (2935)
能力值: ( LV9,RANK:250 )
在线值:
发帖
回帖
粉丝
5
XiaozaYa 跟llvm的ir是类似的,你看llvm的ir其实也就够了,至于你说的表现性,我没理解是什么意思。对于 phi 节点的 untag 过程,你并没有说你疑惑的点是什么,所有笔者也不知道你疑惑的点是什么。个 ...
你可以对着 Maglev IR 看看
2024-4-19 21:32
0
雪    币: 214
能力值: ( LV1,RANK:0 )
在线值:
发帖
回帖
粉丝
6
XiaozaYa 你可以对着 Maglev IR 看看
感谢师傅的解答,其实phi的tag和untag过程比较疑惑,或者说我其实没有理解phi的tag和untag本质上是一个什么操作,师傅好像解答了,我再深入看看,谢谢
2024-4-20 19:00
0
雪    币: 20
能力值: ( LV1,RANK:0 )
在线值:
发帖
回帖
粉丝
7
请问一下exp中的minor_gc为什么最后还要添加new ArrayBuffer(8),前面应该足够出发minor_gc了
2024-4-23 19:22
0
雪    币: 5930
活跃值: (2935)
能力值: ( LV9,RANK:250 )
在线值:
发帖
回帖
粉丝
8
岚沐 请问一下exp中的minor_gc为什么最后还要添加new ArrayBuffer(8),前面应该足够出发minor_gc了
都行,问题不大
2024-8-15 11:53
0
游客
登录 | 注册 方可回帖
返回

账号登录
验证码登录

忘记密码?
没有账号?立即免费注册