0x003 SQLMAP如何检测是否存在SQL注入

0x003 SQLMAP如何检测是否存在SQL注入

我们直接看到lib.controller.controller​中的strat()​方法

因为start()​代码较长,所以我们这里就调重要的代码进行分析

parseTargetUrl()testSqlInj = Falseif PLACE.GET in conf.parameters and not any((conf.data, conf.testParameter)):for parameter in re.findall(r"([^=]+)=([^%s]+%s?|\Z)" % (re.escape(conf.paramDel or "") or DEFAULT_GET_POST_DELIMITER, re.escape(conf.paramDel or "") or DEFAULT_GET_POST_DELIMITER), conf.parameters[PLACE.GET]):paramKey = (conf.hostname, conf.path, PLACE.GET, parameter[0])if paramKey not in kb.testedParams:testSqlInj = Truebreakelse:paramKey = (conf.hostname, conf.path, None, None)if paramKey not in kb.testedParams:testSqlInj = Trueif testSqlInj and conf.hostname in kb.vulnHosts:if kb.skipVulnHost is None:message = "SQL injection vulnerability has already been detected "message += "against '%s'. Do you want to skip " % conf.hostnamemessage += "further tests involving it? [Y/n]"kb.skipVulnHost = readInput(message, default='Y', boolean=True)testSqlInj = not kb.skipVulnHostif not testSqlInj:infoMsg = "skipping '%s'" % targetUrllogger.info(infoMsg)continue

首先调用了parseTargetUrl()​函数进行了解析

def parseTargetUrl():"""Parse target URL and set some attributes into the configuration singleton>>> pushValue(conf.url)>>> conf.url = "https://www.test.com/?id=1">>> parseTargetUrl()>>> conf.hostname'www.test.com'>>> conf.scheme'https'>>> conf.url = popValue()"""

就是简单解析了一下url​ 区分是http​还是https​等等

testSqlInj​用来表示是否需要测试SQL注入漏洞,初始值为False

然后判断是否为GET​请求,且没有conf.data​和conf.testParameter​两个参数

如果上述条件满足就可以对每个GET​请求参数进行分析,判断是否这些参数是否在testedParameter​参数中,如果不在,则将testSqlInj​设置为True

如果需要测试的主机在已经知道存在漏洞的主机列表kb.vulnHosts​中,则进一步处理,提示用户是否需要跳过对这个主机的测试

这里正则的逻辑就是先匹配一段非=的任意长度的字符​然后用=​号分割键和值,再对值进行匹配

if testSqlInj:try:if place == PLACE.COOKIE:pushValue(kb.mergeCookies)kb.mergeCookies = Falsecheck = heuristicCheckSqlInjection(place, parameter)if check != HEURISTIC_TEST.POSITIVE:if conf.smart or (kb.ignoreCasted and check == HEURISTIC_TEST.CASTED):infoMsg = "skipping %sparameter '%s'" % ("%s " % paramType if paramType != parameter else "", parameter)logger.info(infoMsg)continueinfoMsg = "testing for SQL injection on %sparameter '%s'" % ("%s " % paramType if paramType != parameter else "", parameter)logger.info(infoMsg)# 真正开始sql注入的地方injection = checkSqlInjection(place, parameter, value)proceed = not kb.endDetectioninjectable = Falseif getattr(injection, "place", None) is not None:if NOTE.FALSE_POSITIVE_OR_UNEXPLOITABLE in injection.notes:kb.falsePositives.append(injection)else:injectable = Truekb.injections.append(injection)if not kb.alerted:if conf.alert:infoMsg = "executing alerting shell command(s) ('%s')" % conf.alertlogger.info(infoMsg)try:process = subprocess.Popen(conf.alert, shell=True)process.wait()except Exception as ex:errMsg = "error occurred while executing '%s' ('%s')" % (conf.alert, getSafeExString(ex))logger.error(errMsg)kb.alerted = True# In case when user wants to end detection phase (Ctrl+C)if not proceed:breakmsg = "%sparameter '%s' " % ("%s " % injection.place if injection.place != injection.parameter else "", injection.parameter)msg += "is vulnerable. Do you want to keep testing the others (if any)? [y/N] "if not readInput(msg, default='N', boolean=True):proceed = FalseparamKey = (conf.hostname, conf.path, None, None)kb.testedParams.add(paramKey)if not injectable:warnMsg = "%sparameter '%s' does not seem to be injectable" % ("%s " % paramType if paramType != parameter else "", parameter)logger.warning(warnMsg)finally:if place == PLACE.COOKIE:kb.mergeCookies = popValue()

