forked from mongodb/mongo-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_ssl.py
More file actions
582 lines (501 loc) · 23.4 KB
/
test_ssl.py
File metadata and controls
582 lines (501 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
# Copyright 2011-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for SSL support."""
import os
import socket
import sys
import unittest
sys.path[0:0] = [""]
try:
from ssl import CertificateError
except ImportError:
# Backport.
from pymongo.ssl_match_hostname import CertificateError
from urllib import quote_plus
from nose.plugins.skip import SkipTest
from pymongo import MongoClient, MongoReplicaSetClient
from pymongo.common import HAS_SSL, validate_cert_reqs
from pymongo.errors import (ConfigurationError,
ConnectionFailure,
OperationFailure)
from test import host, port, pair, version, db_user, db_pwd, AuthContext
from test.utils import remove_all_users
CERT_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'certificates')
CLIENT_PEM = os.path.join(CERT_PATH, 'client.pem')
CA_PEM = os.path.join(CERT_PATH, 'ca.pem')
SIMPLE_SSL = False
CERT_SSL = False
SERVER_IS_RESOLVABLE = False
MONGODB_X509_USERNAME = (
"C=US,ST=California,L=Palo Alto,O=,OU=Drivers,CN=client")
# To fully test this start a mongod instance (built with SSL support) like so:
# mongod --dbpath /path/to/data/directory --sslOnNormalPorts \
# --sslPEMKeyFile /path/to/pymongo/test/certificates/server.pem \
# --sslCAFile /path/to/pymongo/test/certificates/ca.pem \
# --sslCRLFile /path/to/pymongo/test/certificates/crl.pem \
# --sslWeakCertificateValidation
# Also, make sure you have 'server' as an alias for localhost in /etc/hosts
#
# Note: For all tests to pass with MongoReplicaSetClient the replica
# set configuration must use 'server' for the hostname of all hosts.
def is_server_resolvable():
"""Returns True if 'server' is resolvable."""
socket_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(1)
try:
try:
socket.gethostbyname('server')
return True
except socket.error:
return False
finally:
socket.setdefaulttimeout(socket_timeout)
if HAS_SSL:
import ssl
# Check this all once instead of before every test method below.
# Is MongoDB configured for SSL?
try:
MongoClient(host, port, connectTimeoutMS=100, ssl=True)
SIMPLE_SSL = True
except ConnectionFailure:
pass
# Is MongoDB configured with server.pem, ca.pem, and crl.pem from
# mongodb jstests/lib?
try:
MongoClient(host, port, connectTimeoutMS=100, ssl=True,
ssl_certfile=CLIENT_PEM)
CERT_SSL = True
except ConnectionFailure:
pass
if CERT_SSL:
SERVER_IS_RESOLVABLE = is_server_resolvable()
if SIMPLE_SSL or CERT_SSL:
ssl_auth_ctx = AuthContext(ssl=True, ssl_certfile=CLIENT_PEM)
if ssl_auth_ctx.auth_enabled:
ssl_auth_ctx.add_user_and_log_in()
else:
ssl_auth_ctx = None
class TestClientSSL(unittest.TestCase):
def test_no_ssl_module(self):
# Test that ConfigurationError is raised if the ssl
# module isn't available.
if HAS_SSL:
raise SkipTest(
"The ssl module is available, can't test what happens "
"without it."
)
# Explicit
self.assertRaises(ConfigurationError,
MongoClient, ssl=True)
self.assertRaises(ConfigurationError,
MongoReplicaSetClient, replicaSet='rs', ssl=True)
# Implied
self.assertRaises(ConfigurationError,
MongoClient, ssl_certfile=CLIENT_PEM)
self.assertRaises(ConfigurationError,
MongoReplicaSetClient,
replicaSet='rs',
ssl_certfile=CLIENT_PEM)
def test_config_ssl(self):
self.assertRaises(ConfigurationError, MongoClient, ssl='foo')
self.assertRaises(ConfigurationError,
MongoClient,
ssl=False,
ssl_certfile=CLIENT_PEM)
self.assertRaises(TypeError, MongoClient, ssl=0)
self.assertRaises(TypeError, MongoClient, ssl=5.5)
self.assertRaises(TypeError, MongoClient, ssl=[])
self.assertRaises(ConfigurationError,
MongoReplicaSetClient, replicaSet='rs', ssl='foo')
self.assertRaises(ConfigurationError,
MongoReplicaSetClient,
replicaSet='rs',
ssl=False,
ssl_certfile=CLIENT_PEM)
self.assertRaises(TypeError,
MongoReplicaSetClient, replicaSet='rs', ssl=0)
self.assertRaises(TypeError,
MongoReplicaSetClient, replicaSet='rs', ssl=5.5)
self.assertRaises(TypeError,
MongoReplicaSetClient, replicaSet='rs', ssl=[])
self.assertRaises(IOError, MongoClient, ssl_certfile="NoSuchFile")
self.assertRaises(TypeError, MongoClient, ssl_certfile=True)
self.assertRaises(TypeError, MongoClient, ssl_certfile=[])
self.assertRaises(IOError, MongoClient, ssl_keyfile="NoSuchFile")
self.assertRaises(TypeError, MongoClient, ssl_keyfile=True)
self.assertRaises(TypeError, MongoClient, ssl_keyfile=[])
self.assertRaises(IOError,
MongoReplicaSetClient,
replicaSet='rs',
ssl_keyfile="NoSuchFile")
self.assertRaises(IOError,
MongoReplicaSetClient,
replicaSet='rs',
ssl_certfile="NoSuchFile")
self.assertRaises(TypeError,
MongoReplicaSetClient,
replicaSet='rs',
ssl_certfile=True)
# Test invalid combinations
self.assertRaises(ConfigurationError,
MongoClient,
ssl=False,
ssl_keyfile=CLIENT_PEM)
self.assertRaises(ConfigurationError,
MongoClient,
ssl=False,
ssl_certfile=CLIENT_PEM)
self.assertRaises(ConfigurationError,
MongoClient,
ssl=False,
ssl_keyfile=CLIENT_PEM,
ssl_certfile=CLIENT_PEM)
self.assertRaises(ConfigurationError,
MongoReplicaSetClient,
replicaSet='rs',
ssl=False,
ssl_keyfile=CLIENT_PEM)
self.assertRaises(ConfigurationError,
MongoReplicaSetClient,
replicaSet='rs',
ssl=False,
ssl_certfile=CLIENT_PEM)
self.assertRaises(ConfigurationError,
MongoReplicaSetClient,
replicaSet='rs',
ssl=False,
ssl_keyfile=CLIENT_PEM,
ssl_certfile=CLIENT_PEM)
if HAS_SSL:
self.assertRaises(
ConfigurationError, validate_cert_reqs, 'ssl_cert_reqs', 3)
self.assertRaises(
ConfigurationError, validate_cert_reqs, 'ssl_cert_reqs', -1)
self.assertRaises(
ConfigurationError, validate_cert_reqs, 'ssl_cert_reqs', 'foo')
self.assertEqual(
validate_cert_reqs('ssl_cert_reqs', None), None)
self.assertEqual(
validate_cert_reqs('ssl_cert_reqs', ssl.CERT_NONE),
ssl.CERT_NONE)
self.assertEqual(
validate_cert_reqs('ssl_cert_reqs', ssl.CERT_OPTIONAL),
ssl.CERT_OPTIONAL)
self.assertEqual(
validate_cert_reqs('ssl_cert_reqs', ssl.CERT_REQUIRED),
ssl.CERT_REQUIRED)
self.assertEqual(
validate_cert_reqs('ssl_cert_reqs', 0), ssl.CERT_NONE)
self.assertEqual(
validate_cert_reqs('ssl_cert_reqs', 1), ssl.CERT_OPTIONAL)
self.assertEqual(
validate_cert_reqs('ssl_cert_reqs', 2), ssl.CERT_REQUIRED)
self.assertEqual(
validate_cert_reqs('ssl_cert_reqs', 'CERT_NONE'),
ssl.CERT_NONE)
self.assertEqual(
validate_cert_reqs('ssl_cert_reqs', 'CERT_OPTIONAL'),
ssl.CERT_OPTIONAL)
self.assertEqual(
validate_cert_reqs('ssl_cert_reqs', 'CERT_REQUIRED'),
ssl.CERT_REQUIRED)
class TestSSL(unittest.TestCase):
def setUp(self):
if not HAS_SSL:
raise SkipTest("The ssl module is not available.")
if sys.version.startswith('3.0'):
raise SkipTest("Python 3.0.x has problems "
"with SSL and socket timeouts.")
if ssl_auth_ctx and ssl_auth_ctx.auth_enabled:
raise SkipTest("Can't test with auth enabled.")
def test_simple_ssl(self):
# Expects the server to be running with ssl and with
# no --sslPEMKeyFile or with --sslWeakCertificateValidation
if not SIMPLE_SSL:
raise SkipTest("No simple mongod available over SSL")
client = MongoClient(host, port, ssl=True)
response = client.admin.command('ismaster')
if 'setName' in response:
client = MongoReplicaSetClient(pair,
replicaSet=response['setName'],
w=len(response['hosts']),
ssl=True)
db = client.pymongo_ssl_test
db.test.drop()
self.assertTrue(db.test.insert({'ssl': True}))
self.assertTrue(db.test.find_one()['ssl'])
client.drop_database('pymongo_ssl_test')
def test_cert_ssl(self):
# Expects the server to be running with the server.pem, ca.pem
# and crl.pem provided in mongodb and the server tests eg:
#
# --sslPEMKeyFile=/path/to/pymongo/test/certificates/server.pem
# --sslCAFile=/path/to/pymongo/test/certificates/ca.pem
# --sslCRLFile=/path/to/pymongo/test/certificates/crl.pem
if not CERT_SSL:
raise SkipTest("No mongod available over SSL with certs")
client = MongoClient(host, port, ssl=True, ssl_certfile=CLIENT_PEM)
response = client.admin.command('ismaster')
if 'setName' in response:
client = MongoReplicaSetClient(pair,
replicaSet=response['setName'],
w=len(response['hosts']),
ssl=True, ssl_certfile=CLIENT_PEM)
db = client.pymongo_ssl_test
db.test.drop()
self.assertTrue(db.test.insert({'ssl': True}))
self.assertTrue(db.test.find_one()['ssl'])
client.drop_database('pymongo_ssl_test')
def test_cert_ssl_implicitly_set(self):
# Expects the server to be running with the server.pem, ca.pem
# and crl.pem provided in mongodb and the server tests eg:
#
# --sslPEMKeyFile=/path/to/pymongo/test/certificates/server.pem
# --sslCAFile=/path/to/pymongo/test/certificates/ca.pem
# --sslCRLFile=/path/to/pymongo/test/certificates/crl.pem
if not CERT_SSL:
raise SkipTest("No mongod available over SSL with certs")
client = MongoClient(host, port, ssl_certfile=CLIENT_PEM)
response = client.admin.command('ismaster')
if 'setName' in response:
client = MongoReplicaSetClient(pair,
replicaSet=response['setName'],
w=len(response['hosts']),
ssl_certfile=CLIENT_PEM)
db = client.pymongo_ssl_test
db.test.drop()
self.assertTrue(db.test.insert({'ssl': True}))
self.assertTrue(db.test.find_one()['ssl'])
client.drop_database('pymongo_ssl_test')
def test_cert_ssl_validation(self):
# Expects the server to be running with the server.pem, ca.pem
# and crl.pem provided in mongodb and the server tests eg:
#
# --sslPEMKeyFile=/path/to/pymongo/test/certificates/server.pem
# --sslCAFile=/path/to/pymongo/test/certificates/ca.pem
# --sslCRLFile=/path/to/pymongo/test/certificates/crl.pem
if not CERT_SSL:
raise SkipTest("No mongod available over SSL with certs")
client = MongoClient('localhost',
ssl=True,
ssl_certfile=CLIENT_PEM,
ssl_cert_reqs=ssl.CERT_REQUIRED,
ssl_ca_certs=CA_PEM)
response = client.admin.command('ismaster')
if 'setName' in response:
if response['primary'].split(":")[0] != 'localhost':
raise SkipTest("No hosts in the replicaset for 'localhost'. "
"Cannot validate hostname in the certificate")
client = MongoReplicaSetClient('localhost',
replicaSet=response['setName'],
w=len(response['hosts']),
ssl=True,
ssl_certfile=CLIENT_PEM,
ssl_cert_reqs=ssl.CERT_REQUIRED,
ssl_ca_certs=CA_PEM)
db = client.pymongo_ssl_test
db.test.drop()
self.assertTrue(db.test.insert({'ssl': True}))
self.assertTrue(db.test.find_one()['ssl'])
client.drop_database('pymongo_ssl_test')
def test_cert_ssl_uri_support(self):
# Expects the server to be running with the server.pem, ca.pem
# and crl.pem provided in mongodb and the server tests eg:
#
# --sslPEMKeyFile=/path/to/pymongo/test/certificates/server.pem
# --sslCAFile=/path/to/pymongo/test/certificates/ca.pem
# --sslCRLFile=/path/to/pymongo/test/certificates/crl.pem
if not CERT_SSL:
raise SkipTest("No mongod available over SSL with certs")
uri_fmt = ("mongodb://localhost/?ssl=true&ssl_certfile=%s&ssl_cert_reqs"
"=%s&ssl_ca_certs=%s&ssl_match_hostname=true")
client = MongoClient(uri_fmt % (CLIENT_PEM, 'CERT_REQUIRED', CA_PEM))
db = client.pymongo_ssl_test
db.test.drop()
db.test.insert({'ssl': True})
self.assertTrue(db.test.find_one()['ssl'])
client.drop_database('pymongo_ssl_test')
def test_cert_ssl_validation_optional(self):
# Expects the server to be running with the server.pem, ca.pem
# and crl.pem provided in mongodb and the server tests eg:
#
# --sslPEMKeyFile=/path/to/pymongo/test/certificates/server.pem
# --sslCAFile=/path/to/pymongo/test/certificates/ca.pem
# --sslCRLFile=/path/to/pymongo/test/certificates/crl.pem
if not CERT_SSL:
raise SkipTest("No mongod available over SSL with certs")
client = MongoClient('localhost',
ssl=True,
ssl_certfile=CLIENT_PEM,
ssl_cert_reqs=ssl.CERT_OPTIONAL,
ssl_ca_certs=CA_PEM)
response = client.admin.command('ismaster')
if 'setName' in response:
if response['primary'].split(":")[0] != 'localhost':
raise SkipTest("No hosts in the replicaset for 'localhost'. "
"Cannot validate hostname in the certificate")
client = MongoReplicaSetClient('localhost',
replicaSet=response['setName'],
w=len(response['hosts']),
ssl=True,
ssl_certfile=CLIENT_PEM,
ssl_cert_reqs=ssl.CERT_OPTIONAL,
ssl_ca_certs=CA_PEM)
db = client.pymongo_ssl_test
db.test.drop()
self.assertTrue(db.test.insert({'ssl': True}))
self.assertTrue(db.test.find_one()['ssl'])
client.drop_database('pymongo_ssl_test')
def test_cert_ssl_validation_hostname_matching(self):
# Expects the server to be running with the server.pem, ca.pem
# and crl.pem provided in mongodb and the server tests eg:
#
# --sslPEMKeyFile=/path/to/pymongo/test/certificates/server.pem
# --sslCAFile=/path/to/pymongo/test/certificates/ca.pem
# --sslCRLFile=/path/to/pymongo/test/certificates/crl.pem
#
# Also requires an /etc/hosts entry where "server" is resolvable
if not CERT_SSL:
raise SkipTest("No mongod available over SSL with certs")
if not SERVER_IS_RESOLVABLE:
raise SkipTest("No hosts entry for 'server'. Cannot validate "
"hostname in the certificate")
client = MongoClient(host, port, ssl=True, ssl_certfile=CLIENT_PEM)
response = client.admin.command('ismaster')
uri = ("mongodb://server/?ssl=true&ssl_certfile=%s&ssl_cert_reqs"
"=CERT_REQUIRED&ssl_ca_certs=%s" % (CLIENT_PEM, CA_PEM))
try:
MongoClient('server',
ssl=True,
ssl_certfile=CLIENT_PEM,
ssl_cert_reqs=ssl.CERT_REQUIRED,
ssl_ca_certs=CA_PEM)
self.fail("Invalid hostname should have failed")
except CertificateError:
pass
try:
MongoClient(uri)
self.fail("Invalid hostname should have failed")
except CertificateError:
pass
# No error.
MongoClient('server',
ssl=True,
ssl_certfile=CLIENT_PEM,
ssl_cert_reqs=ssl.CERT_REQUIRED,
ssl_ca_certs=CA_PEM,
ssl_match_hostname=False)
MongoClient(uri + "&ssl_match_hostname=false")
if 'setName' in response:
name = response['setName']
w = len(response['hosts'])
uri = uri + "&replicaSet=%s&w=%d" % (name, w)
try:
MongoReplicaSetClient('server',
replicaSet=name,
w=w,
ssl=True,
ssl_certfile=CLIENT_PEM,
ssl_cert_reqs=ssl.CERT_REQUIRED,
ssl_ca_certs=CA_PEM)
self.fail("Invalid hostname should have failed")
except CertificateError:
pass
try:
MongoReplicaSetClient(uri)
self.fail("Invalid hostname should have failed")
except CertificateError:
pass
# No error.
MongoReplicaSetClient('server',
replicaSet=name,
w=w,
ssl=True,
ssl_certfile=CLIENT_PEM,
ssl_cert_reqs=ssl.CERT_REQUIRED,
ssl_ca_certs=CA_PEM,
ssl_match_hostname=False)
MongoClient(uri + "&ssl_match_hostname=false")
class TestX509Auth(unittest.TestCase):
def setUp(self):
if not HAS_SSL:
raise SkipTest("The ssl module is not available.")
if sys.version.startswith('3.0'):
raise SkipTest("Python 3.0.x has problems "
"with SSL and socket timeouts.")
def test_mongodb_x509_auth(self):
# Expects the server to be running with the server.pem, ca.pem
# and crl.pem provided in mongodb and the server tests as well as
# --auth
#
# --sslPEMKeyFile=/path/to/pymongo/test/certificates/server.pem
# --sslCAFile=/path/to/pymongo/test/certificates/ca.pem
# --sslCRLFile=/path/to/pymongo/test/certificates/crl.pem
# --auth
if not CERT_SSL:
raise SkipTest("No mongod available over SSL with certs")
if not version.at_least(ssl_auth_ctx.client, (2, 5, 3, -1)):
raise SkipTest("MONGODB-X509 tests require MongoDB 2.5.3 or newer")
if not ssl_auth_ctx.auth_enabled:
raise SkipTest('Authentication is not enabled on server')
# This does two things:
# 1. Ensures we test against both client classes.
# 2. Ensures the tests pass regardless of what replica
# set member became primary before the tests run.
ismaster = ssl_auth_ctx.client.admin.command('ismaster')
if 'setName' in ismaster:
get_client = lambda hst: MongoReplicaSetClient(
hst,
ssl=True,
ssl_certfile=CLIENT_PEM,
replicaSet=ismaster['setName'])
else:
get_client = lambda hst: MongoClient(
hst,
ssl=True,
ssl_certfile=CLIENT_PEM)
client = get_client(pair)
client.admin.authenticate(db_user, db_pwd)
# Give admin all necessary privileges.
client['$external'].add_user(MONGODB_X509_USERNAME, roles=[
{'role': 'readWriteAnyDatabase', 'db': 'admin'},
{'role': 'userAdminAnyDatabase', 'db': 'admin'}])
client.admin.logout()
coll = client.pymongo_test.test
self.assertRaises(OperationFailure, coll.count)
self.assertTrue(client.admin.authenticate(MONGODB_X509_USERNAME,
mechanism='MONGODB-X509'))
self.assertTrue(coll.remove())
client.admin.logout()
uri = ('mongodb://%s@%s:%d/?authMechanism='
'MONGODB-X509' % (quote_plus(MONGODB_X509_USERNAME), host, port))
# SSL options aren't supported in the URI...
self.assertTrue(get_client(uri))
# Should require a username
uri = ('mongodb://%s:%d/?authMechanism=MONGODB-X509' % (host, port))
client_bad = get_client(uri)
self.assertRaises(OperationFailure, client_bad.pymongo_test.test.remove)
# Auth should fail if username and certificate do not match
uri = ('mongodb://%s@%s:%d/?authMechanism='
'MONGODB-X509' % (quote_plus("not the username"), host, port))
self.assertRaises(ConfigurationError, get_client, uri)
self.assertRaises(OperationFailure, client.admin.authenticate,
"not the username",
mechanism="MONGODB-X509")
# Cleanup
client.admin.authenticate(db_user, db_pwd)
remove_all_users(client['$external'])
if __name__ == "__main__":
unittest.main()