Use secure RNG for UIDs

Closes #766
This commit is contained in:
Unrud 2020-05-15 23:34:31 +02:00
parent f598271583
commit 4d632a97f3
2 changed files with 9 additions and 10 deletions

View File

@ -23,11 +23,12 @@ Module for address books and calendar entries (see ``Item``).
""" """
import binascii
import math import math
import os
import sys import sys
from datetime import timedelta from datetime import timedelta
from hashlib import sha256 from hashlib import sha256
from random import getrandbits
import vobject import vobject
@ -179,7 +180,7 @@ def find_available_uid(exists_fn, suffix=""):
"""Generate a pseudo-random UID""" """Generate a pseudo-random UID"""
# Prevent infinite loop # Prevent infinite loop
for _ in range(1000): for _ in range(1000):
r = "%016x" % getrandbits(128) r = binascii.hexlify(os.urandom(16)).decode("ascii")
name = "%s-%s-%s-%s-%s%s" % ( name = "%s-%s-%s-%s-%s%s" % (
r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix) r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix)
if not exists_fn(name): if not exists_fn(name):

View File

@ -404,7 +404,7 @@ function edit_collection(user, password, collection, callback) {
* @return {string} * @return {string}
*/ */
function random_uuid() { 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 * @param {number} length
* @return {string} * @return {string}
*/ */
function randHex(length) { function random_hex(length) {
let s = Math.floor(Math.random() * Math.pow(16, length)).toString(16); let bytes = new Uint8Array(Math.ceil(length / 2));
while (s.length < length) { window.crypto.getRandomValues(bytes);
s = "0" + s; return bytes.reduce((s, b) => s + b.toString(16).padStart(2, "0"), "").substring(0, length);
}
return s;
} }
/** /**
@ -1007,7 +1005,7 @@ function CreateEditCollectionScene(user, password, collection) {
let displayname = edit ? collection.displayname : ""; let displayname = edit ? collection.displayname : "";
let description = edit ? collection.description : ""; let description = edit ? collection.description : "";
let type = edit ? collection.type : CollectionType.CALENDAR_JOURNAL_TASKS; 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() { function remove_invalid_types() {
if (!edit) { if (!edit) {