Upload
others
View
4
Download
0
Embed Size (px)
Citation preview
Low Hanging Fruit:
Securing Your Basic
MongoDB Installation
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
~ 60 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. Know how to use Read Only Views to improve security
6. Have an intelligent conversations with your organization about locking down
your MongoDB instances
Top Risks / Common attacks
Ransomware – 2017 - “27,000 MongoDB servers” in January, WannaCry in May
Of course, affected MongoDB servers did not have authentication enabled!
DDOS, Steganography, “SQL/NoSQL Injection”, system hijacking
Political destabilization / infrastructure compromise
Massive data theft via “Advanced Persistent Threats”: Experian, Yahoo, Target …
Slide 5
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
Access restrictions
Role Based Access Control
Account monitoring,
especially for servers
Slide 6
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 7
Common Weaknesses / Mitigations – Practices
Weaknesses
Failure to apply patches
Risky DB features enabled
Weak application security
Lack of visibility into DB
and network activity
Mitigations
Create patch friendly environment
Disable risky DB features
-- noscripting
Take advantage of OWASP tools,
strategies
Move controls closer to the data itself
Log sensitive operations
Enterprise: Consider DLP or SIEM
I. Secure connectivity to and between servers
Secure Connectivity reduces Surface Area
MongoDB TLS (SSL successor) hierarchy
Walk through enabling TLS
Configuration options
Code examples
PKI is acronym laden!
MongoDB
TLS Hierarchy
CRUD API calls over TLS
Internal Traffic over TLS
CA Certificates File
Server Key &
Certificate PEM FileDB Server 1
Dri
ver
Client
Machine
CA Certificates File
CA Certificates File
Server Key &
Certificate PEM File
DB Server 3
CA Certificates File
Server Key &
Certificate PEM FileDB Server 2
MongoDB
TLS protected
communications
SSL/TLS configuration – Create 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; Organization 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: example creates self-signed certificate,
not recommended for production. For
production, have a CA create a cert; to do so
run the openSSL command to create a CSR,
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
Note:.pem is a
container file format
SSL/TLS configuration – Create 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 -inform PEM -subject -nameopt RFC2253
[[email protected],CN=root,OU=ECWiseClients,O=ECWise,L=SR,ST=CA,C=US]
Note: consider secure
repository for key storage, e.g.
keystore service in Java or
third party key manager; also
Protect .pem file directories
Note: be sure that client and
server certs have different
DNs, i.e. that at least one DN
component, or RDN differs
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
II. Authentication: Available Strategies, Details Follow
Username /
Password
Local CA
Certificates
File
Certificate
1. Challenge/Response(SCRAM-SHA-1) – based on RFC5802)
2. x.509 Certificate (requires CA)
Authentication Method Clear Text Password Identity Location
Challenge/Response
(SCRAM-SHA-1)No (Digest) Internal
x.509 Certificate No (Digital Signature) External
Authentication Strategy Comparisons
Addresses
“Weak Authentication”
vulnerability
SCRAM-SHA-1:
Enable authentication, create 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 additional users
use admin
db.createUser(
{
user: "UserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
in /etc/mongod.conf
security.authorization: enabled
Slide 17
Note Client vs. Member
authentication capabilities
Authentication
using x.509 Certs
x.509 authentication: Create,assign, enable Certs
Create local certification authority or use third party
Generate and sign certificates for client and servers in replica set
Server and client certs must differ in organization part of DNs
RS member O, OU, and DC components must match
Start MongoDB replica set instances without access control
Initialize replica set
Update config.json
Restart replica set in x.509 mode
mongod --replSet set509 --port $mport --dbpath ./db/$host \
--sslMode requireSSL --clusterAuthMode x509 --sslCAFile root-ca.pem \
--sslAllowInvalidHostnames --fork --logpath ./db/${host}.log \
--sslPEMKeyFile ${host}.pem --sslClusterFile ${cluster}.pem
$mongo
...
> db.getSiblingDB("$external").auth(
{
mechanism: "MONGODB-X509",
user: "CN=client1,OU=MyClients,O=EC Wise,
L=Chengdu,ST=GD,C=CN" }
);
> db.test.find()
Client Authentication Examples
SCRAM-SHA-1 x.509 Certificate
FQDN
$ mongo
...
> db.getSiblingDB("admin").auth(
{
mechanism: "SCRAM-SHA-1",
user: "dbmaster",
pwd: "adminpasswd123",
digestPassword: true
}
);Client names must
match DN in cert
III. User & Role Management in MongoDB
Addresses Overly permissive, inappropriate, and unused privileges
vulnerability
Enable Access Control for authentication
Set up users and roles, applicable to both humans and services
Enforce the Least Privilege strategy we discussed earlier
Bind users and roles to machines or (sub)networks with
Authentication Restriction
Use Roles to Manage Privilege Assignments
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
User & Role Examples based on Mini-Clinic app*
Obviously, a medical clinic needs to be secure
Roles – Scheduler, Practitioner, Pharmacist, Auditor
Objects – Patient, Encounter, Observation, Prescription
Operations – Schedule Encounter, Make Diagnosis, Prescribe Medication
Mini-Clinic Website
Mini-Clinic Restful Services MongoDB
*based on
HL7 Fast Healthcare Interoperability Resources
Mini Clinic Role Mapping
Role \ Data
Patient Encounters ObservationMedication
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 24
User and Role Management Examplesdb = 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": []
“authenticationRestrictions”: [{ “clientSource”: [“192.168.17.6”,
“127.0.0.1”] ,“serverAddress”: [“10.10.10.0/24”,
“127.0.0.1”] }] }
);
//create scheduler userdb.dropUser("user_scheduler");db.createUser(
{"user": "user_scheduler","pwd": "ecwise.c1m","roles": [
{"role": "scheduler",
"db": "admin““authenticationRestrictions”:
[{“clientSource”: [“192.168.17.6”, “127.0.0.1”] ,
“serverAddress”: [“10.10.10.0/24”, “127.0.0.1”] }]
}]
});
DBs on separate subnet, not accessible to internet
Amazon VLAN/VPCs
Dedicated OS users for DB and App Services
Localhost Default (3.6)
Use BindIP to tell MongoDB
any other adapter and sockets to listen to
IP Whitelisting (3.6)
(enhances authentication)
RouterSingle Public Access
Shard + Replication set
Shard + Replication set
Shard + Replication set
Configure Server Replication Set
Application
Mongo DB ClusterInternal Network behind firewall
Authentication with account & password
Internal Authentication between nodes of clusterWith Key File (or X.509 certification)
VPN AccessMaintenance
Admin user
VPN Authentication
IV. Network/OS considerations
You’re mainly addressing
“Surface Area” risks, i.e.
limiting areas of exposure
V. MongoDB Atlas has Security Baked In
TLS/SSL enabled by default with mongodb+srv connection string
Authentication, and authorization via SCRAM
Network isolation and VPC Peering on AWS
IP whitelists using Authentication Restriction
Encrypted storage volumes
Roles not definable: create users through Atlas UI and assign them to
predefined roles
VI. Read Only Views
Addresses both “Surface area reduction” and “weak authorization” risks
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 viewsdb = db.getSiblingDB('admin');
/* create View */db.createView(
"scheduler_patient","patient",{
$project:{
"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
VII. 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
Slide 30
Thank You
Closing comments/questions?
For follow up:
Tom Spitzer
@tspitzer_ecwise
https://www.linkedin.com/in/tom-spitzer-74643/
415-572-4156
Appendix
Examples and References
Some additional code examples and web
references are provided
MongoDB x.509 authentication settings
{
"db" : "mongodb://localhost:27001/db-name?ssl=true",
"dbOpts": {
"user": "[email protected],CN=XYZ,OU=XYZ-Client,O=XYZ,L=XYZ,ST=XYZ,C=XYZ",
"auth": { "authMechanism": "MONGODB-X509" },
"server": {
"sslValidate": false,
"sslKey": {"filePath": "/absolute/path/to/db-user.pem"},
"sslCert": {"filePath": "/absolute/path/to/db-user.crt"}
}
}
}
Cyber-Security References
• CyberCriminals and their APT and AVT Techniques
• InfoSec Institute: Anatomy of an APT Attack: Step by Step Approach
• Forrester Wave: Data Loss Prevention Suites Q4, 2016
• Data Guardian’s Definitive Guide to Data Loss Prevention
• How to Avoid Ransomware attacks against MongoDB
• InfoWorld Guide to MongoDB Security
• MongoDB Security Checklist (product documentation)
• Download link for MongoDB Security Reference Architecture