SlideShare a Scribd company logo
It's a Dangerous World
MongoDB
Community Edition Security
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
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
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
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”
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
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
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
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
Secure connectivity to and between servers
Walk through enabling TLS
Configuration options
Java/PHP/Python code examples
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
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
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
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
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
self._role_mapping = {'AUTHORIZE': self.get_authorize_db, 'SCHEDULER': self.get_scheduler_db,
'PRACTITIONER': self.get_practitioner_db,
'PHARMACIST': self.get_pharmacist_db,
'AUDITOR': self.get_auditor_db}
def _get_database(self, type):
username = config[type]['username']
password = config[type]['password']
cert_path = config['security']['cert_path']
uri = "mongodb://%s:%s@%s:%s" % (
quote_plus(username), quote_plus(password), self._host, self._port)
return MongoClient(uri, ssl=True, ssl_ca_cert=cert_path)[self._db_name]
def get_database_by_role(self, role):
return self._role_mapping.get(role, None)()
def get_authorize_db(self):
if self._authorize_db is None:
self._authorize_db = self._get_database('mongo_authorize')
return self._authorize_db
Mini Clinic Python SSL connection
PHP
<?php
$MYCERT = "D:/software/mongodb-3.2.0/ssl/mongodb-cert.pem";
<!-- Load the certification file into stream context -->
$ctx = stream_context_create(array(
"ssl" => array(
"cafile" => $MYCERT
),
));
$config = parse_ini_file(‘../config.ini’);
$server = $config [‘server’];
$port= $config[‘port’];
$dbName = $config[‘dbname’];
$user = $config[‘user’];
$pwd = $config[‘password’];
<!-- Build URI -->
$mongo_uri =
"mongodb://".$user.":".$pwd."@".$server.":".$port."/".$dbName;
<!-- Create client connection with TLS connection settings -->
$conn = new MongoClient($mongo_uri,
array("ssl" => true),
array("context" => $ctx));
$db = $conn->selectDB($dbName);
<!-- validation query -->
$coll = new MongoCollection($db, 'sample');
echo "find documents: " . $coll->count();
$conn->close();
?>
Java @Bean
public SSLSocketFactory sslSocketFactory() throws Exception{
TrustManager[] trust = new TrustManager[] { new MyX509TrustManager() };
// load certificate file into key manager
KeyManager[] key = MyX509KeyManager.createKeyManager(new FileInputStream(sslCAKeyFile));
SSLContext ssl = SSLContext.getInstance("SSL");
ssl.init(key, trust, new java.security.SecureRandom());
return ssl.getSocketFactory(); // used below in MongoClientOptions
}
@Bean
public MongoClient mongo() throws Exception {
MongoClient client = null;
MongoClientOptions options = MongoClientOptions.builder().writeConcern(WriteConcern.JOURNALED)
.sslEnabled(true).sslInvalidHostNameAllowed(true)// debug for self-sign CA file
.socketFactory(sslSocketFactory()).build();
// get host, port, database, user, password from properties file
client = new MongoClient(Arrays.asList(new ServerAddress(host, port)),
Arrays.asList(MongoCredential.createCredential(username,database, password.toCharArray())),
options);
// Removed test code that was here to ‘prove’ connection
return client;
}
Authentication models
Username /
Password
Local CA
Certificates
File
Certificate
1. Challenge/Response
(SCRAM-SHA-1) – based on RFC5802)
2. x.509 Certificate (requires CA)
Slide 20
Client Authentication Comparisons
Authentication Method Clear Text Password Identity Location
Challenge/Response
(SCRAM-SHA-1)
No (Digest) Internal
x.509 Certificate No (Digital Signature) External
Client Authentication Examples
SCRAM-SHA-1
x.509 Certificate
FQDN
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
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
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
Slide 25
User and Role Management Example
db = db.getSiblingDB('admin');
//create scheduler
db.createRole(
{
"role": "scheduler",
"privileges": [
{
"resource": {"db": "mini_clinic","collection": "scheduler_patient"},
"actions": ["find"]
},
{
"resource": {"db": "mini_clinic","collection": "encounter"},
"actions": ["find","insert","update"]
}
],
"roles": []
}
);
//create scheduler user
db.dropUser("user_scheduler");
db.createUser(
{
"user": "user_scheduler",
"pwd": "ecwise.c1m",
"roles": [
{
"role": "scheduler",
"db": "admin"
}
]
}
);
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
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
Read only views
db = db.getSiblingDB('admin');
/* create View */
db.createView(
"scheduler_patient",
"patient",
{
$project:
{
"_id": 1,
"firstName": 1,
"lastName": 1
}
}
);
db.createView(
"practitioner_patient",
"patient",
{
$project:
{
"nationalID": 0
}
}
);
set13:PRIMARY> db.patient.findone({lastName : “Maddin”})
{ "_id" : ObjectId("5914108c8e034900016a5172"), "nationalID" : "1234-
5678-90", "firstName" : "Joe", "dob" : "1985-08-08", "lastName" :
"Maddin", "phone" : "400-800-1234", "gender" : "MALE" }
set13:PRIMARY> db.scheduler_patient.findone({lastName :
“Maddin”})
{ "_id" : ObjectId("5914108c8e034900016a5172"), "firstName" : "Joe",
"lastName" : "Maddin" }
set13:PRIMARY> db.practitioner_patient.findone({lastName :
“Maddin”})
{ "_id" : ObjectId("5914108c8e034900016a5172"), "firstName" : "Joe",
"dob" : "1985-08-08", "lastName" : "Maddin", "phone" : "400-800-
1234", "gender" : "MALE" }
// everything BUT national ID
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
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 ….
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!
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!
“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
“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
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); }
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) {
// ...
});
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)
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
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

