Algorithm Search⌘K

Algorithmadvanced

Markov password model

Also called n-gram password model.

Estimates password strength with a character n-gram model trained on a password list. A password scores -log2 of its probability, and its guess number is its rank under the model.

Time
Θ(n k) worst · average · best
Space
O(k) extra
Where
T = the number of symbols in the padded training list; k = the order of the model (characters of context); n = the length of the password
Properties
deterministiconline
Origin
Arvind Narayanan, Vitaly Shmatikov, Claude Castelluccia, Markus Duermuth, Daniele Perito, Matteo Dell'Amico, Maurizio Filippone, 2005

A Markov password model estimates how strong a password is. It is a character n-gram model trained on a password list: each character is predicted from the kk characters before it, and an end symbol closes the string. The trained model gives each password ww a probability P(w)P(w). The strength is −log⁡2P(w)-\log_2 P(w) bits, and the guess number is the rank of ww when all strings are sorted by decreasing probability, which is the number of guesses that a guesser who knows the model would need. Scoring is one pass over the password, Θ(nk)\Theta(nk) time for a password of nn characters. Both numbers are estimates under the model and its training list: they say how a password compares with the habits seen in the list, not how hard it is to guess for every attacker. The model is a Markov chain on contexts, and its counts are smoothed, here with additive smoothing, so that a string not seen in training still has a probability.

In plain words

People choose passwords in patterns. Some letters often follow others, many passwords end in a digit, and short words are common. A model that has read a long list of passwords learns how often each character comes after the few characters before it.

To judge a new password, the model reads it one character at a time and asks how likely each next character was. It multiplies these chances. A password made of common steps gets a high chance and is weak. A password with rare steps gets a tiny chance and is strong. A strength meter turns the chance into a score, and it can also estimate how many more likely passwords exist, which says how many guesses a careful guesser would need.

The problem

The input is a training list of passwords over an alphabet Σ\Sigma, an order k≥0k \ge 0, a smoothing constant δ≥0\delta \ge 0, and a password ww. Let σ=∣Σ∣+1\sigma = |\Sigma| + 1, counting the end symbol ⊣\dashv. Each password in the list is padded with kk start symbols ▹\triangleright in front and ⊣\dashv at the end. For each context cc of kk symbols and each next symbol aa, training counts N(c,a)N(c, a), the number of times aa follows cc, and N(c)=∑aN(c,a)N(c) = \sum_a N(c, a). The model is

P(a∣c)=N(c,a)+δN(c)+δσ,P(w)=∏i=1∣w∣+1P(wi∣ci),P(a \mid c) = \frac{N(c, a) + \delta}{N(c) + \delta\sigma}, \qquad P(w) = \prod_{i=1}^{|w|+1} P(w_i \mid c_i),

where w∣w∣+1=⊣w_{|w|+1} = \dashv and cic_i is the last kk symbols before position ii. The outputs are the strength −log⁡2P(w)-\log_2 P(w) and the guess number 1+∣{v:P(v)>P(w)}∣1 + |\{v : P(v) > P(w)\}|.

The algorithm

  1. MARKOV-SCORE(w, N, k, δ, σ)
  2. 1c ← ▷^k ; p ← 1 ▷ k start symbols
  3. 2for i ← 1 to |w| + 1 do
  4. 3a ← w[i] if i ≤ |w|, else ⊣ ▷ the end symbol
  5. 4p ← p · (N(c, a) + δ) / (N(c) + δσ)
  6. 5c ← the last k symbols of c·a
  7. 6return -log2 p

Training is one pass over the padded list that adds 1 to N(c,a)N(c, a) and N(c)N(c) for each symbol. Line L4 is the smoothed probability of the next symbol; with δ=0\delta = 0 it is the maximum likelihood estimate, and an unseen step gives probability 0 and strength +∞+\infty. The end symbol of line L3 makes PP a distribution over strings of all lengths, so that a long password is not scored as if it were a prefix of a longer one. The code keeps pp as an exact fraction and computes the logarithm from its numerator and denominator.

