From 4d632a97f372ec7dc635758f6925780979fa5ade Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 15 May 2020 23:34:31 +0200 Subject: [PATCH] Use secure RNG for UIDs Closes #766 --- radicale/item/__init__.py | 5 +++-- radicale/web/internal_data/fn.js | 14 ++++++-------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/radicale/item/__init__.py b/radicale/item/__init__.py index aef6d9e..53a2113 100644 --- a/radicale/item/__init__.py +++ b/radicale/item/__init__.py @@ -23,11 +23,12 @@ Module for address books and calendar entries (see ``Item``). """ +import binascii import math +import os import sys from datetime import timedelta from hashlib import sha256 -from random import getrandbits import vobject @@ -179,7 +180,7 @@ def find_available_uid(exists_fn, suffix=""): """Generate a pseudo-random UID""" # Prevent infinite loop for _ in range(1000): - r = "%016x" % getrandbits(128) + r = binascii.hexlify(os.urandom(16)).decode("ascii") name = "%s-%s-%s-%s-%s%s" % ( r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix) if not exists_fn(name): diff --git a/radicale/web/internal_data/fn.js b/radicale/web/internal_data/fn.js index 9305596..ef47d08 100644 --- a/radicale/web/internal_data/fn.js +++ b/radicale/web/internal_data/fn.js @@ -404,7 +404,7 @@ function edit_collection(user, password, collection, callback) { * @return {string} */ function random_uuid() { - return randHex(8) + "-" + randHex(4) + "-" + randHex(4) + "-" + randHex(4) + "-" + randHex(12); + return random_hex(8) + "-" + random_hex(4) + "-" + random_hex(4) + "-" + random_hex(4) + "-" + random_hex(12); } /** @@ -969,12 +969,10 @@ function DeleteCollectionScene(user, password, collection) { * @param {number} length * @return {string} */ -function randHex(length) { - let s = Math.floor(Math.random() * Math.pow(16, length)).toString(16); - while (s.length < length) { - s = "0" + s; - } - return s; +function random_hex(length) { + let bytes = new Uint8Array(Math.ceil(length / 2)); + window.crypto.getRandomValues(bytes); + return bytes.reduce((s, b) => s + b.toString(16).padStart(2, "0"), "").substring(0, length); } /** @@ -1007,7 +1005,7 @@ function CreateEditCollectionScene(user, password, collection) { let displayname = edit ? collection.displayname : ""; let description = edit ? collection.description : ""; let type = edit ? collection.type : CollectionType.CALENDAR_JOURNAL_TASKS; - let color = edit && collection.color ? collection.color : "#" + randHex(6); + let color = edit && collection.color ? collection.color : "#" + random_hex(6); function remove_invalid_types() { if (!edit) {