More Related Content

PPTX
Securing Your Enterprise Web Apps with MongoDB Enterprise
PPTX
Introducing Stitch
PPTX
How Thermo Fisher is Reducing Data Analysis Times from Days to Minutes with M...
PPTX
Webinar: Compliance and Data Protection in the Big Data Age: MongoDB Security...
PPTX
Managing Multi-Tenant SaaS Applications at Scale
PPTX
Sizing MongoDB Clusters
PPTX
Getting Started with MongoDB Using the Microsoft Stack
PPTX
Managing Cloud Security Design and Implementation in a Ransomware World
Securing Your Enterprise Web Apps with MongoDB Enterprise
Introducing Stitch
How Thermo Fisher is Reducing Data Analysis Times from Days to Minutes with M...
Webinar: Compliance and Data Protection in the Big Data Age: MongoDB Security...
Managing Multi-Tenant SaaS Applications at Scale
Sizing MongoDB Clusters
Getting Started with MongoDB Using the Microsoft Stack
Managing Cloud Security Design and Implementation in a Ransomware World

What's hot (20)

PPTX
Performance Tipping Points - Hitting Hardware Bottlenecks
PPTX
Webinar: Choosing the Right Shard Key for High Performance and Scale
PPTX
Experian Health: Moving Universal Identity Manager from ANSI SQL to MongoDB
PDF
MongoDB Launchpad 2016: MongoDB 3.4: Your Database Evolved
PPTX
Cloud Backup Overview
PPTX
Sizing Your MongoDB Cluster
PPTX
Webinar: Enabling Microservices with Containers, Orchestration, and MongoDB
PPTX
A Free New World: Atlas Free Tier and How It Was Born
PDF
MongoDB Launchpad 2016: Moving Cybersecurity to the Cloud
PPTX
Webinar: Architecting Secure and Compliant Applications with MongoDB
PPTX
AWS Lambda, Step Functions & MongoDB Atlas Tutorial
PPTX
Introducing MongoDB Atlas
PDF
Building a Microservices-based ERP System
PPTX
Document Validation in MongoDB 3.2
PDF
Engineering an Encrypted Storage Engine
PPTX
Private Cloud Self-Service at Scale
PPTX
Building the Real-Time Performance Panel
PPTX
Practical Design Patterns for Building Applications Resilient to Infrastructu...
PPTX
MongoDB 3.4: Deep Dive on Views, Zones, and MongoDB Compass
PDF
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
Performance Tipping Points - Hitting Hardware Bottlenecks
Webinar: Choosing the Right Shard Key for High Performance and Scale
Experian Health: Moving Universal Identity Manager from ANSI SQL to MongoDB
MongoDB Launchpad 2016: MongoDB 3.4: Your Database Evolved
Cloud Backup Overview
Sizing Your MongoDB Cluster
Webinar: Enabling Microservices with Containers, Orchestration, and MongoDB
A Free New World: Atlas Free Tier and How It Was Born
MongoDB Launchpad 2016: Moving Cybersecurity to the Cloud
Webinar: Architecting Secure and Compliant Applications with MongoDB
AWS Lambda, Step Functions & MongoDB Atlas Tutorial
Introducing MongoDB Atlas
Building a Microservices-based ERP System
Document Validation in MongoDB 3.2
Engineering an Encrypted Storage Engine
Private Cloud Self-Service at Scale
Building the Real-Time Performance Panel
Practical Design Patterns for Building Applications Resilient to Infrastructu...
MongoDB 3.4: Deep Dive on Views, Zones, and MongoDB Compass
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
Ad

Similar to It's a Dangerous World (20)