Guess numbers. The exact guess number counts the strings with a higher probability. A prefix has a probability at least as large as each string that extends it, so a search over prefixes can skip each prefix whose probability is already at most P(w)P(w). This is exact but can take time proportional to the guess number. Dell'Amico and Filippone (2015) estimate it instead from mm strings S1,…,SmS_1, \ldots, S_m drawn from the model: each SjS_j with P(Sj)>P(w)P(S_j) > P(w) stands for 1/(mP(Sj))1/(m P(S_j)) strings, and the sum is an unbiased estimate of the count. The code returns only the probabilities of the drawn strings, not the strings.

Example

The training list is made up: ab1, ab11, abab, b1, ba1, a1, ab and bb1, over the alphabet {a,b,1}\{a, b, 1\}. With k=1k = 1 there are four contexts: the start, with N=8N = 8; a, with N=7N = 7; b, with N=9N = 9; and 1, with N=7N = 7. With δ=1\delta = 1 and σ=4\sigma = 4, scoring w=w = ab1 goes as follows.

ii context cc symbol aa N(c,a)N(c, a) N(c)N(c) P(a∣c)P(a \mid c) pp after line L4
1 start a 5 8 6/12 1/2
2 a b 5 7 6/11 3/11
3 b 1 4 9 5/13 15/143
4 1 end 6 7 7/11 105/1573

So P(ab1)=105/1573P(\texttt{ab1}) = 105/1573 and the strength is −log⁡2(105/1573)≈3.91-\log_2(105/1573) \approx 3.91 bits. Only 4 strings have a higher probability, so the guess number is 5. The other strings score as follows.

password P(w)P(w) strength in bits guess number
ab1 105/1573 3.91 5
ba 1/143 7.16 24
1b 1/572 9.16 50
b1a 5/4719 9.88 80

The password 1b is short, but it starts with a digit and puts a letter after a digit, which no password of the list does, so it scores higher than the longer ab1. On a real list the numbers are much larger, but the ordering logic is the same.

Correctness

Line L2 keeps the invariant that before step ii, cc is the context cic_i and pp is the product of the first i−1i - 1 factors, so line L6 returns −log⁡2P(w)-\log_2 P(w). For δ>0\delta > 0 the probabilities of all finite strings sum to 1: the mass of the strings of length at most LL plus the mass of the prefixes of length L+1L + 1 is exactly 1 for each LL, and the second part shrinks geometrically because each context gives the end symbol a probability of at least δ/(N(c)+δσ)\delta / (N(c) + \delta\sigma). With δ=0\delta = 0 the counts are the maximum likelihood model of the list. The exact guess number search is correct because a prefix is at least as probable as each of its extensions, and the Monte Carlo estimate is unbiased because each string vv is drawn with probability P(v)P(v) and weighted by 1/P(v)1/P(v). The full proofs are in proofs/correctness.md.

Proof: The Markov password model is a distribution, and its guess numbers and Monte Carlo estimates are exact or unbiasedfull

We use the pseudocode MARKOV-SCORE of the page. The alphabet is Σ\Sigma, the order is k≥0k \ge 0, and σ=∣Σ∣+1\sigma = |\Sigma| + 1 counts the characters and the end symbol ⊣\dashv. For a context cc (a string of kk symbols over Σ\Sigma and the start symbol) and a symbol a∈Σ∪{⊣}a \in \Sigma \cup \{\dashv\}, the trained model has counts N(c,a)N(c, a) and N(c)=∑aN(c,a)N(c) = \sum_a N(c, a), and

P(a∣c)=N(c,a)+δN(c)+δσ.P(a \mid c) = \frac{N(c, a) + \delta}{N(c) + \delta\sigma}.

For a string w=w1⋯wnw = w_1 \cdots w_n let wn+1=⊣w_{n+1} = \dashv and let cic_i be the last kk symbols of ▹kw1⋯wi−1\triangleright^k w_1 \cdots w_{i-1}, where ▹\triangleright is the start symbol.

