MongoDB的相关安全问题


记得去年的时候因为工作需要调研过一段时间的MongoDB,不过后来因为别的原因就没有深入,这次又碰到了,所以,顺便从网上找了一些教程,了解它的一些相关安全问题,记录如下:

工具:

扫描 https://github.com/tcstool/NoSQLMap
GUI连接 MongoVUE

文档:

MongoDB官方文档
MongoDB安全配置

相关案例:

http://www.wooyun.org/searchbug.php #搜索“MongoDB”

扫描脚本:
#!/usr/bin/env python
# coding=utf-8
import pymongo
def mongoScan(ip, port):
try:
    conn = pymongo.MongoClient(ip, port, connectTimeoutMS=4000, socketTimeoutMS=4000)
    try:
        dbList = conn.database_names()
        dbVer = conn.server_info()['version']
        conn.disconnect()
        print "Successful access with no credentials!"
        return [0, dbVer]
    except:
        if str(sys.exc_info()).find('need to login') != -1:
            conn.disconnect()
            print "Login required!"
            return [1, None]
        else:
            conn.disconnect()
            print "Access check failure."
            return [2, None]

except:
    print "Couldn't connect to Mongo server."
    return [3, None]
多线程版本:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys
import pymongo
import threading
from Queue import Queue

def conn(addr):
    try:
        conn = pymongo.MongoClient(addr, 27017, socketTimeoutMS=3000)
        dbname = conn.database_names()
        if dbname:
            print "Success IP: %s" % addr
            print "show dbs:"
            with open("ixyzero.com.txt", "a") as af:
                af.write(addr+"n")
            for i in dbname:
                b = "t%s" % i
                print b
                with open("ixyzero.com.txt", "a") as af:
                    af.write(b+"n")
        conn.close()
    except:
        print "%s connection was failed" % addr

class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        global queue
        while not queue.empty():
            ip = queue.get()
            conn(ip)

if __name__ == "__main__":
    queue = Queue()
    a = open(sys.argv[1], 'r')
    for ip in a.readlines():
        ip = ip.strip('')
        queue.put(ip)
    for i in range(99):
        c = MyThread()
        c.start()

参考链接ZMAP扫描mongodb配合多线程验证脚本

安装/操作命令:
hi@vm:~$ sudo apt-get install mongodb-clients #远程连接,需要安装MongoDB的客户端
hi@vm:~$ mongo
mongo mongodump mongoexport mongofiles mongoimport mongorestore mongostat
hi@vm:~$ mongo 203.195.150.245
MongoDB shell version: 2.0.4
connecting to: 203.195.150.245/test
> show dbs;
> use db_name;
switched to db db_name
> show collections;
> db.stats();
> db.currentOp();
> db.serverStatus();

> use local;
> db.stats();
> db.currentOp();
> db.serverStatus();
> db.system.users.find();
> db.FlightOrder.find().limit(100);


hi@vm:~$ mongo
MongoDB shell version: 2.0.4
connecting to: test
Wed Nov 19 14:22:07 Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84
exception: connect failed
hi@vm:~$ sudo apt-get install mongodb #本地测试,需要安装MongoDB服务端
mongodb mongodb-clients mongodb-dev mongodb-server

 

hi@vm:~$ mongo
MongoDB shell version: 2.0.4
connecting to: test
> show dbs;
local (empty)
> use local;
switched to db local
> show collections;
> help
db.help() help on db methods
db.mycoll.help() help on collection methods
rs.help() help on replica set methods
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce

show dbs show database names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms
show logs show the accessible logger names
show log [name] prints out the last segment of log in memory, 'global' is default
use <db_name> set current database
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
it result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x set default number of items to display on shell
exit quit the mongo shell
> db.help();
DB methods:
db.addUser(username, password[, readOnly=false])
db.auth(username, password)
db.cloneDatabase(fromhost)
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost)
db.createCollection(name, { size : ..., capped : ..., max : ... } )
db.currentOp() displays the current operation in the db
db.dropDatabase()
db.eval(func, args) run code server-side
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getMongo() get the server connection object
db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
db.getName()
db.getPrevError()
db.getProfilingLevel() - deprecated
db.getProfilingStatus() - returns if profiling is on and slow threshold
db.getReplicationInfo()
db.getSiblingDB(name) get the db at the same server as this one
db.isMaster() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.logout()
db.printCollectionStats()
db.printReplicationInfo()
db.printSlaveReplicationInfo()
db.printShardingStatus()
db.removeUser(username)
db.repairDatabase()
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }
db.serverStatus()
db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
db.shutdownServer()
db.stats()
db.version() current version of the server
db.getMongo().setSlaveOk() allow queries on a replication slave server
db.fsyncLock() flush data to disk and lock server for backups
db.fsyncUnock() unlocks server following a db.fsyncLock()
> help admin
ls([path]) list files
pwd() returns current directory
listFiles([path]) returns file list
hostname() returns name of this host
cat(fname) returns contents of text file as a string
removeFile(f) delete a file or directory
load(jsfilename) load and execute a .js file
run(program[, args...]) spawn a program and wait for its completion
runProgram(program[, args...]) same as run(), above
sleep(m) sleep m milliseconds
getMemInfo() diagnostic
> help connect

Normally one specifies the server on the mongo shell command line. Run mongo --help to see those options.
Additional connections may be opened:

var x = new Mongo('host[:port]');
var mydb = x.getDB('mydb');
or
var mydb = connect('host[:port]/mydb');

Note: the REPL prompt only auto-reports getLastError() for the shell command line connection.

> help keys
Tab completion and command history is available at the command prompt.

Some emacs keystrokes are available too:
Ctrl-A start of line
Ctrl-E end of line
Ctrl-K del to end of line

Multi-line commands
You can enter a multi line javascript expression. If parens, braces, etc. are not closed, you will see a new line
beginning with '...' characters. Type the rest of your expression. Press Ctrl-C to abort the data entry if you
get stuck.

> help misc
b = new BinData(subtype,base64str) create a BSON BinData value
b.subtype() the BinData subtype (0..255)
b.length() length of the BinData data in bytes
b.hex() the data as a hex encoded string
b.base64() the data as a base 64 encoded string
b.toString()

b = HexData(subtype,hexstr) create a BSON BinData value from a hex string
b = UUID(hexstr) create a BSON BinData value of UUID subtype
b = MD5(hexstr) create a BSON BinData value of MD5 subtype

o = new ObjectId() create a new ObjectId
o.getTimestamp() return timestamp derived from first 32 bits of the OID
o.isObjectId()
o.toString()
o.equals(otherid)
>

一些tips小结:

① 在Web页面查看MongoDB的相关信息

http://x.x.x.x:27017
You are trying to access MongoDB on the native driver port. For http diagnostic access, add 1000 to the port number
http://x.x.x.x:28017

② MongoDB远程连接配置

1.添加管理员账号

> use admin
switched to db admin
> db.addUser('tank','test');

2.配置mongodb.conf

#bind_ip = 127.0.0.1 //注释此行
auth = true //将此行前的注释去掉

3.重启mongodb

4.防火墙开放27017端口

iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 27017 -j ACCEPT

5.远程连接测试

$ mongo x.x.x.x:27017/db_name -u admin -p
……输入密码……

 

额外参考链接:

《 “MongoDB的相关安全问题” 》 有 4 条评论

  1. 创建集合
    http://wiki.jikexueyuan.com/project/mongodb/mongodb-create-collection.html
    http://www.runoob.com/mongodb/mongodb-create-collection.html
    `
    > db
    > show collections

    > db.createCollection(“mycollection”)
    { “ok” : 1 }
    > show collections

    > db.createCollection(“mycol”, { capped : true, autoIndexID : true, size : 6142800, max : 10000 } )
    { “ok” : 1 }
    > show collections

    > db.tutorialspoint.insert({“name” : “tutorialspoint”})
    > show collections
    `

    删除集合
    http://wiki.jikexueyuan.com/project/mongodb/mongodb-drop-collection.html
    `
    > show collections
    >db.mycollection.drop()
    true

    > show collections
    `
    MongoDB 插入文档
    http://www.runoob.com/mongodb/mongodb-insert.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注