PPTX
Low Hanging Fruit, Making Your Basic MongoDB Installation More Secure
PPTX
MongoDB World 2018: Low Hanging Fruit: Making Your Basic MongoDB Installation...
PPT
Jan 2008 Allup
PDF
Отчет Csa report RAPID7
PPTX
Securing MongoDB to Serve an AWS-Based, Multi-Tenant, Security-Fanatic SaaS A...
PDF
Gartner Security & Risk Management Summit 2018
PPTX
IT Infrastructure Through The Public Network Challenges And Solutions
PDF
MongoDB World 2019: New Encryption Capabilities in MongoDB 4.2: A Deep Dive i...
PPT
Protecting Your Key Asset – Data Protection Best Practices V2.0 Final
PPTX
Application of Machine Learning in Cybersecurity
PDF
Tips to Remediate your Vulnerability Management Program
PDF
13. Neville Varnham - PeopleSoft Cyber Security
PDF
EXPLORING WOMEN SECURITY BY DEDUPLICATION OF DATA
PPTX
OWASP_Top_Ten_Proactive_Controls_v2.pptx
PDF
OWASP Portland - OWASP Top 10 For JavaScript Developers
PPTX
Connection String Parameter Pollution Attacks
PDF
MongoDB .local Bengaluru 2019: New Encryption Capabilities in MongoDB 4.2: A ...
PPTX
Securing Your MongoDB Deployment
PPTX
Jon McCoy - AppSec-USA-2014 Hacking C#(.NET) Applications:Defend by Design
PPS
Hacking Client Side Insecurities
Low Hanging Fruit, Making Your Basic MongoDB Installation More Secure
MongoDB World 2018: Low Hanging Fruit: Making Your Basic MongoDB Installation...
Jan 2008 Allup
Отчет Csa report RAPID7
Securing MongoDB to Serve an AWS-Based, Multi-Tenant, Security-Fanatic SaaS A...
Gartner Security & Risk Management Summit 2018
IT Infrastructure Through The Public Network Challenges And Solutions
MongoDB World 2019: New Encryption Capabilities in MongoDB 4.2: A Deep Dive i...
Protecting Your Key Asset – Data Protection Best Practices V2.0 Final
Application of Machine Learning in Cybersecurity
Tips to Remediate your Vulnerability Management Program
13. Neville Varnham - PeopleSoft Cyber Security
EXPLORING WOMEN SECURITY BY DEDUPLICATION OF DATA
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP Portland - OWASP Top 10 For JavaScript Developers
Connection String Parameter Pollution Attacks
MongoDB .local Bengaluru 2019: New Encryption Capabilities in MongoDB 4.2: A ...
Securing Your MongoDB Deployment
Jon McCoy - AppSec-USA-2014 Hacking C#(.NET) Applications:Defend by Design
Hacking Client Side Insecurities
Ad

More from MongoDB (20)

PDF
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
PDF
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
PDF
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
PDF
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
PDF
MongoDB SoCal 2020: MongoDB Atlas Jump Start
PDF
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
PDF
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
PDF
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
PDF
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
PDF
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
PDF
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
PDF
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
PDF
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
PDF
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
PDF
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
PDF
MongoDB .local Paris 2020: Les bonnes pratiques pour sécuriser MongoDB
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Les bonnes pratiques pour sécuriser MongoDB

Recently uploaded (20)

PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Cloud computing and distributed systems.
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation theory and applications.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPT
Teaching material agriculture food technology
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
MYSQL Presentation for SQL database connectivity
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Machine learning based COVID-19 study performance prediction
Digital-Transformation-Roadmap-for-Companies.pptx
Cloud computing and distributed systems.
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Approach and Philosophy of On baking technology
Encapsulation theory and applications.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Teaching material agriculture food technology
The AUB Centre for AI in Media Proposal.docx
Spectral efficient network and resource selection model in 5G networks
Dropbox Q2 2025 Financial Results & Investor Presentation
MYSQL Presentation for SQL database connectivity
“AI and Expert System Decision Support & Business Intelligence Systems”
Mobile App Security Testing_ A Comprehensive Guide.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Advanced methodologies resolving dimensionality complications for autism neur...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