Claim 1 (the score). MARKOV-SCORE returns −log⁡2P(w)-\log_2 P(w) with P(w)=∏i=1n+1P(wi∣ci)P(w) = \prod_{i=1}^{n+1} P(w_i \mid c_i).

Proof. The loop of line L2 keeps the invariant: before the iteration for ii, c=cic = c_i and p=∏j<iP(wj∣cj)p = \prod_{j < i} P(w_j \mid c_j). Line L1 makes it true for i=1i = 1, since c1=▹kc_1 = \triangleright^k and the empty product is 1. Line L3 picks wiw_i, line L4 multiplies pp by P(wi∣ci)P(w_i \mid c_i), and line L5 sets cc to the last kk symbols of ciwic_i w_i, which is ci+1c_{i+1}. After the iteration for i=n+1i = n + 1, p=P(w)p = P(w), and line L6 returns −log⁡2p-\log_2 p. □\square

Claim 2 (a distribution). For each context cc, ∑aP(a∣c)=1\sum_a P(a \mid c) = 1 when the denominator is positive. If δ>0\delta > 0, then ∑wP(w)=1\sum_w P(w) = 1 over all finite strings ww over Σ\Sigma.

Proof. The first part is ∑a(N(c,a)+δ)=N(c)+δσ\sum_a (N(c, a) + \delta) = N(c) + \delta\sigma. For the second, let Q(u)=∏i=1∣u∣P(ui∣ci)Q(u) = \prod_{i=1}^{|u|} P(u_i \mid c_i) be the probability of the prefix uu without the end symbol, so P(u)=Q(u)P(⊣∣c∣u∣+1)P(u) = Q(u) P(\dashv \mid c_{|u|+1}) and Q(u)=∑a∈Σ∪{⊣}Q(u) = \sum_{a \in \Sigma \cup \{\dashv\}} of Q(u)P(a∣c∣u∣+1)Q(u) P(a \mid c_{|u|+1}). We show by induction on LL that

∑∣w∣≤LP(w)+∑∣u∣=L+1Q(u)=1.\sum_{|w| \le L} P(w) + \sum_{|u| = L + 1} Q(u) = 1.

For L=−1L = -1 the first sum is empty and the second is Q(ε)=1Q(\varepsilon) = 1. To go from L−1L - 1 to LL, split each Q(u)Q(u) with ∣u∣=L|u| = L by its next symbol: the end symbol gives P(u)P(u), a character aa gives Q(ua)Q(ua). This is the identity that the test checks with exact fractions.

There are finitely many contexts, so ε=min⁡cP(⊣∣c)>0\varepsilon = \min_c P(\dashv \mid c) > 0 when δ>0\delta > 0, since then P(⊣∣c)≥δ/(N(c)+δσ)P(\dashv \mid c) \ge \delta / (N(c) + \delta\sigma). Each step that is not the end has probability at most 1−ε1 - \varepsilon in total, so ∑∣u∣=L+1Q(u)≤(1−ε)L+1\sum_{|u| = L+1} Q(u) \le (1 - \varepsilon)^{L+1}, which tends to 0. □\square

With δ=0\delta = 0 and a context never seen in training, the denominator is 0 and the code gives probability 0. Then the mass can be less than 1, and a string with an unseen transition has strength +∞+\infty.

Claim 3 (maximum likelihood). With δ=0\delta = 0, the values P(a∣c)=N(c,a)/N(c)P(a \mid c) = N(c, a) / N(c) maximize the likelihood of the training list among all order-kk models.

Proof. The log likelihood of the list is ∑c∑aN(c,a)log⁡P(a∣c)\sum_c \sum_a N(c, a) \log P(a \mid c). The terms for different contexts are independent. For one context with N(c)>0N(c) > 0 and empirical distribution p^(a)=N(c,a)/N(c)\hat p(a) = N(c, a)/N(c), the term is N(c)∑ap^(a)log⁡P(a∣c)N(c) \sum_a \hat p(a) \log P(a \mid c), and by Gibbs' inequality this is largest exactly when P(⋅∣c)=p^P(\cdot \mid c) = \hat p. □\square

