Speaker: Tom Spitzer, Vice President, Engineering, EC Wise, Inc.
Session Type: 40 minute main track session
Level: 200 (Intermediate)
Track: Security
MongoDB Community Server provides a wide range of capabilities for securing your MongoDB installation. In this session, we will focus on access control features, including authentication and authorization mechanisms, that enable you to enforce a least privilege model on user accounts. We will also discuss strategies for enabling and maintaining service and application accounts. Next we will present the encryption capabilities that are available in the community edition and discuss their benefits and possible shortcomings. Finally, we will talk about application level protections your developers can implement to keep risky code from getting to your MongoDB instance.
What You Will Learn:
- The workings of the MongoDB User Management Interface, the Authentication Database, basic Authentication mechanisms (SCRAM-SHA-1 and certificates), Roles, and Role Based Access controls – plus best practices for using these features to improve the security of your database.
- How to use TLS/SSL for transport encryption, application encryption options, and field level redaction.
- How injection attacks work and how to minimize the risk of injection attacks.
2. About: Tom Spitzer,
VP, Engineering, EC Wise
EC Wise builds/enables Complex Secure Solutions
Software Products / Service Delivery Platforms / Cyber Security
Key Practices: Security, Secure Software Development, Intelligent Systems, Data
Mature, International
Offices and customers: North and South America, Asia
~ 100 employees, senior experienced teams
Founded 1998
Prior to EC Wise I developed eCommerce and ERP systems
3. Learning Objectives
1. Describe how attackers are able to compromise other people’s data
2. Configure MongoDB instances securely
3. Manage users, roles, and privileges, so that when a user logs in, that user has
access to a set of role based privileges
4. Encrypt data in transit
5. Have an intelligent conversations with your organization about locking down
your MongoDB instances
4. Problem Scope: Intel Survey (2015)
Respondents who suffered one data breach experienced an
average of six significant breaches
In 68% of these incidents, the data exfiltrated from the
network was serious enough to require public disclosure or
have a negative financial impact
Internal actors responsible for 43% of data loss, (half
accidental)
Ratio (of internal actors) higher in Asia Pacific than U.S. or Europe.
Theft of unencrypted physical media is still quite common -
40% of exfiltrations
25% of data exfiltrations used file transfer or tunneling
protocols, such as FTP or SCP.
32% of data exfiltrations were encrypted.
While MSFT Office docs were the most common format
stolen (25%), PII from customers and employees was the
number one target (62%)
No indication of increased risk with cloud applications.
Our focus today is going to be on
protecting data in MongoDB
databases, though as you can
see exfiltration of documents is a
big problem as well
5. Common attacks
Ransomware – “27,000 MongoDB servers” in January, WannaCry in May
Of course, affected MongoDB servers did not have authentication enabled!
“NoSQL Injection”
Organized data breaches via “Advanced Persistent Threats”
6. Slide 6
Common Weaknesses / Mitigations - Access
Weaknesses
Authentication weak or not enabled
Overly permissive, inappropriate, and
unused privileges
Abuse & lax management of privileged
and service accounts
e.g. do DBAs really require always-on
access to application data?
Mitigations
Least privilege
“Strong” authentication
Multiple MongoDB options
Role Based Access Control
Account monitoring,
especially for servers
7. Slide 7
Common Weaknesses / Mitigations
– Surface Area
Weaknesses
Lack of Control of Info Assets
Storage media not secured
Too much info generally available
Mitigations
Inventory – what, where, how
Reduce surface area
Dispose of data that is no
longer needed;
(archive / delete)
Devalue data through encryption,
tokenization, masking
Pay attention to key management
8. Slide 8
Common Weaknesses / Mitigations – Practices
Weaknesses
Failure to apply patches
Risky DB features enabled
Weak application security
Insufficient/incomplete audit trails
Can result in SOX, HIPAA, and GDPR violations
as well as failure to see breaches
Mitigations
Create patch friendly environment
Disable risky DB features
-- noscripting
Take advantage of OWASP tools,
strategies
Move controls closer to the data itself
Enable database and network auditing
Have somebody do forensics
Consider DLP or SIEM
9. Introducing the Mini-Clinic
(based on HL7 Fast Healthcare Interoperability Resources)
Obviously, a medical clinic needs to be secure
Roles – Scheduler, Practioner, Pharmacist, Auditor
Objects – Patient, Encounter, Observation, Prescription
Operations – Schedule Encounter, Make Diagnosis, Prescribe Medication
Mini-Clinic
Website
Mini-Clinic Restful
Services MongoDB
10. Secure connectivity to and between servers
Walk through enabling TLS
Configuration options
Java/PHP/Python code examples
11. Configuration flow for topology/script on next slides
analysis MongoDB SSL configuration
Security Configuration
Engineer
Create local CA
Generate PK
and CSR for
Server 1
Generate PK
and CSR for
Server 2
Generate PK
and CSR for
Server 3
Submit Server 1
CSR to CA to get
Cert
Submit Server 2
CSR to CA to get
Cert
Submit Server 3
CSR to CA to get
Cert
Concatenate
Server 1 PK and
Cert into
MongoDB .pem file
Concatenate
Server 2 PK and
Cert into
MongoDB .pem file
Concatenate
Server 3 PK and
Cert into
MongoDB .pem file
Update
Server 1
Config file
Update
Server 2
Config File
Update
Server 3
Config File
X.509 setup for Replica Set
Generate PK
and CSR for
client
X.509 setup for Client
Submit Client
CSR to CA to
get Cert
Concatenate Client
PK and Cert into
MongoDB .pem file
Create
MongoDB
User
corresponding
to CERT
Restart
MongDB and
connect
MongoDB
SSL
Setup
CSR
CERT
CERT
PK
CSR
CSR
PK
CSR
PK
CSR
CERT
PK
CERT
CA: Certificate Authority
CSR: Certificate Signing Request
PK: Private Key
Cert: Certificate
12. TLS (supersedes SSL)
CRUD API calls over TLS
Internal Traffic over TLS
CA Certificates File
Server Key &
Certificate PEM File
DB Server 1
DriverClient
Machine
CA Certificates File
CA Certificates File
Server Key &
Certificate PEM File
DB Server 3
CA Certificates File
Server Key &
Certificate PEM File
DB Server 2
13. SSL/TLS configuration – Server .pem files
# Initialize CA by creating PK for it
$ openssl genrsa -out CAKey.key -aes256
# Create CA certificate
$ openssl req -x509 -new -extensions v3_ca -key CAKey.key -out CA-cert.crt
# create key file and Certificate Signing Request for each server
# will prompt for information used to create Distinguished Name or DN
# Country, State/Province; Locality; Organzation Name; Org Unit; Common Name; Email
$ openssl req -new -nodes -newkey rsa:2048 -keyout serverX.key -out serverX.csr
# have CA "sign" each server's CSR and generate server's public Cert
$openssl x509 -CA ./CA/CA-cert.crt -CAkey ./CA ./CA/CAkey.key -CAcreateserial -req
-in ./CSR/serverX.csr - out ./CERTS/serverX.crt
# create .pem file for each server
$ cat serverX.key serverX.crt > serverX.pem
# copy .pem and host CERT file to config directory
$ cp serverX.pem CA-cert.crt /mongodb/config/
Note: this creates a self-signed certificate,
which is not usually recommended. For
production you usually want a CA to provde the
cert, so you run the openSSL command to
create a certificate signing request, and send it
to your CA.
This process is more fully explained at
OpenSSL Essentials
#update MongDB Config file with SSL info
net:
port:27017
bindIP: 10.1.1.1
ssl:
mode: requireSSL OR preferSSL
PEMKeyFile: /mongodb/config/serverX.pem
CAFile: /mongodb/config/CA-cert.crt
clusterFile: /mongodb/config/serverX.pem
security:
custerAuthMode: x509
14. SSL/TLS configuration – Client .pem file
# generate client key and CSR, again it will prompt for DN components
# note that DN has to be different from server DN, can use different Org Unit
$ openssl req -new -nodes -newkey rsa:2048 -keyout rootuser.key -out rootuser.csr
# submit client CSR to CA for signing and Cert generation
$ openssl x509 - CA ./CA/CA-cert.crt -CAKey ./CA/CAKey -CAcreateserial
-req -in ./CSR/rootuser.csr -out ./CERTS/rootuser.crt
# concatenate client .pem
$ cat mongokey/rootuser.key ssl/CERTS/rootuser.crt > mongokey/rootuser.pem
# get client Cert subject details
$ openssl x509 -in mongokey/rootuser.pem -infomr PEM -subject -nameopt RFC2253
[subject=emailAddress=tspitzer@ecwise.com,CN=root,OU=ECWiseClients,O=ECWise,L=SR,ST=CA,C=US]
// create MongoDB users with root role for subject
rep1:Primary> db.getSiblingDB("$external").runCommand({
... createUser:"emailAddress=tspitzer@ecwise.com,CN=root,OU=ECWiseClients,O=ECWise,L=SR,ST=CA,C=US"
... roles [{role: "root", db: "admin"}]
... })
Note: consider secure
repository for key storage, e.g.
keystore service in Java
15. SSL/TLS configuration – restart with SSL
Restart mongod
[ts@SRDevLnxSvr02 ~]$ mongod -f /etc/mongod.conf
Provide CERT to client , and connect with SSL
[usert@Client ~]$ mongo --ssl --host server1 –sslPEMKeyFile ./mongokey/rootuser.pem --sslCAFile=CACert.crt
22. Enable authentication, create user accounts
Start MongoDB without access control
Connect in instance
Create user administrator
Restart instance with access control
$ mongod -f /etc/mongod.conf
Connect and authenticate as user administrator
mongo --ssl --host mongod_host --sslCAFile=/etc/ssl/mongodb.pem
-uUserAdmin -ppassword abc123
Create users
use admin
db.createUser(
{
user: "UserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
in /etc/mongod.conf
security.authorization: enabled
23. Define roles, scope privileges to roles
Privilege allows an action on a resource.
MongoDB defines a “bunch” of privileged operations.
Roles are defined pairings of resources and actions that you can assign users
Sixteen built-in roles, you have probably read about them
read, readWrite, dbAdmin, clusterAdmin, backup, restore, etc..
Create custom roles, assign users to roles per the scripts on following slides
class Authorization Model
Permission
Resource
Role
Action
User
24. Mini Clinic Role Mapping
Role Data
Patient Encounters Observation
Medication
Order Medication
CUD R CUD R CUD R CUD R CUD R
Scheduler
√ (only
name) √ √
Practitioner
√ (no
national
ID) √ √ √ √ √ √
Pharmacist √ √ √ √
Auditor √ √ √ √ √ √ √ √ √ √
CUD = Create/Update/Delete
R = Read
26. Router
Single Public Access
Shard + Replication set
Shard + Replication set
Shard + Replication set
Configure Server
Replication Set
Application
Mongo DB Cluster
Internal Network behind firewall
Authentication with account & password
Internal Authentication between nodes of cluster
With Key File (or X.509 certification)
VPN Access
Maintenance
Admin user
VPN Authentication
Network and OS considerations
DBs on separate subnet, not accessible to internet
Amazon VLAN/VPCs
Dedicated OS users for DB and App Services
27. Read only views
Enable administrators to define a query that is materialized at runtime
db.createView(<name>, <collection>, <pipeline>, <options>)
where pipeline is an array that consists of the aggregation pipeline stage
Admins can define permissions on who can access the views
Use these Views in your applications to provide another level of security
29. Slide 29
Introduction to OWASP
Open Web Application Security Project
OWASP “Top Ten” includes
Injection; Cross-site scripting; Security Misconfiguration
Sensitive Data Exposure; Cross Site Request Forgery
Guidelines for Developing, Reviewing and Testing secure code
“Cheat sheets”
Libraries that developers can use
Testing tools like Zed Attack Proxy
30. Injection Attacks - History
Became “popular” with simple web form applications backed by MySQL
“SQL Injection”
Exploits apps that pass text through without validation
i.e. web form prompts for value, exploiter enters valid SQL expression
SELECT <columns> FROM <table> WHERE <value> = ‘abc123' OR 1
SELECT <columns> FROM <table> WHERE <value> = ‘abc123'; UPDATE <table> SET
<column> = <'value'> WHERE ….
31. Injection Attacks (JSON Injection from PHP Array)
Well behaved user
//login page HTTP Post payload
username=tspitzer&password=MongoDBWorld
//Common PHP Code processes this POST with //
associative array (name – value pairs)
db->logins->
find(array("username"=>$_POST["username"],
"password"=>$_POST[password"]));
//which with my legitimate payload resolves
// with JSON encoding to
db->logins.find({username: 'tspitzer', password:
MongDBWorld'})
Malicious user
//if I enter [$ne]=1 as both my username
// and password; the payload becomes
username[$ne]=1&password[$ne]=1
//PHP translates this to
db>logins->
find(array("username" => array("$ne" =>
1), "password" => array($ne" => 1));
//which encodes to the MongoDB query
db.logins.find({username: { $ne : 1 },
password: { $ne: 1 } })
// which will return all users in the logins collection!
32. Injection Attacks (JSON Injection from PHP Array)
Well behaved user
//login page HTTP Post payload
username=tspitzer&password=MongoDBWorld
//Common PHP Code processes this POST with //
associative array (name – value pairs)
db->logins->
find(array("username"=>$_POST["username"],
"password"=>$_POST[password"]));
//which with my legitimate payload resolves
// with JSON encoding to
db->logins.find({username: 'tspitzer', password:
MongDBWorld'})
Malicious user
//if I enter [$ne]=1 as both my username
// and password; the payload becomes
username[$ne]=1&password[$ne]=1
//PHP translates this to
db>logins->
find(array("username" => array("$ne" =>
1), "password" => array($ne" => 1));
//which encodes to the MongoDB query
db.logins.find({username: { $ne : 1 },
password: { $ne: 1 } })
// which will return all users in the logins collection!
33. “OR” Injection
//string concatenation example, our login page code looks like
string query = "{username: '" + post_username + "', password: '" + post_password + "' }"
//with a well behaved user we get the query
{username: 'tspitzer', password: MongoDBWorld' }
// but if the attacker enters
Username - jwalker', $or[{}, {'a':'a Password - '}], $comment: 'stealing data from MongoDB'
// the query becomes
{ username: 'jwalker', $or: [ {}, { 'a': 'a', password: ''} ],
$comment: 'stealing data from MongoDB' }
//as long as jwalker is a valid user name, this will reveal all account information
34. “OR” Injection
//string concatenation example, our login page code looks like
string query = "{username: '" + post_username + "', password: '" + post_password + "' }"
//with a well behaved user we get the query
{username: 'tspitzer', password: MongoDBWorld' }
// but if the attacker enters
Username - jwalker', $or[{}, {'a':'a Password - '}], $comment: 'stealing data from MongoDB'
// the query becomes
{ username: 'jwalker', $or: [ {}, { 'a': 'a', password: ''} ],
$comment: 'stealing data from MongoDB' }
//as long as jwalker is a valid user name, this will reveal all account information
35. JavaScript Injection; $where exploits
• String request parameters to server side java script
• Prompt for Year; Attacker enters
– 2015’;while(1);var%20foo’=bar
– While(1) will execute, constitutes denial of service
• db.myCollection.find( { active: true, $where: function() { return obj.credits - obj.debits <
$userInput; } } );;
– 0;var date=new Date(); do{curDate = new Date();}while(curDate-date<10000)
– function() { return obj.credits - obj.debits < 0;var date=new Date(); do{curDate = new
Date();}while(curDate-date<10000); }
36. Most Effective Deterrent is Input Validation
Seems obvious, but its still a problem
Whitelist user entries, force them to pick from list (yes, difficult with passwords)
Blacklist – look for keywords and operators in entered strings
$or, $ne, $where, etc.
Don’t let users create passwords that include these strings
There’s even a library: mongo-sanitize
var sanitize = require('mongo-sanitize');
// The sanitize function will strip out
// any keys that start with '$' in the input,
var clean = sanitize(req.params.username);
Users.findOne({ name: clean }, function(err, doc) {
// ...
});
37. Slide 37
How to Discourage Application Attacks
Suppress Error Messages in web apps
Monitor Database Activity – Put logs into SIEM and analyze
Disable Unnecessary Database Capabilities (--noscripting)
Enforce Least Privilege Model
Apply Vendor Patches Regularly
Conduct Penetration Testing Against Database Connected Applications
Adopt network behavioral security technologies (e.g. DarkTrace)
38. Slide 38
Testing and Validation
Code review – see OWASP code review guides
OWASP Testing Guide
ZAP – web app pen test tool, OWASP flagship project
Commercial “Pen” testing services
39. Architecting a secure system
Consider the whole application from the UI/service initiation down to the DB
A layered security strategy will be most effective
Break down organizational barriers – work across teams
Always encrypt network traffic
Decide on authentication model: standing alone vs. integrated with corporate
Think carefully about Roles
Hinweis der Redaktion
The learning objectives are the guiding points to everything you include in your session, so it makes sense to use them as your starting point. LOs should be focused, discrete and oriented toward the attendee. They should also be active, stating what attendees should be able to do with the information in the talk. (Learning objectives that state an attendee should "understand" something are NOT active. :-) ). As an example of a good learning objective, for a session on MongoDB, Kubernetes and Docker containers a learning objective could be “Following this talk attendees should be able to define a highly available MongoDB deployment using Kubernetes services, replica sets and config maps”. The learning objectives should be presented to the audience as the first slide following the title and should be one of the few slides with text. We recommend three to five LOs.
Don’t say “rights”
Point out that HL7 is a standard
One of the best way to describe solving a problem is describe how you solved it, and you have probably tried 2-3 ways of solving it before you figured out the right answer. Describe that process here. It often helps to illustrate with code and/or architectural diagrams
Use FQDNs and ensure used hostname matches certificate CN
PEM: Privacy Enhancement Mail container format (base64 encoded format)
"SSL cipher selection": non-documented flag "--sslCipherConfig" see: https://jira.mongodb.org/browse/SERVER-16073
net.ssl.mode: disabled | allowSSL | preferSSL | requireSSL
For Kerberos, when running kinit to get the initial ticket from the KDCs Ticket Granting Service, the password is never sent over the wire - instead, the TGS uses it's knowledge of the client's password to encrypt the TGS's new sesion key. On the client side, it's prompted password it used to decrypt the TGS session key. As a result, the password is not sent over the wire.
In 3.4, for x.509 Certificate authentication passing the ‘user’ field to auth() is not necessary as it is implied by the subject name in the client certificate file.
It often helps to illustrate with code and/or architectural diagrams
It often helps to illustrate with code and/or architectural diagrams