python: Use standard secrets module to generate random tokens.

There are three functional side effects:

• Correct an insignificant but mathematically offensive bias toward
repeated characters in generate_api_key introduced in commit
47b4283c4b4c70ecde4d3c8de871c90ee2506d87; its entropy is increased
from 190.52864 bits to 190.53428 bits.

• Use the base32 alphabet in confirmation.models.generate_key; its
entropy is reduced from 124.07820 bits to the documented 120 bits, but
now it uses 1 syscall instead of 24.

• Use the base32 alphabet in get_bigbluebutton_url; its entropy is
reduced from 51.69925 bits to 50 bits, but now it uses 1 syscall
instead of 10.

(The base32 alphabet is A-Z 2-7.  We could probably replace all of
these with plain secrets.token_urlsafe, since I expect most callers
can handle the full urlsafe_b64 alphabet A-Z a-z 0-9 - _ without
problems.)

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg
2020-09-04 19:02:13 -07:00
committed by Tim Abbott
parent 56546170cf
commit b7b7475672
20 changed files with 51 additions and 57 deletions

View File

@@ -1,4 +1,5 @@
import logging
import secrets
from typing import Any, Dict, List, Optional, Tuple
from django.conf import settings
@@ -19,7 +20,7 @@ from zerver.lib.push_notifications import num_push_devices_for_user
from zerver.lib.streams import access_stream_by_name
from zerver.lib.subdomains import get_subdomain
from zerver.lib.users import compute_show_invites_and_add_streams
from zerver.lib.utils import generate_random_token, statsd
from zerver.lib.utils import statsd
from zerver.models import PreregistrationUser, Realm, Stream, UserProfile
from zerver.views.compatibility import is_outdated_desktop_app, is_unsupported_browser
from zerver.views.portico import hello_view
@@ -200,7 +201,7 @@ def home_real(request: HttpRequest) -> HttpResponse:
request._log_data['extra'] = "[{}]".format(queue_id)
csp_nonce = generate_random_token(48)
csp_nonce = secrets.token_hex(24)
user_permission_info = get_user_permission_info(user_profile)