Skip to content

Commit

Permalink
Add basic entropy function.
Browse files Browse the repository at this point in the history
Add a metric entropy function check, but do not configure it to execute.
I need to look over how this is structured to determine how I want to
handle new checks.
  • Loading branch information
hosom committed May 14, 2018
1 parent dfff799 commit fafe11c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
27 changes: 27 additions & 0 deletions passfilt-server/checkpass.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"crypto/sha1"
"fmt"
"math"
"net/http"
"strings"
"sync"
Expand Down Expand Up @@ -50,6 +51,32 @@ func isPwnd(p string) bool {
return false
}

// metricEntropy tries to measure the 'randomness' of a password
// it returns the shannon entropy divided by the length of the
// password.
func metricEntropy(pass string) float64 {
m := map[rune]float64{}
for _, r := range pass {
m[r]++
}

var hx float64
for _, val := range m {
hx += val * math.Log2(val)
}

l := float64(len(pass))
hx = (math.Log2(l) - (hx / l))

mEntropy := hx / l

if math.IsNaN(mEntropy) {
return 0.0
}

return mEntropy
}

func checkpass(user string, pass string, banlist *sync.Map) bool {
// by default, passwords are considered OK
passOk := true
Expand Down
13 changes: 13 additions & 0 deletions passfilt-server/checkpass_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,16 @@ func TestIsPwnd(t *testing.T) {
t.Error("Random password detected as pwnd.")
}
}

func TestMetricEntropy(t *testing.T) {
s := "abbcccdddd"

if metricEntropy(s) != 0.18464393446710153 {
t.Error("Failed to calculate correct entropy.", metricEntropy(s))
}

s = ""
if metricEntropy(s) != 0 {
t.Error("Failed to handle empty string.", metricEntropy(s))
}
}

0 comments on commit fafe11c

Please sign in to comment.