From 87793a9058108c18bbe2aa0112cde9d98768c52d Mon Sep 17 00:00:00 2001 From: Shane Harvey Date: Mon, 29 Apr 2019 12:12:25 -0700 Subject: [PATCH] Saner random byte generation --- bson/objectid.py | 2 +- pymongo/auth.py | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/bson/objectid.py b/bson/objectid.py index 8b7ad8ec8..c6fa652f3 100644 --- a/bson/objectid.py +++ b/bson/objectid.py @@ -42,7 +42,7 @@ def _raise_invalid_id(oid): def _random_bytes(): """Get the 5-byte random field of an ObjectId.""" - return struct.pack(">Q", SystemRandom().randint(0, 0xFFFFFFFFFF))[3:] + return os.urandom(5) class ObjectId(object): diff --git a/pymongo/auth.py b/pymongo/auth.py index 3667257af..fef4386f1 100644 --- a/pymongo/auth.py +++ b/pymongo/auth.py @@ -17,6 +17,7 @@ import functools import hashlib import hmac +import os import socket try: @@ -38,7 +39,6 @@ except ImportError: from base64 import standard_b64decode, standard_b64encode from collections import namedtuple -from random import SystemRandom from bson.binary import Binary from bson.py3compat import string_type, _unicode, PY3 @@ -253,8 +253,7 @@ def _authenticate_scram(credentials, sock_info, mechanism): _hmac = hmac.HMAC user = username.encode("utf-8").replace(b"=", b"=3D").replace(b",", b"=2C") - nonce = standard_b64encode( - (("%s" % (SystemRandom().random(),))[2:]).encode("utf-8")) + nonce = standard_b64encode(os.urandom(32)) first_bare = b"n=" + user + b",r=" + nonce cmd = SON([('saslStart', 1),