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
- Model
- Word RAM
- Properties
- deterministiconline
- Evidence
- Full proofCode in 1 languages
- 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 characters before it, and an end symbol closes the string. The trained model gives each password a probability . The strength is bits, and the guess number is the rank of 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, time for a password of 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 , an order , a smoothing constant , and a password . Let , counting the end symbol . Each password in the list is padded with start symbols in front and at the end. For each context of symbols and each next symbol , training counts , the number of times follows , and . The model is
where and is the last symbols before position . The outputs are the strength and the guess number .
The algorithm
MARKOV-SCORE(w, N, k, δ, σ)- 1
c ← ▷^k ; p ← 1 ▷ k start symbols - 2
for i ← 1 to |w| + 1 do - 3
a ← w[i] if i ≤ |w|, else ⊣ ▷ the end symbol - 4
p ← p · (N(c, a) + δ) / (N(c) + δσ) - 5
c ← the last k symbols of c·a - 6
return -log2 p
Training is one pass over the padded list that adds 1 to and for each symbol. Line L4 is the smoothed probability of the next symbol; with it is the maximum likelihood estimate, and an unseen step gives probability 0 and strength . The end symbol of line L3 makes 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 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 . This is exact but can take time proportional to the guess number. Dell'Amico and Filippone (2015) estimate it instead from strings drawn from the model: each with stands for 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 . With there are four contexts: the start, with ; a, with ; b, with ; and 1, with . With and , scoring ab1 goes as follows.
| context | symbol | 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 and the strength is bits. Only 4 strings have a higher probability, so the guess number is 5. The other strings score as follows.
| password | 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 , is the context and is the product of the first factors, so line L6 returns . For the probabilities of all finite strings sum to 1: the mass of the strings of length at most plus the mass of the prefixes of length is exactly 1 for each , and the second part shrinks geometrically because each context gives the end symbol a probability of at least . With 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 is drawn with probability and weighted by . 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 , the order is , and counts the characters and the end symbol . For a context (a string of symbols over and the start symbol) and a symbol , the trained model has counts and , and
For a string let and let be the last symbols of , where is the start symbol.
Claim 1 (the score). MARKOV-SCORE returns with .
Proof. The loop of line L2 keeps the invariant: before the iteration for , and . Line L1 makes it true for , since and the empty product is 1. Line L3 picks , line L4 multiplies by , and line L5 sets to the last symbols of , which is . After the iteration for , , and line L6 returns .
Claim 2 (a distribution). For each context , when the denominator is positive. If , then over all finite strings over .
Proof. The first part is . For the second, let be the probability of the prefix without the end symbol, so and of . We show by induction on that
For the first sum is empty and the second is . To go from to , split each with by its next symbol: the end symbol gives , a character gives . This is the identity that the test checks with exact fractions.
There are finitely many contexts, so when , since then . Each step that is not the end has probability at most in total, so , which tends to 0.
With 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 .
Claim 3 (maximum likelihood). With , the values maximize the likelihood of the training list among all order- models.
Proof. The log likelihood of the list is . The terms for different contexts are independent. For one context with and empirical distribution , the term is , and by Gibbs' inequality this is largest exactly when .
Claim 4 (guess numbers). GUESS-NUMBER of the code returns .
Proof. Each factor is at most 1, so for each prefix and each that extends it, . The search starts at the empty prefix and skips the subtree of when ; no string in that subtree can have . Each other prefix is visited once, counted when , and extended by each character while . So each string of length at most with is counted once, and no other string is.
Claim 5 (the Monte Carlo estimate). Let be independent draws from the model and a threshold. Then
has expectation .
Proof. By linearity, . This set is finite for , since . When the draws are cut at length , as in the code, the same computation gives the count of strings of length at most .
The estimate of the guess number of is with . 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 symbols in a hash table, so MARKOV-SCORE takes time for on the word-RAM, or when is a constant, and extra space. Training reads each of the symbols of the padded list once and does one lookup for each, so it takes time, and the tables hold at most contexts of symbols.
Complexity
- Scoring. Line L4 runs times, each with a hash table lookup of a context of symbols, so the time is on the word-RAM, or for a fixed order. The extra space is for the context.
- Training. One lookup for each of the symbols of the padded list, so time. The model stores at most contexts, and in the worst case 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 strings costs for strings of length at most . After sorting the probabilities and taking suffix sums of , each estimate is a binary search, .
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 , 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 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 . 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 , the product is the probability of 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 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 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 symbols instead of the last , each step uses a stale context. The context is the last symbols of .
- 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Q34M2V Edit this page History Report an error Markdown