Claim 4 (guess numbers). GUESS-NUMBER(w,M)(w, M) of the code returns 1+∣{v:∣v∣≤M, P(v)>P(w)}∣1 + |\{v : |v| \le M,\ P(v) > P(w)\}|.

Proof. Each factor is at most 1, so for each prefix uu and each vv that extends it, P(v)≤Q(u)P(v) \le Q(u). The search starts at the empty prefix and skips the subtree of uu when Q(u)≤P(w)Q(u) \le P(w); no string in that subtree can have P(v)>P(w)P(v) > P(w). Each other prefix uu is visited once, counted when P(u)=Q(u)P(⊣∣c)>P(w)P(u) = Q(u) P(\dashv \mid c) > P(w), and extended by each character while ∣u∣<M|u| < M. So each string of length at most MM with P(v)>P(w)P(v) > P(w) is counted once, and no other string is. □\square

Claim 5 (the Monte Carlo estimate). Let S1,…,SmS_1, \ldots, S_m be independent draws from the model and tt a threshold. Then

G^=∑j=1m[P(Sj)>t]m P(Sj)\hat G = \sum_{j=1}^{m} \frac{[P(S_j) > t]}{m\, P(S_j)}

has expectation ∣{v:P(v)>t}∣|\{v : P(v) > t\}|.

Proof. By linearity, E[G^]=E[[P(S)>t]/P(S)]=∑v:P(v)>0P(v)[P(v)>t]/P(v)=∣{v:P(v)>t}∣\mathbb{E}[\hat G] = \mathbb{E}\big[[P(S) > t] / P(S)\big] = \sum_{v : P(v) > 0} P(v) [P(v) > t] / P(v) = |\{v : P(v) > t\}|. This set is finite for t>0t > 0, since P(v)≤(1−ε)∣v∣P(v) \le (1 - \varepsilon)^{|v|}. When the draws are cut at length MM, as in the code, the same computation gives the count of strings of length at most MM. □\square

The estimate of the guess number of ww is 1+G^1 + \hat G with t=P(w)t = P(w). Its variance is not bounded by this argument, and the test only checks that it is near the exact count on one small model.

Cost. Line L4 does one lookup of a context of kk symbols in a hash table, so MARKOV-SCORE takes Θ(nk)\Theta(nk) time for n=∣w∣n = |w| on the word-RAM, or Θ(n)\Theta(n) when kk is a constant, and O(k)O(k) extra space. Training reads each of the TT symbols of the padded list once and does one lookup for each, so it takes O(Tk)O(Tk) time, and the tables hold at most TT contexts of kk symbols. ■\blacksquare

Complexity

  • Scoring. Line L4 runs n+1n + 1 times, each with a hash table lookup of a context of kk symbols, so the time is Θ(nk)\Theta(nk) on the word-RAM, or Θ(n)\Theta(n) for a fixed order. The extra space is O(k)O(k) for the context.
  • Training. One lookup for each of the TT symbols of the padded list, so O(Tk)O(Tk) time. The model stores at most TT contexts, and in the worst case ∣Σ∣k|\Sigma|^k of them can appear, which is why orders above 4 or 5 need much data and strong smoothing.
  • Exact guess numbers. The pruned search visits each string it counts and the prefixes on the way, so its time grows with the guess number. It is only for small models, as in the test.
  • Monte Carlo guess numbers. Drawing mm strings costs O(mℓ∣Σ∣)O(m \ell |\Sigma|) for strings of length at most ℓ\ell. After sorting the mm probabilities and taking suffix sums of 1/(mP)1/(mP), each estimate is a binary search, O(log⁡m)O(\log m).

Properties

  • An estimate, not a measure. The score depends on the training list, the order and the smoothing. A password that is rare in the list can still be common elsewhere, and a model trained on one population can misjudge another.
  • A proper distribution. With an end symbol and δ>0\delta > 0, the probabilities of all strings sum to 1, so probabilities of different lengths can be compared.
  • Exact arithmetic. The code multiplies fractions, so equal probabilities are equal and ties in the guess number are well defined.
  • Online. A meter can update pp after each typed character with one step of line L4.

