Algorithmadvanced
Probabilistic context-free grammar password model
Also called PCFG password cracking, Weir password grammar.
Estimates password strength with a grammar of letter, digit and symbol runs learned from a password list. A password scores -log2 of its probability, and its guess number is its rank.
- Time
- Θ(n) worst · average · best
- Space
- O(n) extra
- Where
- N = the number of characters in the training list; n = the length of the password
- Model
- Word RAM
- Properties
- deterministicoffline
- Evidence
- Full proofCode in 1 languages
- Origin
- Matt Weir, Sudhir Aggarwal, Breno de Medeiros, Bill Glodek, Patrick Gage Kelley, Saranga Komanduri, Michelle Mazurek, 2009
The PCFG password model estimates how strong a password is. It treats a password as a sequence of runs of letters, digits and other symbols, so that love12 is the letter run love followed by the digit run 12, with the base structure L4 D2. A probabilistic context-free grammar learned from a password list gives each base structure a probability and, for each tag and length, each run a probability. The probability of a password is the product of the probability of its structure and of its runs, its strength is bits, and its guess number is plus the number of strings with a higher probability. Scoring takes time for a password of characters. The numbers are estimates under the model and its training list, not a guarantee against all attackers. Weir et al. (2009) introduced the grammar to order guesses for password recovery; this page uses it only to score passwords and to count more likely strings.
In plain words
Many people build a password from parts: a word, then some digits, then maybe a symbol. The model learns two things from a list of passwords. It learns how common each pattern of parts is, such as "four letters then two digits". It also learns how common each part is, such as the digits 12 among all two-digit parts.
To judge a password, the model cuts it into parts, looks up the chance of its pattern and the chance of each part, and multiplies them. A password that follows a common pattern with common parts gets a high chance and is weak. A password with a rare pattern or rare parts gets a small chance and is strong. A meter can also count how many passwords the model thinks are more likely, which estimates how many guesses a careful guesser would need.
The problem
Each character has a tag: L for a letter, D for a digit and S for any other character. A run of a string is a maximal block of characters with the same tag, and the base structure is the list of (tag, length) pairs of the runs of . The input is a training list of non-empty passwords and a password . Training counts , the number of passwords with structure , and , the number of times is a run with tag and length in the list. The model is
where are the runs of . The outputs are the strength and the guess number .
The algorithm
PCFG-SCORE(w, P)- 1
x_1, ..., x_r ← the maximal runs of w - 2
s ← ((tag(x_1), |x_1|), ..., (tag(x_r), |x_r|)) - 3
p ← P(s) ▷ 0 if s was not seen - 4
for i ← 1 to r do - 5
p ← p · P(x_i | tag(x_i), |x_i|) ▷ 0 if x_i was not seen - 6
return p
Training is one pass over the list. It splits each password as line L1 does, adds 1 to the count of its structure and to the count of each run in its slot, and divides each count by the total of its group. The strength is , and the code computes it from the numerator and denominator of the exact fraction .
Guess numbers. A string has a positive probability only if its structure and all its runs were seen, so there are finitely many such strings. For each structure the code sorts the runs of each slot by decreasing probability and does a depth-first search over the choices of runs. It stops a branch as soon as the partial product, times the best choice for each remaining slot, is at most . The search counts the strings above the threshold and never lists them. For large models, the Monte Carlo estimate of Dell'Amico and Filippone (2015), described on the Markov password model page, works for this model as well.
Example
The training list is made up: love12, love12, star12, love!, star99, moon1, love99 and sun!!. There are four structures: L4 D2 with 5 passwords, and L4 S1, L4 D1 and L3 S2 with 1 each. Among the 7 letter runs of length 4, love occurs 4 times, star 2 times and moon once. Among the 5 digit runs of length 2, 12 occurs 3 times and 99 2 times. Scoring love12 goes as follows.
| line | step | factor | |
|---|---|---|---|
| L1, L2 | runs love, 12; structure L4 D2 |
||
| L3 | 5/8 | 5/8 | |
| L5 | 4/7 | 5/14 | |
| L5 | 3/5 | 3/14 |
So , the strength is about 2.22 bits, and no string is more likely, so its guess number is 1. The model gives a positive probability to exactly 13 strings, and their probabilities add up to 1. Some of them score as follows.
| password | strength in bits | guess number | |
|---|---|---|---|
love12 |
3/14 | 2.22 | 1 |
sun!! |
1/8 | 3.00 | 3 |
star99 |
1/14 | 3.81 | 5 |
love1 |
1/14 | 3.81 | 5 |
moon99 |
1/28 | 4.81 | 9 |
moon1 |
1/56 | 5.81 | 12 |
lovestar |
0 | infinite | none |
The string love1 was never in the list, but its structure and runs were, so it gets the same probability as star99, which was. The string lovestar has the structure L8, which was never seen, so its probability is 0.
Correctness
Because each run is a maximal block of one tag, and two neighbouring slots of a learned structure have different tags, each string has at most one derivation in the grammar. So the product of lines L3 to L5 is the probability of the string, not of one of several parses. The same fact gives a one to one map from the choices of a structure and its runs to the strings with a positive probability, so the probabilities of all strings add up to 1. The relative frequencies are the maximum likelihood rule probabilities for the training list. The guess number search is exact, because the runs of each slot are sorted, so once a choice cannot beat the threshold, no later choice can. The full proofs are in proofs/correctness.md.
Proof: The PCFG password model is unambiguous, sums to 1, and its guess numbers are exactfull
We use the pseudocode PCFG-SCORE of the page. Each character has one tag: L for a letter, D for a digit and S for any other character. A run of a string is a maximal block of consecutive characters with the same tag. The segmentation of is the list of its runs , and its base structure is , where is the tag of and . We call a pair a slot.
Training on a list of non-empty passwords counts , the number of passwords with base structure , and , the number of times is a run in slot over the whole list. Let . The model is
and these are the rule probabilities of the grammar with the rules for each with and for each with . We write for the set of structures and for the set of runs with a positive count in slot .
Fact 1. Each has no two neighbouring slots with the same tag, and each is a string of characters, all with tag .
Proof. Both come from the segmentation of a training password. Two neighbouring runs have different tags, since otherwise they would form one longer block, and a run has one tag and its own length.
Claim 1 (one derivation). Each string has at most one derivation in the grammar. If it has one, it uses the rule of and the rules for the runs of .
Proof. Take a derivation with structure and terminals , so . By Fact 1, each is a block of characters with tag , and . So each block is maximal: it cannot extend into a neighbour with another tag. The maximal blocks of are its runs, so for each and .
Claim 2 (the score). PCFG-SCORE returns , which is the probability of under the grammar.
Proof. Line L1 computes the runs and line L2 the base structure. Line L3 sets to , which is 0 when the structure was not seen. The loop of lines L4 and L5 keeps the invariant that after steps , where an unseen run gives the factor 0. Line L6 returns the full product. The probability of a string under a grammar is the sum of the probabilities of its derivations. By Claim 1 there is at most one, and its probability is this product; if there is none, some factor is 0.
Claim 3 (a distribution). , where the sum is over all strings.
Proof. By Claim 1 the map from a structure and a choice of runs to the string is one to one, and its image is the set of strings with . So
since each inner sum is and the counts add up to .
Claim 4 (maximum likelihood). Among all choices of rule probabilities for the same grammar, the relative frequencies maximize the probability of the training list.
Proof. By Claim 2 the log likelihood of the list is
The first sum and each slot of the second depend on separate distributions. For one of them, with counts and total , the term is , and by Gibbs' inequality it is largest exactly when .
Claim 5 (guess numbers). For , COUNT-ABOVE of the code returns . So GUESS-NUMBER returns when .
Proof. By the one to one map in the proof of Claim 3, it is enough to count, for each , the choices of runs with . The code sorts each list by decreasing probability and sets . A node of the search is a prefix of choices with the partial product . Each completion of this prefix with has a probability of at most . When this bound is at most for some , it is also at most for each later in the sorted list, so the code stops the loop and loses no counted completion. Each other choice is pushed once, so each complete choice with a product above is reached once and counted once, and a complete choice is reached only if its bound, which is then its own product, is above .
The code counts the strings and does not list them.
Cost. Line L1 reads once, for . Line L2 builds a tuple of slots, and line L3 hashes it in . Each lookup of line L5 hashes the run in , and . So PCFG-SCORE takes time and extra space for the runs on the word-RAM. Training does the same for each password, so it takes time for characters in the list. COUNT-ABOVE takes work for each node it pushes, and each pushed node is a prefix of a counted string, so its time is plus the sorting, where is the count it returns.
Complexity
- Scoring. Line L1 reads once, line L3 hashes a structure of at most slots, and the lookups of line L5 hash runs whose lengths add up to . So the time is on the word-RAM, with extra space for the runs.
- Training. The same work for each password, so time for characters. The tables hold at most one entry for each distinct structure and each distinct run.
- Exact guess numbers. Each node of the search is a prefix of a counted string, so the time is plus the sorting, for structures of at most slots and a count . It grows with the guess number and is only for small models, as in the test.
Properties
- Unambiguous. Each string has at most one parse, so there is no sum over parses and no choice of the best parse.
- A proper distribution with finite support. The probabilities add up to 1, but only over the strings built from seen structures and seen runs. Every other string has probability 0.
- Exact arithmetic. The code multiplies fractions, so ties are exact, as for
star99andlove1above. - An estimate, not a measure. The scores depend on the training list. A password unlike the list can still be weak against another list.
Variants and improvements
- Dictionaries for letters. In Weir et al. (2009) the probabilities of structures and of digit and symbol runs were learned, and the letter runs came from dictionaries. Kelley et al. (2012) learned the letter runs from the training data, as on this page. A dictionary covers more words, but its probabilities do not come from the list.
- Case and other tags. Later work adds a separate pattern for upper and lower case, and tags for keyboard patterns, dates or multi-word runs. Each new tag must keep the segmentation unique, or the grammar becomes ambiguous.
- Smoothing. Giving unseen runs and structures a small probability removes the infinite scores. Ma et al. (2014) compared smoothed PCFG and Markov models and found that well-smoothed Markov models did at least as well in their study.
- Order of guesses. Weir et al. listed strings in decreasing probability with a priority queue over partly filled structures. This page does not list strings; a strength meter needs only the count.
When to use it
Use a PCFG model to estimate strength in a meter, or to compare password policies on a test list, when passwords are made of words, digits and symbols. It is simple to train, it scores in one pass, and its parts are easy to explain to a user, for example "a common word followed by a common number". It gives probability 0 to strings outside its support, so a meter needs smoothing or a fallback. A Markov model gives a probability to every string. Neither model protects stored passwords; for that use slow password hashing, and to detect a stolen password file use honeywords.
Pitfalls
- Runs that are not maximal. If line L1 splits a block of one tag into smaller pieces, a string has several parses, and the product of line L5 is the probability of one parse, not of the string. The probabilities then add up to more or less than 1. Line L1 must cut only where the tag changes.
- No structure factor. If line L3 sets instead of , every structure counts as if it were certain, and a rare pattern such as L3 S2 scores as weak as a common one. Line L3 must start from .
- Runs not split by length. If line L5 uses over runs of all lengths instead of , the mass of a slot spreads over runs that cannot fill it, and the probabilities add up to less than 1. Line L5 must condition on the tag and the length.
- Zero for new words. Without smoothing, line L5 gives 0 for a run not seen in training, so a weak password with one new word scores as infinitely strong. A meter must smooth or fall back to another model.
- Floating point underflow. A product of many small factors can round to 0. Add logarithms or keep exact fractions.
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/pcfg-password-model/. The authors are listed in prov/RSR0DF.jsonl.
"""A probabilistic context-free grammar of passwords, used to estimate strength.
A password is split into maximal runs of letters (L), digits (D) and other
symbols (S). The base structure is the list of (tag, length) pairs, for
example L3 D2 for "abc12". Following Weir et al. (2009), with the letter runs
learned from the training list as in Kelley et al. (2012), the grammar has a
rule START -> structure for each base structure seen in training, and a rule
(tag, length) -> x for each run x seen in training, each with its relative
frequency. The probability of a password is the probability of its one
derivation: P(structure) times the product of P(run | tag, length). A run or
structure not seen in training gives probability 0.
The guess number of w is 1 plus the number of strings with a higher
probability. It is an estimate under the model and its training list. The
code counts these strings and never lists them.
"""
import math
from fractions import Fraction
from typing import NamedTuple
Structure = tuple # ((tag, length), ...)
class PCFGModel(NamedTuple):
structures: dict # Structure -> Fraction
runs: dict # (tag, length) -> {run string: Fraction}
def tag_of(ch: str) -> str:
"""L for an ASCII letter, D for an ASCII digit, S for any other character."""
if ch.isascii() and ch.isalpha():
return "L"
if ch.isascii() and ch.isdigit():
return "D"
return "S"
def segment(w: str) -> list[tuple[str, str]]:
"""The maximal runs of w with their tags. Cost: O(len(w))."""
out: list[tuple[str, str]] = []
i = 0
while i < len(w):
t = tag_of(w[i])
j = i + 1
while j < len(w) and tag_of(w[j]) == t:
j += 1
out.append((t, w[i:j]))
i = j
return out
def structure_of(segs: list[tuple[str, str]]) -> Structure:
return tuple((t, len(x)) for t, x in segs)
def train(passwords: list[str]) -> PCFGModel:
"""Relative frequencies of the base structures and of the runs.
Precondition: at least one non-empty password. Cost: O(N) for N characters.
"""
s_count: dict = {}
r_count: dict = {}
for w in passwords:
if not w:
continue
segs = segment(w)
s = structure_of(segs)
s_count[s] = s_count.get(s, 0) + 1
for t, x in segs:
d = r_count.setdefault((t, len(x)), {})
d[x] = d.get(x, 0) + 1
total = sum(s_count.values())
if total == 0:
raise ValueError("the training list has no non-empty password")
structures = {s: Fraction(c, total) for s, c in s_count.items()}
runs = {}
for key, d in r_count.items():
n = sum(d.values())
runs[key] = {x: Fraction(c, n) for x, c in d.items()}
return PCFGModel(structures, runs)
def probability(m: PCFGModel, w: str) -> Fraction:
"""PCFG-SCORE of the page, as an exact probability. Cost: O(len(w))."""
segs = segment(w) # @line L1
s = structure_of(segs) # @line L2
p = m.structures.get(s, Fraction(0)) # @line L3
for t, x in segs: # @line L4
p *= m.runs.get((t, len(x)), {}).get(x, Fraction(0)) # @line L5
return p # @line L6
def strength_bits(m: PCFGModel, w: str) -> float:
"""-log2 P(w); infinite when the model gives w probability 0."""
p = probability(m, w)
if p == 0:
return math.inf
return math.log2(p.denominator) - math.log2(p.numerator)
def count_above(m: PCFGModel, t: Fraction) -> int:
"""The number of strings v with P(v) > t, for t > 0.
For each structure, it walks the runs of each slot in decreasing order of
probability and stops as soon as even the best choice for the remaining
slots cannot beat t. Cost: O(r) per string counted plus the cut-offs, for
structures of at most r slots.
"""
if t <= 0:
raise ValueError("the threshold must be positive")
total = 0
for s, ps in m.structures.items():
lists = [sorted(m.runs[key].values(), reverse=True) for key in s]
best_rest = [Fraction(1)] * (len(s) + 1) # product of the best choice of slots i..r-1
for i in range(len(s) - 1, -1, -1):
best_rest[i] = best_rest[i + 1] * lists[i][0]
stack = [(0, ps)]
while stack:
i, p = stack.pop()
if i == len(s):
total += 1
continue
for q in lists[i]:
if p * q * best_rest[i + 1] <= t:
break # the lists are sorted, so no later choice is better
stack.append((i + 1, p * q))
return total
def guess_number(m: PCFGModel, w: str) -> int:
"""1 + the number of strings more probable than w. Precondition: P(w) > 0."""
p = probability(m, w)
if p == 0:
raise ValueError("the model gives this password probability 0")
return count_above(m, p) + 1
test_pcfg_password_model.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pcfg-password-model/. The authors are listed in prov/RSR0DF.jsonl.
import itertools
import math
import random
import re
from fractions import Fraction
import pytest
from pcfg_password_model import (
count_above,
guess_number,
probability,
segment,
strength_bits,
train,
)
# The training lists are made up in the test, by hand or from a seeded
# generator. No real password list is used.
RUN = re.compile(r"[A-Za-z]+|[0-9]+|[^A-Za-z0-9]+")
def oracle_probability(passwords: list, w: str) -> Fraction:
"""Split with a regular expression and count again from the list."""
def tag(x: str) -> str:
return "L" if x[0].isalpha() else "D" if x[0].isdigit() else "S"
def shape(x: str) -> tuple:
return tuple((tag(r), len(r)) for r in RUN.findall(x))
train_list = [x for x in passwords if x]
s = shape(w)
p = Fraction(sum(1 for x in train_list if shape(x) == s), len(train_list))
all_runs = [r for x in train_list for r in RUN.findall(x)]
for r in RUN.findall(w):
same_slot = [y for y in all_runs if tag(y) == tag(r) and len(y) == len(r)]
if not same_slot:
return Fraction(0)
p *= Fraction(same_slot.count(r), len(same_slot))
return p
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)]
PAGE_LIST = ["love12", "love12", "star12", "love!", "star99", "moon1", "love99", "sun!!"]
def test_segment() -> None:
assert segment("love12") == [("L", "love"), ("D", "12")]
assert segment("ab 12!x") == [("L", "ab"), ("S", " "), ("D", "12"), ("S", "!"), ("L", "x")]
assert segment("éa") == [("S", "é"), ("L", "a")]
assert segment("") == []
def test_page_example() -> None:
m = train(PAGE_LIST)
L4D2 = (("L", 4), ("D", 2))
assert m.structures[L4D2] == Fraction(5, 8)
assert m.runs[("L", 4)] == {"love": Fraction(4, 7), "star": Fraction(2, 7), "moon": Fraction(1, 7)}
assert m.runs[("D", 2)] == {"12": Fraction(3, 5), "99": Fraction(2, 5)}
assert probability(m, "love12") == Fraction(3, 14)
assert probability(m, "moon99") == Fraction(1, 28)
assert probability(m, "sun!!") == Fraction(1, 8)
assert probability(m, "lovestar") == 0
assert probability(m, "love13") == 0
assert round(strength_bits(m, "love12"), 2) == 2.22
assert round(strength_bits(m, "moon99"), 2) == 4.81
got = [guess_number(m, w) for w in ["love12", "sun!!", "star99", "love!", "love1", "moon99", "moon1"]]
assert got == [1, 3, 5, 5, 5, 9, 12]
assert count_above(m, Fraction(1, 10**6)) == 13
def test_against_recount() -> None:
rng = random.Random(2009)
checked = 0
for _ in range(150):
alphabet = rng.choice(["ab1", "a12!", "ab1!.", "a1"])
passwords = made_up_list(rng, alphabet, rng.randint(1, 10), 6)
m = train(passwords)
for _ in range(4):
if rng.random() < 0.5:
w = rng.choice(passwords)
else:
w = "".join(rng.choice(alphabet) for _ in range(rng.randint(1, 6)))
assert probability(m, w) == oracle_probability(passwords, w)
checked += 1
assert checked == 600
def all_strings(alphabet: str, max_len: int) -> list:
return ["".join(t) for n in range(1, max_len + 1) for t in itertools.product(alphabet, repeat=n)]
def test_sum_is_one_and_guess_numbers() -> None:
"""Each string with a positive probability has the length of a training
password, so a brute force over all short strings sees all of them."""
rng = random.Random(12)
checked = 0
for _ in range(40):
alphabet = rng.choice(["a1!", "ab1", "a1"])
passwords = made_up_list(rng, alphabet, rng.randint(1, 8), 4)
m = train(passwords)
universe = all_strings(alphabet, 4)
probs = {s: probability(m, s) for s in universe}
assert sum(probs.values(), Fraction(0)) == 1
positive = [s for s in universe if probs[s] > 0]
for w in rng.sample(positive, min(4, len(positive))):
expected = 1 + sum(1 for s in positive if probs[s] > probs[w])
assert guess_number(m, w) == expected
checked += 1
for t in [Fraction(1, 2), Fraction(1, 7), Fraction(1, 100)]:
assert count_above(m, t) == sum(1 for s in positive if probs[s] > t)
assert checked >= 100
def test_count_above_on_a_larger_model() -> None:
"""Compare the pruned count with a full product over the run lists."""
rng = random.Random(31)
passwords = made_up_list(rng, "abc12!", 60, 7)
m = train(passwords)
every = []
for s, ps in m.structures.items():
for combo in itertools.product(*[list(m.runs[key].values()) for key in s]):
p = ps
for q in combo:
p *= q
every.append(p)
assert sum(every, Fraction(0)) == 1
for t in sorted(set(every))[:: max(1, len(set(every)) // 25)]:
assert count_above(m, t) == sum(1 for p in every if p > t)
def test_bad_input() -> None:
m = train(["ab1", "", "cd2"])
assert probability(m, "ab") == 0
assert strength_bits(m, "ab") == math.inf
with pytest.raises(ValueError):
guess_number(m, "ab")
with pytest.raises(ValueError):
count_above(m, Fraction(0))
with pytest.raises(ValueError):
train(["", ""])
History
Weir, Aggarwal, de Medeiros and Glodek (IEEE Symposium on Security and Privacy 2009) learned a probabilistic grammar of base structures from a password list and used it to order guesses by probability. Kelley et al. (2012) built a guess number calculator on this grammar, with letter runs learned from training data, to compare password composition policies. Ma, Yang, Luo and Li (2014) compared PCFG and Markov models with probability threshold graphs. Dell'Amico and Filippone (2015) gave a Monte Carlo estimate of guess numbers that applies to this model and makes strength estimates for large models practical.
References
- Matt Weir, Sudhir Aggarwal, Breno de Medeiros and Bill Glodek, Password cracking using probabilistic context-free grammars, IEEE Symposium on Security and Privacy 2009, pages 391 to 405, the base structures of letter, digit and symbol runs, the learned probabilities of structures and of digit and symbol runs, and the order of guesses by probability
- Patrick Gage Kelley, Saranga Komanduri, Michelle L. Mazurek, Richard Shay, Timothy Vidas, Lujo Bauer, Nicolas Christin, Lorrie Faith Cranor and Julio Lopez, Guess again (and again and again), measuring password strength by simulating password-cracking algorithms, IEEE Symposium on Security and Privacy 2012, pages 523 to 537, the guess number calculator, the PCFG with letter runs learned from training data, and the comparison of password policies
- 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 PCFG and Markov models with 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 estimate of guess numbers from a sample, applied to PCFG and other models
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 RSR0DF Edit this page History Report an error Markdown