Skip to content

Commit

Permalink
[util] Remove expand_seed routine.
Browse files Browse the repository at this point in the history
This routine wasn't currently affecting the logic, but would have weakened
certain seeds that happened to have low values. Ideally this should all be
refactored to use byte strings so it's clearer what range the value is sampled
from, but for now just removing the harmful logic should suffice.

Signed-off-by: Jade Philipoom <[email protected]>
  • Loading branch information
jadephilipoom committed Sep 24, 2024
1 parent 78ad89d commit 8cfe060
Show file tree
Hide file tree
Showing 6 changed files with 18 additions and 30 deletions.
7 changes: 3 additions & 4 deletions util/design/lib/LcStEnc.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@
from collections import OrderedDict

from Crypto.Hash import cSHAKE128
from lib.common import (check_int, ecc_encode, expand_seed, get_hd,
hd_histogram, is_valid_codeword, random_or_hexvalue,
scatter_bits)
from lib.common import (check_int, ecc_encode, get_hd, hd_histogram,
is_valid_codeword, random_or_hexvalue, scatter_bits)
from topgen import secure_prng as sp

# Seed diversification constant for LcStEnc (this enables to use
Expand Down Expand Up @@ -288,7 +287,7 @@ def __init__(self, config):
log.info('Seed: {0:x}'.format(config['seed']))
log.info('')

sp.reseed(expand_seed(LC_SEED_DIVERSIFIER + int(config['seed'])))
sp.reseed(LC_SEED_DIVERSIFIER + int(config['seed']))

log.info('Checking SECDED.')
_validate_secded(config)
Expand Down
2 changes: 1 addition & 1 deletion util/design/lib/OtpMemImg.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def __init__(self, lc_state_config, otp_mmap_config, img_config,
log.info('')

# Re-initialize with seed to make results reproducible.
sp.reseed(common.expand_seed(OTP_IMG_SEED_DIVERSIFIER + int(img_config['seed'])))
sp.reseed(OTP_IMG_SEED_DIVERSIFIER + int(img_config['seed']))

if 'partitions' not in img_config:
raise RuntimeError('Missing partitions key in configuration.')
Expand Down
4 changes: 2 additions & 2 deletions util/design/lib/OtpMemMap.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import logging as log
from math import ceil, log2

from lib.common import check_bool, check_int, expand_seed, random_or_hexvalue
from lib.common import check_bool, check_int, random_or_hexvalue
from mubi.prim_mubi import is_width_valid, mubi_value_as_int
from tabulate import tabulate
from topgen import secure_prng as sp
Expand Down Expand Up @@ -405,7 +405,7 @@ def __init__(self, config):
config["seed"] = check_int(config["seed"])

# Initialize RNG.
sp.reseed(expand_seed(OTP_SEED_DIVERSIFIER + int(config['seed'])))
sp.reseed(OTP_SEED_DIVERSIFIER + int(config['seed']))
log.info('Seed: {0:x}'.format(config['seed']))
log.info('')

Expand Down
15 changes: 1 addition & 14 deletions util/design/lib/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import re
import sys
import textwrap
from math import ceil, log, log2
from math import ceil, log2
from pathlib import Path

sys.path.append(os.path.join(os.path.dirname(__file__), '../../'))
Expand Down Expand Up @@ -116,19 +116,6 @@ def blockify(s, size, limit):
return (",\n ".join(s_list))


def expand_seed(seed):
'''Checks if the input seed is shorter than 256 bits and expands it if
it's not.
'''
new_seed = seed
seed_bytes = ceil(log(seed + 1, 256))
while new_seed < (1 << 256):
new_seed <<= seed_bytes * 8
new_seed += seed
new_seed %= (1 << 256)
return new_seed


def get_random_perm_hex_literal(numel):
'''Compute a random permutation of 'numel' elements and
return as packed hex literal.'''
Expand Down
4 changes: 2 additions & 2 deletions util/topgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import hjson
import tlgen
import version_file
from design.lib.common import expand_seed
from ipgen import (IpBlockRenderer, IpConfig, IpDescriptionOnlyRenderer,
IpTemplate, TemplateRenderError)
from mako import exceptions
Expand Down Expand Up @@ -1081,7 +1080,8 @@ def main():
elif "rnd_cnst_seed" not in topcfg:
log.error('Seed "rnd_cnst_seed" not found in configuration HJSON.')
exit(1)
secure_prng.reseed(expand_seed(topcfg["rnd_cnst_seed"]))

secure_prng.reseed(topcfg["rnd_cnst_seed"])

# TODO, long term, the levels of dependency should be automatically
# determined instead of hardcoded. The following are a few examples:
Expand Down
16 changes: 9 additions & 7 deletions util/topgen/secure_prng.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,23 +173,25 @@ def reseed(self, seed):
from previous instantiation.
"""
if seed == 0:
entropy_input = seed.to_bytes(32, 'big')
log.error("ERROR: PRNG seeded with 0.")
sys.exit(1)
# Check if the provided seed is at least 32 bytes long.
elif sys.getsizeof(seed) < sys.getsizeof(1 << 255):
# Error out if seed is shorter than 256 bits.
log.error("ERROR: Seed shorter than 256 bits.")
sys.exit(1)

if seed.bit_length() < 250:
# Warn, but don't fail, because the DV logic always passes in 32-bit
# seeds and this can naturally happen about 1% of the time.
log.warn('PRNG seed is only {seed.bit_length()} bits long, which is '
'unlikely for a sample from a 256-bit distribution. Please '
'double-check the logic.')
# Check if the seed is longer than 256 bits. Trim the excess bits and
# issue a warning if it is.
elif seed > (1 << 256):
if seed.bit_length() > 256:
new_seed = seed % (1 << 256)
log.warning("Seed longer than 256 bits. CTR_DRBG seeded with: " +
hex(new_seed))
entropy_input = new_seed.to_bytes(32, 'big')
else:
entropy_input = seed.to_bytes(32, 'big')

self.CTR_DRBG_Instantiate(entropy_input)
self.returned_bits = []

Expand Down

0 comments on commit 8cfe060

Please sign in to comment.