It's a Dangerous World

  • 1. It's a Dangerous World MongoDB Community Edition Security
  • 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
  • 16. self._role_mapping = {'AUTHORIZE': self.get_authorize_db, 'SCHEDULER': self.get_scheduler_db, 'PRACTITIONER': self.get_practitioner_db, 'PHARMACIST': self.get_pharmacist_db, 'AUDITOR': self.get_auditor_db} def _get_database(self, type): username = config[type]['username'] password = config[type]['password'] cert_path = config['security']['cert_path'] uri = "mongodb://%s:%s@%s:%s" % ( quote_plus(username), quote_plus(password), self._host, self._port) return MongoClient(uri, ssl=True, ssl_ca_cert=cert_path)[self._db_name] def get_database_by_role(self, role): return self._role_mapping.get(role, None)() def get_authorize_db(self): if self._authorize_db is None: self._authorize_db = self._get_database('mongo_authorize') return self._authorize_db Mini Clinic Python SSL connection
  • 17. PHP <?php $MYCERT = "D:/software/mongodb-3.2.0/ssl/mongodb-cert.pem"; <!-- Load the certification file into stream context --> $ctx = stream_context_create(array( "ssl" => array( "cafile" => $MYCERT ), )); $config = parse_ini_file(‘../config.ini’); $server = $config [‘server’]; $port= $config[‘port’]; $dbName = $config[‘dbname’]; $user = $config[‘user’]; $pwd = $config[‘password’]; <!-- Build URI --> $mongo_uri = "mongodb://".$user.":".$pwd."@".$server.":".$port."/".$dbName; <!-- Create client connection with TLS connection settings --> $conn = new MongoClient($mongo_uri, array("ssl" => true), array("context" => $ctx)); $db = $conn->selectDB($dbName); <!-- validation query --> $coll = new MongoCollection($db, 'sample'); echo "find documents: " . $coll->count(); $conn->close(); ?>
  • 18. Java @Bean public SSLSocketFactory sslSocketFactory() throws Exception{ TrustManager[] trust = new TrustManager[] { new MyX509TrustManager() }; // load certificate file into key manager KeyManager[] key = MyX509KeyManager.createKeyManager(new FileInputStream(sslCAKeyFile)); SSLContext ssl = SSLContext.getInstance("SSL"); ssl.init(key, trust, new java.security.SecureRandom()); return ssl.getSocketFactory(); // used below in MongoClientOptions } @Bean public MongoClient mongo() throws Exception { MongoClient client = null; MongoClientOptions options = MongoClientOptions.builder().writeConcern(WriteConcern.JOURNALED) .sslEnabled(true).sslInvalidHostNameAllowed(true)// debug for self-sign CA file .socketFactory(sslSocketFactory()).build(); // get host, port, database, user, password from properties file client = new MongoClient(Arrays.asList(new ServerAddress(host, port)), Arrays.asList(MongoCredential.createCredential(username,database, password.toCharArray())), options); // Removed test code that was here to ‘prove’ connection return client; }
  • 19. Authentication models Username / Password Local CA Certificates File Certificate 1. Challenge/Response (SCRAM-SHA-1) – based on RFC5802) 2. x.509 Certificate (requires CA)
  • 20. Slide 20 Client Authentication Comparisons Authentication Method Clear Text Password Identity Location Challenge/Response (SCRAM-SHA-1) No (Digest) Internal x.509 Certificate No (Digital Signature) External
  • 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
  • 25. Slide 25 User and Role Management Example db = db.getSiblingDB('admin'); //create scheduler db.createRole( { "role": "scheduler", "privileges": [ { "resource": {"db": "mini_clinic","collection": "scheduler_patient"}, "actions": ["find"] }, { "resource": {"db": "mini_clinic","collection": "encounter"}, "actions": ["find","insert","update"] } ], "roles": [] } ); //create scheduler user db.dropUser("user_scheduler"); db.createUser( { "user": "user_scheduler", "pwd": "ecwise.c1m", "roles": [ { "role": "scheduler", "db": "admin" } ] } );
  • 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
  • 28. Read only views db = db.getSiblingDB('admin'); /* create View */ db.createView( "scheduler_patient", "patient", { $project: { "_id": 1, "firstName": 1, "lastName": 1 } } ); db.createView( "practitioner_patient", "patient", { $project: { "nationalID": 0 } } ); set13:PRIMARY> db.patient.findone({lastName : “Maddin”}) { "_id" : ObjectId("5914108c8e034900016a5172"), "nationalID" : "1234- 5678-90", "firstName" : "Joe", "dob" : "1985-08-08", "lastName" : "Maddin", "phone" : "400-800-1234", "gender" : "MALE" } set13:PRIMARY> db.scheduler_patient.findone({lastName : “Maddin”}) { "_id" : ObjectId("5914108c8e034900016a5172"), "firstName" : "Joe", "lastName" : "Maddin" } set13:PRIMARY> db.practitioner_patient.findone({lastName : “Maddin”}) { "_id" : ObjectId("5914108c8e034900016a5172"), "firstName" : "Joe", "dob" : "1985-08-08", "lastName" : "Maddin", "phone" : "400-800- 1234", "gender" : "MALE" } // everything BUT national ID
  • 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

Editor's Notes

  • #4: 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.
  • #7: Don’t say “rights”
  • #10: Point out that HL7 is a standard
  • #11: 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
  • #13: 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
  • #21: 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.
  • #22: 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.
  • #23: It often helps to illustrate with code and/or architectural diagrams
  • #24: It often helps to illustrate with code and/or architectural diagrams