Variants and improvements

  • Order and backoff. Orders between 2 and 5 are common. When a context is rare, backoff or interpolation with lower orders, or Kneser-Ney smoothing and Good-Turing estimation, give better probabilities than a single additive δ\delta. Ma et al. (2014) found that the choice of smoothing and normalization has a large effect on the results.
  • Normalization by length. Instead of an end symbol, a model can generate the length first and then the characters; the end symbol is the simpler way to get a distribution over all lengths.
  • Adaptive meters. Castelluccia, Duermuth and Perito (2012) trained the model on the passwords of the service itself, so the meter follows the habits of its own users.
  • Comparison with grammars. The PCFG password model splits a password into segments of letters, digits and symbols. The two models can be compared by their guess numbers on a held-out list.

When to use it

Use a Markov model to estimate strength in a meter or to compare password policies on a test list. It needs only a training list and counts, it scores in one pass, and its probabilities are well defined for any string. A PCFG model is closer to how people build passwords from words and digits, and a dictionary-based meter catches known words better; Ma et al. (2014) found that well-smoothed Markov models did at least as well as PCFG models in their study. Neither model gives a security guarantee: for stored passwords, use slow password hashing, and to detect a stolen password file, use honeywords.

Pitfalls

  • No end symbol. If line L3 stops at i=∣w∣i = |w|, the product is the probability of ww as a prefix. A password then never has a higher probability than its own prefixes, the probabilities of strings of different lengths do not sum to 1, and they cannot be compared. Line L3 must include the end symbol.
  • No smoothing. With δ=0\delta = 0 in line L4, any step not seen in training gives probability 0 and an infinite strength, even for a weak password with one unusual character. Use δ>0\delta > 0 or a backoff to a lower order.
  • Floating point underflow. A product of many small factors in line L4 can round to 0 in floating point. Add logarithms instead, or keep exact fractions, as the code does.
  • A wrong context update. If line L5 keeps the first kk symbols instead of the last kk, each step uses a stale context. The context is the last kk symbols of c⋅ac \cdot a.
  • Reading the score as a guarantee. A high score means that the password is unlike the training list, not that it is safe against an attacker with another list.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

markov_password_model.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/markov-password-model/. The authors are listed in prov/Q34M2V.jsonl.

"""A character Markov model of passwords, used to estimate password strength.

The model of order k predicts each character from the k characters before it,
with k start symbols in front of the password and an end symbol after it. It
is trained on a list of passwords by counting, with additive smoothing delta,
and it scores a password by its probability P(w) or by -log2 P(w) bits. A
low probability means a strong password under this model. The guess number
of w is 1 plus the number of strings with a higher probability: the place of
w in a guessing order by decreasing probability. It is an estimate under the
model and its training list, not a property of the password alone.

All probabilities are exact fractions.
"""

import math
import random
from fractions import Fraction
from typing import NamedTuple

START = "\x02"
END = "\x03"


class MarkovModel(NamedTuple):
    k: int  # the order: the number of characters of context
    alphabet: tuple[str, ...]  # the characters a password may use, sorted
    delta: Fraction  # the additive smoothing constant
    counts: dict  # (context, symbol) -> count, symbol in alphabet or END
    totals: dict  # context -> count


def shift(ctx: str, a: str, k: int) -> str:
    """The last k symbols of ctx followed by a."""
    return (ctx + a)[len(ctx) + 1 - k :] if k else ""


def _check(w: str, alphabet: tuple[str, ...]) -> None:
    for ch in w:
        if ch not in alphabet:
            raise ValueError(f"character {ch!r} is not in the alphabet")