这段代码就是真正进行sql注入​的地方

首先启发性检测sql注入​,通过heuristicCheckSqlInjection()​这个函数

如果启发性测试成功了的话,check​就会等于HEURISTIC_TEST.POSITIVE​这个参数,不成功的话就跳过

我们来看看heuristicCheckSqlInjection()​函数也就是启发性sql注入​的代码

def heuristicCheckSqlInjection(place, parameter):if conf.skipHeuristics:return None# 获取参数origValue = conf.paramDict[place][parameter]paramType = conf.method if conf.method not in (None, HTTPMETHOD.GET, HTTPMETHOD.POST) else placeprefix = ""suffix = ""randStr = ""# 由conf的值决定prefix和suffixif conf.prefix or conf.suffix:if conf.prefix:prefix = conf.prefixif conf.suffix:suffix = conf.suffix# rendStr 生成的启发式payload 单引号或者双引号的个数不等于1while randStr.count('\'') != 1 or randStr.count('\"') != 1:"""返回具有给定字符数的随机字符串值长度10 HEURISTIC_CHECK_ALPHABET可以在lib/core/settings.py中找到HEURISTIC_CHECK_ALPHABET的配置HEURISTIC_CHECK_ALPHABET = ('"', '\'', ')', '(', ',', '.')随机生成长度为10的 且生成的内容的基础是HEURISTIC_CHECK_ALPHABET"""randStr = randomStr(length=10, alphabet=HEURISTIC_CHECK_ALPHABET)# 启发模式设置为Truekb.heuristicMode = True# 将生成的随机字符串拼接进入payload,如果我们conf的属性中prefix和suffix为空的话,这里直接就是randStr了payload = "%s%s%s" % (prefix, randStr, suffix)# 将请求类型 place 请求参数 parameter 和生成的payload也就是randStr传入agent.payload中# 也就是?id=1 插入payload分隔符 1 后面再加上随机字符串,然后再加上payload分隔符payload = agent.payload(place, parameter, newValue=payload)page, _, _ = Request.queryPage(payload, place, content=True, raise404=False)kb.heuristicPage = pagekb.heuristicMode = False# 通过返回的页面获取可能的路径,也是正则匹配parseFilePaths(page)# 通过页面回显查询是否有可识别的数据库报错,如果匹配到了返回True反之则为Falseresult = wasLastResponseDBMSError()infoMsg = "heuristic (basic) test shows that %sparameter '%s' might " % ("%s " % paramType if paramType != parameter else "", parameter)def _(page):# 启发式的请求的返回有异常字符串# FORMAT_EXCEPTION_STRINGS同样在setting.py中# FORMAT_EXCEPTION_STRINGS = ("Type mismatch", "Error converting", "Please enter a", "Conversion failed", "String or binary data would be truncated", "Failed to convert", "unable to interpret text value", "Input string was not in a correct format", "System.FormatException", "java.lang.NumberFormatException", "ValueError: invalid literal", "TypeMismatchException", "CF_SQL_INTEGER", "CF_SQL_NUMERIC", " for CFSQLTYPE ", "cfqueryparam cfsqltype", "InvalidParamTypeException", "Invalid parameter type", "Attribute validation error for tag", "is not of type numeric", "<cfif Not IsNumeric(", "invalid input syntax for integer", "invalid input syntax for type", "invalid number", "character to number conversion error", "unable to interpret text value", "String was not recognized as a valid", "Convert.ToInt", "cannot be converted to a ", "InvalidDataException", "Arguments are of the wrong type")return any(_ in (page or "") for _ in FORMAT_EXCEPTION_STRINGS)casting = _(page) and not _(kb.originalPage) # 如果页面回显有异常字符串有True,反之为False# 这里是启发式判断是否有 数据库报错获取数据库类型 代码执行的错误if not casting and not result and kb.dynamicParameter and origValue.isdigit() and not kb.heavilyDynamic:# 上面请求的回显没有报错的话就执行下面的代码randInt = int(randomInt())payload = "%s%s%s" % (prefix, "%d-%d" % (int(origValue) + randInt, randInt), suffix)payload = agent.payload(place, parameter, newValue=payload, where=PAYLOAD.WHERE.REPLACE)result = Request.queryPage(payload, place, raise404=False) # 比较页面内容if not result:# 如果还是不行就随机生成字符串再尝试一遍randStr = randomStr()payload = "%s%s%s" % (prefix, "%s.%d%s" % (origValue, random.randint(1, 9), randStr), suffix)payload = agent.payload(place, parameter, newValue=payload, where=PAYLOAD.WHERE.REPLACE)casting = Request.queryPage(payload, place, raise404=False)# 根据上面的返回来查看是否匹配了一些异常 也就是setting中定义的值和页面的内容来判断是否存在出入kb.heuristicTest = HEURISTIC_TEST.CASTED if casting else HEURISTIC_TEST.NEGATIVE if not result else HEURISTIC_TEST.POSITIVEif kb.heavilyDynamic:debugMsg = "heuristic check stopped because of heavy dynamicity"logger.debug(debugMsg)return kb.heuristicTest# 报错信息if casting:errMsg = "possible %s casting detected (e.g. '" % ("integer" if origValue.isdigit() else "type")platform = conf.url.split('.')[-1].lower()if platform == WEB_PLATFORM.ASP:errMsg += "%s=CInt(request.querystring(\"%s\"))" % (parameter, parameter)elif platform == WEB_PLATFORM.ASPX:errMsg += "int.TryParse(Request.QueryString[\"%s\"], out %s)" % (parameter, parameter)elif platform == WEB_PLATFORM.JSP:errMsg += "%s=Integer.parseInt(request.getParameter(\"%s\"))" % (parameter, parameter)else:errMsg += "$%s=intval($_REQUEST[\"%s\"])" % (parameter, parameter)errMsg += "') at the back-end web application"logger.error(errMsg)if kb.ignoreCasted is None:message = "do you want to skip those kind of cases (and save scanning time)? %s " % ("[Y/n]" if conf.multipleTargets else "[y/N]")kb.ignoreCasted = readInput(message, default='Y' if conf.multipleTargets else 'N', boolean=True)elif result:infoMsg += "be injectable"if Backend.getErrorParsedDBMSes():infoMsg += " (possible DBMS: '%s')" % Format.getErrorParsedDBMSes()logger.info(infoMsg)else:infoMsg += "not be injectable"logger.warning(infoMsg)kb.heuristicMode = True# 禁用HTML编码kb.disableHtmlDecoding = True# 随机生成两个payload,长度为6randStr1, randStr2 = randomStr(NON_SQLI_CHECK_PREFIX_SUFFIX_LENGTH), randomStr(NON_SQLI_CHECK_PREFIX_SUFFIX_LENGTH)value = "%s%s%s" % (randStr1, DUMMY_NON_SQLI_CHECK_APPENDIX, randStr2)payload = "%s%s%s" % (prefix, "'%s" % value, suffix)payload = agent.payload(place, parameter, newValue=payload)page, _, _ = Request.queryPage(payload, place, content=True, raise404=False)# 传入探测是否存在sql注入paramType = conf.method if conf.method not in (None, HTTPMETHOD.GET, HTTPMETHOD.POST) else place# Reference: https://bugs.python.org/issue18183if value.upper() in (page or "").upper():infoMsg = "heuristic (XSS) test shows that %sparameter '%s' might be vulnerable to cross-site scripting (XSS) attacks" % ("%s " % paramType if paramType != parameter else "", parameter)logger.info(infoMsg)if conf.beep:beep()for match in re.finditer(FI_ERROR_REGEX, page or ""):if randStr1.lower() in match.group(0).lower():infoMsg = "heuristic (FI) test shows that %sparameter '%s' might be vulnerable to file inclusion (FI) attacks" % ("%s " % paramType if paramType != parameter else "", parameter)logger.info(infoMsg)if conf.beep:beep()breakkb.disableHtmlDecoding = Falsekb.heuristicMode = Falsereturn kb.heuristicTest


