1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
|
/*
* crunchy - find common flaws in passwords
* Copyright (c) 2017-2018, Christian Muehlhaeuser <muesli@gmail.com>
*
* For license see LICENSE
*/
package crunchy
import (
"bufio"
"encoding/hex"
"hash"
"os"
"path/filepath"
"strings"
"sync"
"unicode"
"unicode/utf8"
"github.com/xrash/smetrics"
)
// Validator is used to setup a new password validator with options and dictionaries
type Validator struct {
options Options
once sync.Once
wordsMaxLen int // length of longest word in dictionaries
words map[string]struct{} // map to index parsed dictionaries
hashedWords map[string]string // maps hash-sum to password
}
// Options contains all the settings for a Validator
type Options struct {
// MinLength is the minimum length required for a valid password (>=1, default is 8)
MinLength int
// MinDiff is the minimum amount of unique characters required for a valid password (>=1, default is 5)
MinDiff int
// MinDist is the minimum WagnerFischer distance for mangled password dictionary lookups (>=0, default is 3)
MinDist int
// Hashers will be used to find hashed passwords in dictionaries
Hashers []hash.Hash
// DictionaryPath contains all the dictionaries that will be parsed (default is /usr/share/dict)
DictionaryPath string
// Check haveibeenpwned.com database
CheckHIBP bool
}
// NewValidator returns a new password validator with default settings
func NewValidator() *Validator {
return NewValidatorWithOpts(Options{
MinDist: -1,
DictionaryPath: "/usr/share/dict",
CheckHIBP: false,
})
}
// NewValidatorWithOpts returns a new password validator with custom settings
func NewValidatorWithOpts(options Options) *Validator {
if options.MinLength <= 0 {
options.MinLength = 8
}
if options.MinDiff <= 0 {
options.MinDiff = 5
}
if options.MinDist < 0 {
options.MinDist = 3
}
return &Validator{
options: options,
words: make(map[string]struct{}),
hashedWords: make(map[string]string),
}
}
// indexDictionaries parses dictionaries/wordlists
func (v *Validator) indexDictionaries() {
if v.options.DictionaryPath == "" {
return
}
dicts, err := filepath.Glob(filepath.Join(v.options.DictionaryPath, "*"))
if err != nil {
return
}
for _, dict := range dicts {
file, err := os.Open(dict)
if err != nil {
continue
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
nw := normalize(scanner.Text())
nwlen := len(nw)
if nwlen > v.wordsMaxLen {
v.wordsMaxLen = nwlen
}
// if a word is smaller than the minimum length minus the minimum distance
// then any collisons would have been rejected by pre-dictionary checks
if nwlen >= v.options.MinLength-v.options.MinDist {
v.words[nw] = struct{}{}
}
for _, hasher := range v.options.Hashers {
v.hashedWords[hashsum(nw, hasher)] = nw
}
}
}
}
// foundInDictionaries returns whether a (mangled) string exists in the indexed dictionaries
func (v *Validator) foundInDictionaries(s string) error {
v.once.Do(v.indexDictionaries)
pw := normalize(s) // normalized password
revpw := reverse(pw) // reversed password
pwlen := len(pw)
// let's check perfect matches first
// we can skip this if the pw is longer than the longest word in our dictionary
if pwlen <= v.wordsMaxLen {
if _, ok := v.words[pw]; ok {
return &DictionaryError{ErrDictionary, pw, 0}
}
if _, ok := v.words[revpw]; ok {
return &DictionaryError{ErrMangledDictionary, revpw, 0}
}
}
// find hashed dictionary entries
if pwindex, err := hex.DecodeString(pw); err == nil {
if word, ok := v.hashedWords[string(pwindex)]; ok {
return &HashedDictionaryError{ErrHashedDictionary, word}
}
}
// find mangled / reversed passwords
// we can skip this if the pw is longer than the longest word plus our minimum distance
if pwlen <= v.wordsMaxLen+v.options.MinDist {
for word := range v.words {
if dist := smetrics.WagnerFischer(word, pw, 1, 1, 1); dist <= v.options.MinDist {
return &DictionaryError{ErrMangledDictionary, word, dist}
}
if dist := smetrics.WagnerFischer(word, revpw, 1, 1, 1); dist <= v.options.MinDist {
return &DictionaryError{ErrMangledDictionary, word, dist}
}
}
}
return nil
}
// Check validates a password for common flaws
// It returns nil if the password is considered acceptable.
func (v *Validator) Check(password string) error {
if strings.TrimSpace(password) == "" {
return ErrEmpty
}
if len(password) < v.options.MinLength {
return ErrTooShort
}
if countUniqueChars(password) < v.options.MinDiff {
return ErrTooFewChars
}
// Inspired by cracklib
maxrepeat := 3.0 + (0.09 * float64(len(password)))
if countSystematicChars(password) > int(maxrepeat) {
return ErrTooSystematic
}
err := v.foundInDictionaries(password)
if err != nil {
return err
}
if v.options.CheckHIBP {
err := foundInHIBP(password)
if err != nil {
return err
}
}
return nil
}
// Rate grades a password's strength from 0 (weak) to 100 (strong).
func (v *Validator) Rate(password string) (uint, error) {
if err := v.Check(password); err != nil {
return 0, err
}
l := len(password)
systematics := countSystematicChars(password)
repeats := l - countUniqueChars(password)
var letters, uLetters, numbers, symbols int
for len(password) > 0 {
r, size := utf8.DecodeRuneInString(password)
password = password[size:]
if unicode.IsLetter(r) {
if unicode.IsUpper(r) {
uLetters++
} else {
letters++
}
} else if unicode.IsNumber(r) {
numbers++
} else {
symbols++
}
}
// ADD: number of characters
n := l * 4
// ADD: uppercase letters
if uLetters > 0 {
n += (l - uLetters) * 2
}
// ADD: lowercase letters
if letters > 0 {
n += (l - letters) * 2
}
// ADD: numbers
n += numbers * 4
// ADD: symbols
n += symbols * 6
// REM: letters only
if l == letters+uLetters {
n -= letters + uLetters
}
// REM: numbers only
if l == numbers {
n -= numbers * 4
}
// REM: repeat characters (case insensitive)
n -= repeats * 4
// REM: systematic characters
n -= systematics * 3
if n < 0 {
n = 0
} else if n > 100 {
n = 100
}
return uint(n), nil
}
|