def train(passwords: list[str], k: int, alphabet: str, delta: Fraction = Fraction(1)) -> MarkovModel:
    """Count the transitions of the padded passwords.

    Precondition: k >= 0, delta >= 0, each password uses only the alphabet.
    Cost: O(N k) time for N characters in the list, O(N k) space.
    """
    if k < 0 or delta < 0:
        raise ValueError("need k >= 0 and delta >= 0")
    alpha = tuple(sorted(set(alphabet)))
    if START in alpha or END in alpha:
        raise ValueError("the start and end symbols are reserved")
    counts: dict = {}
    totals: dict = {}
    for w in passwords:
        _check(w, alpha)
        ctx = START * k
        for a in list(w) + [END]:
            counts[(ctx, a)] = counts.get((ctx, a), 0) + 1
            totals[ctx] = totals.get(ctx, 0) + 1
            ctx = shift(ctx, a, k)
    return MarkovModel(k, alpha, Fraction(delta), counts, totals)


def next_prob(m: MarkovModel, ctx: str, a: str) -> Fraction:
    """P(a | ctx) with additive smoothing over the alphabet and END."""
    sigma = len(m.alphabet) + 1
    den = m.totals.get(ctx, 0) + m.delta * sigma
    if den == 0:
        return Fraction(0)  # no smoothing and an unseen context
    return (m.counts.get((ctx, a), 0) + m.delta) / den


def probability(m: MarkovModel, w: str) -> Fraction:
    """MARKOV-SCORE of the page, as an exact probability. Cost: O(|w| k)."""
    _check(w, m.alphabet)
    ctx = START * m.k  # @line L1
    p = Fraction(1)
    for i in range(len(w) + 1):  # @line L2
        a = w[i] if i < len(w) else END  # @line L3
        p *= next_prob(m, ctx, a)  # @line L4
        ctx = shift(ctx, a, m.k)  # @line L5
    return p


def strength_bits(m: MarkovModel, w: str) -> float:
    """-log2 P(w), the strength in bits (L6). Infinite when P(w) = 0."""
    p = probability(m, w)
    if p == 0:
        return math.inf
    return math.log2(p.denominator) - math.log2(p.numerator)  # @line L6


def guess_number(m: MarkovModel, w: str, max_len: int) -> int:
    """1 + the number of strings of length at most max_len whose probability
    is higher than P(w). It counts and never lists the strings.

    A prefix has probability at least that of each string that extends it, so
    the search stops at each prefix whose probability is at most P(w).
    Cost: O(G |alphabet| k) for G strings counted, plus the pruned prefixes.
    """
    target = probability(m, w)
    count = 0
    stack = [("", START * m.k, Fraction(1))]
    while stack:
        prefix, ctx, p = stack.pop()
        if p <= target:
            continue
        if p * next_prob(m, ctx, END) > target:
            count += 1
        if len(prefix) == max_len:
            continue
        for a in m.alphabet:
            q = p * next_prob(m, ctx, a)
            stack.append((prefix + a, shift(ctx, a, m.k), q))
    return count + 1


def sample_probabilities(m: MarkovModel, rng: random.Random, count: int, max_len: int) -> list[Fraction]:
    """The probabilities of count strings drawn from the model, cut at max_len.
    Only the probabilities are returned. Precondition: delta > 0.
    Cost: O(count max_len |alphabet|)."""
    if m.delta <= 0:
        raise ValueError("sampling needs delta > 0")
    symbols = list(m.alphabet) + [END]
    out = []
    for _ in range(count):
        ctx = START * m.k
        p = Fraction(1)
        for _ in range(max_len + 1):
            probs = [next_prob(m, ctx, a) for a in symbols]
            u = Fraction(rng.random())
            j = 0
            acc = probs[0]
            while u >= acc and j + 1 < len(symbols):
                j += 1
                acc += probs[j]
            p *= probs[j]
            if symbols[j] == END:
                break
            ctx = shift(ctx, symbols[j], m.k)
        else:
            p = Fraction(0)  # cut at max_len: counted as probability 0
        out.append(p)
    return out