接下来的检测sql注入的主要函数我们后续再详细分析
如果文章中内容有误,希望大佬们帮忙指正!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/6880.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

linux中Could not load [org.bouncycastle.jcajce.provider.symmetric.RC2$KeyGen

问题描述 在linux中部署java项目&#xff0c;项目中有使用凭证加密。 解决方法 查询项目使用Java的在系统中的位置&#xff1b;找到对应java的jre路径&#xff1b;将bcprov-jdk14-127.jar放入JAVA_HOME/jre/lib/ext下&#xff1b;打开JAVA_HOME/jre/lib/security下的java.se…

分布式领域计算模型及SparkRay实现对比

目录 一、分布式计算领域概览 二、Spark计算模型分析 三、Ray计算模型分析 3.1 需求分析 3.2 系统设计 3.3 系统实现 四、总结 一、分布式计算领域概览 当前分布式计算模型主要分为以下4种&#xff1a; Bulk Synchronous Parallel Model&#xff08;块同步并行模型&…

【Linux 11】进程地址空间

文章目录 &#x1f308; Ⅰ 虚拟地址引入&#x1f308; Ⅱ 虚拟地址空间&#x1f308; Ⅲ 页表 (解释 fork() 的返回值既 > 0 又 0)&#x1f308; Ⅳ 什么是地址空间&#x1f308; Ⅴ 为什么要有地址空间 &#x1f308; Ⅰ 虚拟地址引入 现在通过一段代码来观察一个现象&a…

初识指针(1)<C语言>

前言 指针是C语言中比较难的一部分&#xff0c;大部分同学对于此部分容易产生“畏难情结”&#xff0c;但是学习好这部分对C语言的深入很大的帮助&#xff0c;所以此篇主要以讲解指针基础为主。 指针概念 变量创建的本质就是在内存中申请空间&#xff0c;找到这个变量就需要地址…

GO语言核心30讲 实战与应用 (第一部分)

原站地址&#xff1a;Go语言核心36讲_Golang_Go语言-极客时间 一、测试的基本规则和流程 1. GO程序主要分三类测试&#xff1a;功能测试、性能测试&#xff0c;以及示例测试。 示例测试和功能测试差不多&#xff0c;但它更关注程序打印出来的内容。 2. 测试文件的名称应该以…

交互中的“互”难以产生的原因

脑机交互技术的目标是通过分析和解读大脑活动&#xff0c;将其与特定的意图、指令或行为连接起来。通过训练和分析&#xff0c;可以建立起大脑活动与特定行为或意图之间的关联模型&#xff0c;从而实现脑机交互的应用&#xff0c;例如控制外部设备、传递信息等。然而&#xff0…

Python机器学习实验 Python 数据可视化

1.实验目的 掌握 Matplotlib 数据可视化的常用方法。 2.实验内容 1. 绘制鸢尾花数据集的特征分布图 说明&#xff1a;鸢尾花是单子叶百合目花卉&#xff0c;是一种比较常见的花&#xff0c;鸢尾花的品种较多。 鸢尾花数据集最初由 Edgar Anderson 测量得到&#xff0c;而后在…

android中给view添加遮罩层

1.在 res 目录中添加 id : <?xml version"1.0" encoding"utf-8"?> <resources><item name"view_mask_id" type"id" /> </resources> 2.扩展方法: /** 给一个 View 添加一层由 [res] 填充的遮罩层布局, 可…

深入学习和理解Django模板层:构建动态页面

title: 深入学习和理解Django模板层&#xff1a;构建动态页面 date: 2024/5/5 20:53:51 updated: 2024/5/5 20:53:51 categories: 后端开发 tags: Django模板表单处理静态文件国际化性能优化安全防护部署实践 第一章&#xff1a;模板语法基础 Django模板语法介绍 Django模…

每天五分钟深度学习:数学中常见函数中的导数

本文重点 导数是微积分学中的一个核心概念,它描述了函数在某一点附近的变化率。在物理学、工程学、经济学等众多领域中,导数都发挥着极其重要的作用。本文旨在详细介绍数学中常见函数的导数,以期为读者提供一个全面而深入的理解。 数学中常见的导数 常数函数的导数 对于常数…

ctfshow 框架复现

文章目录 web 466web 467web 468web469web 470web 471web 472web 473web 474web 475web 476 web 466 Laravel5.4版本 &#xff0c;提交数据需要base64编码 代码审计学习—Laravel5.4 - 先知社区 (aliyun.com) 用第二条链子 反序列化格式 /admin/序列化串base64<?php na…

大模型在自动驾驶领域的应用

大模型在自动驾驶领域的应用主要体现在以下几个方面&#xff1a; 1. **感知与识别**&#xff1a;自动驾驶车辆需要准确地感知周围环境&#xff0c;包括其他车辆、行人、交通标志等。大型深度学习模型&#xff0c;如卷积神经网络&#xff08;CNN&#xff09;和递归神经网络&…

(论文阅读-多目标优化器)Multi-Objective Parametric Query Optimization

目录 摘要 一、简介 1.1 State-of-the-Art 1.2 贡献和大纲 二、定义 三、相关工作 四、问题分析 4.1 分析 4.2 算法设计影响 五、通用算法 5.1 算法概述 5.2 完备性证明 六、分段线性代价函数算法 6.1 数据结构 6.2 基本运算实现 6.3 复杂度分析 七、实验评估 …

FR-TSN4206获得“时间敏感网络产业链名录计划”测试认证证书,TSN交换机助力智能工业发展

TSN技术&#xff0c;即时间敏感网络技术&#xff0c;已成为智能工业、自动驾驶等领域的核心。它通过时钟同步、数据调度等功能&#xff0c;确保低延迟、高可靠性的数据传输。 为推动TSN技术在我国的发展&#xff0c;工业互联网产业联盟联合多家单位启动了“时间敏感网络产业链名…

Amazon EKS创建EFS存储卷

1、创建Amazon EFS CSI 驱动程序 亚马逊相关文档 在 Select trusted entity&#xff08;选择受信任的实体&#xff09;页面上操作 在 Add permissions&#xff08;添加权限&#xff09;页面上筛选AmazonEFSCSIDriverPolicy操作 记得将AmazonEBSVolumePolicy添加到我们创建的…

Colab/PyTorch - Getting Started with PyTorch

Colab/PyTorch - Getting Started with PyTorch 1. 源由2. 概要2.1 PyTorch是什么&#xff1f;2.2 为什么学习PyTorch&#xff1f;2.3 PyTorch库概览 3. 步骤4. 预期&展望5. 总结6. 参考资料 1. 源由 世界在发展&#xff0c;为其服务的技术也在不断演变。每个人都要跟上技…

Docker-Compose 容器集群的快速编排

Docker-compose 简介 Docker-Compose项目是Docker官方的开源项目&#xff0c;负责实现对Docker容器集群的快速编排。 Docker-Compose将所管理的容器分为三层&#xff0c;分别是 工程&#xff08;project&#xff09;&#xff0c;服务&#xff08;service&#xff09;以及容器&…

2024阿里云ctf-web-chain17学习

agent jdk17依赖有h2思路清晰打jdbc attack <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.aliba…

AI图书推荐:ChatGPT在真实商业世界中的应用

《ChatGPT在真实商业世界中的应用》 (Unleashing The Power of ChatGPT: A Real World Business Applications)首先概述了ChatGPT及其在对话式人工智能领域的影响。接着&#xff0c;你将深入了解ChatGPT的技术方面&#xff0c;理解机器学习算法和自然语言处理如何在后台工作。然…

Raft共识算法笔记,MIT6.824,

处理leader和follow的一个重要思路是多数投票&#xff0c;确保系统中存在奇数个服务器&#xff08;例如3台&#xff09;。进行任何操作都需要来自多数服务器的同意&#xff0c;例如3台服务器中的2台。如果没有多数同意&#xff0c;系统会等待。为什么多数投票有助于避免脑裂问题…