def estimate_guess_number(target: Fraction, sample_probs: list[Fraction]) -> float:
    """The Monte Carlo estimate of Dell'Amico and Filippone (2015): each sample
    s with P(s) > target stands for 1 / (m P(s)) strings above the target.
    The estimate of the count is unbiased; the result adds 1 for the rank."""
    m = len(sample_probs)
    total = sum((1 / (m * p) for p in sample_probs if p > target), Fraction(0))
    return float(total) + 1
test_markov_password_model.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/markov-password-model/. The authors are listed in prov/Q34M2V.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from markov_password_model import (
    END,
    START,
    estimate_guess_number,
    guess_number,
    next_prob,
    probability,
    sample_probabilities,
    strength_bits,
    train,
)

# The training lists are made up in the test from a seeded generator. No real
# password list is used.


def made_up_list(rng: random.Random, alphabet: str, size: int, max_len: int) -> list:
    return ["".join(rng.choice(alphabet) for _ in range(rng.randint(1, max_len))) for _ in range(size)]


def oracle_probability(passwords: list, k: int, alphabet: str, delta: Fraction, w: str) -> Fraction:
    """Count each transition again by a scan of the padded strings."""
    padded = [START * k + x + END for x in passwords]
    sigma = len(set(alphabet)) + 1
    target = START * k + w + END
    p = Fraction(1)
    for i in range(k, len(target)):
        ctx, a = target[i - k : i], target[i]
        c_ctx = sum(1 for x in padded for j in range(k, len(x)) if x[j - k : j] == ctx)
        c_pair = sum(1 for x in padded for j in range(k, len(x)) if x[j - k : j] == ctx and x[j] == a)
        den = c_ctx + delta * sigma
        p *= Fraction(0) if den == 0 else (c_pair + delta) / den
    return p


PAGE_LIST = ["ab1", "ab11", "abab", "b1", "ba1", "a1", "ab", "bb1"]


def test_page_example() -> None:
    m = train(PAGE_LIST, 1, "ab1", Fraction(1))
    assert m.totals == {START: 8, "1": 7, "a": 7, "b": 9}
    assert probability(m, "ab1") == Fraction(1, 2) * Fraction(6, 11) * Fraction(5, 13) * Fraction(7, 11)
    assert probability(m, "ab1") == Fraction(105, 1573)
    assert round(strength_bits(m, "ab1"), 2) == 3.91
    assert probability(m, "1b") == Fraction(1, 12) * Fraction(1, 11) * Fraction(3, 13)
    assert round(strength_bits(m, "1b"), 2) == 9.16
    assert [guess_number(m, w, 12) for w in ["ab1", "ba", "1b", "b1a"]] == [5, 24, 50, 80]


def test_against_recount() -> None:
    rng = random.Random(2012)
    checked = 0
    for _ in range(120):
        alphabet = rng.choice(["ab", "ab1", "a1!"])
        passwords = made_up_list(rng, alphabet, rng.randint(1, 8), 5)
        k = rng.randint(0, 3)
        delta = rng.choice([Fraction(0), Fraction(1, 10), Fraction(1, 2), Fraction(1)])
        m = train(passwords, k, alphabet, delta)
        for _ in range(5):
            w = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 5)))
            assert probability(m, w) == oracle_probability(passwords, k, alphabet, delta, w)
            checked += 1
    assert checked == 600


def test_probabilities_sum_to_one() -> None:
    """With delta > 0 the strings of length at most L and the prefixes of
    length L + 1 carry all the mass, exactly."""
    rng = random.Random(5)
    for _ in range(12):
        alphabet = rng.choice(["ab", "a1"])
        passwords = made_up_list(rng, alphabet, rng.randint(1, 6), 4)
        k = rng.randint(0, 2)
        m = train(passwords, k, alphabet, rng.choice([Fraction(1, 3), Fraction(1)]))
        L = 4
        total = sum(
            (probability(m, "".join(t)) for n in range(L + 1) for t in itertools.product(m.alphabet, repeat=n)),
            Fraction(0),
        )
        # mass of the prefixes of length L + 1 = P(prefix without the end symbol)
        no_end = Fraction(0)
        for t in itertools.product(m.alphabet, repeat=L + 1):
            w = "".join(t)
            p_with_end = probability(m, w)
            ctx = (START * k + w)[len(START * k + w) - k :] if k else ""
            no_end += p_with_end / next_prob(m, ctx, END)
        assert total + no_end == 1


def test_guess_number_against_enumeration() -> None:
    rng = random.Random(77)
    checked = 0
    for _ in range(60):
        alphabet = "ab"
        passwords = made_up_list(rng, alphabet, rng.randint(2, 6), 4)
        m = train(passwords, rng.randint(0, 2), alphabet, Fraction(1))
        max_len = 6
        all_strings = ["".join(t) for n in range(max_len + 1) for t in itertools.product("ab", repeat=n)]
        probs = {s: probability(m, s) for s in all_strings}
        for _ in range(4):
            w = rng.choice(all_strings[:31])  # length at most 4
            expected = 1 + sum(1 for s in all_strings if probs[s] > probs[w])
            assert guess_number(m, w, max_len) == expected
            checked += 1
    assert checked == 240


def test_ties_and_order() -> None:
    m = train(["ab", "ba"], 0, "ab", Fraction(0))
    # order 0 with these counts: P(a) = P(b) = P(END) = 1/3
    assert probability(m, "ab") == probability(m, "ba") == Fraction(1, 27)
    assert guess_number(m, "ab", 4) == 1 + 1 + 2  # the empty string and "a", "b"
    assert probability(m, "") == Fraction(1, 3)


def test_unseen_with_no_smoothing() -> None:
    m = train(["aa"], 1, "ab", Fraction(0))
    assert probability(m, "ab") == 0
    assert strength_bits(m, "ab") == math.inf
    with pytest.raises(ValueError):
        probability(m, "ac")
    with pytest.raises(ValueError):
        train(["a\x03"], 1, "a\x03")


def test_monte_carlo_estimate() -> None:
    """The estimate of Dell'Amico and Filippone is close to the exact count."""
    rng = random.Random(2015)
    m = train(made_up_list(random.Random(9), "ab1", 20, 4), 1, "ab1", Fraction(1, 2))
    samples = sample_probabilities(m, rng, 4000, 12)
    for w in ["ab", "a1b", "bb11", "1a1a1"]:
        exact = guess_number(m, w, 12)
        est = estimate_guess_number(probability(m, w), samples)
        assert abs(est - exact) <= 0.2 * exact, (w, est, exact)

History

Shannon used n-gram models of text in 1951 to estimate the entropy of English. Narayanan and Shmatikov (2005) applied character Markov models to passwords. Castelluccia, Duermuth and Perito (NDSS 2012) used n-gram models for adaptive strength meters. Ma, Yang, Luo and Li (2014) compared Markov and PCFG models with probability threshold graphs and showed the effect of smoothing and normalization. Dell'Amico and Filippone (2015) gave the Monte Carlo estimate of the guess number, which makes the comparison of models on large lists practical.

References

  1. Arvind Narayanan and Vitaly Shmatikov, Fast dictionary attacks on passwords using time-space tradeoff, ACM CCS 2005, pages 364 to 372, the Markov models of passwords and the threshold on the probability of a string
  2. Claude Castelluccia, Markus Duermuth and Daniele Perito, Adaptive password-strength meters from Markov models, NDSS 2012, the n-gram model of the meter, its training on the password list of the service, and the score as minus the log of the probability
  3. Jerry Ma, Weining Yang, Min Luo and Ninghui Li, A study of probabilistic password models, IEEE Symposium on Security and Privacy 2014, pages 689 to 704, doi:10.1109/SP.2014.50, the comparison of Markov and PCFG models, smoothing, the end symbol and normalization, and probability threshold graphs
  4. Matteo Dell'Amico and Maurizio Filippone, Monte Carlo strength evaluation, fast and reliable password checking, ACM CCS 2015, pages 158 to 169, doi:10.1145/2810103.2813631, the estimator of the guess number from a sample of the model and its unbiasedness

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/Q34M2V/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example