Simple Password Generation with Haskell

So, I’ve been using a custom password generator for a while. It’s great because it has some useful settings like “only generate alphanumeric passwords” or “only generate letters” to deal with stupid, legacy-code websites that refuse to modernize their password handling code. I use this generator to create 50-character passwords, because hey, if it’s randomly generated, then you might as well generate really long passwords! I recently upgraded the pseudorandom number generator (PRNG) to use a cryptographically secure PRNG (CPRNG), just for fun.

Anyway, here is the program:

-- LICENSE: PUBLIC DOMAIN
module Main where

import Control.Monad.State
import Crypto.Random.AESCtr
import Data.Binary (decode)
import qualified Data.ByteString.Lazy as B
import Data.List (nub)
import IO
import System (getArgs)
import System.IO (hSetEcho)

keysChar, keysNum, keysPunc, keysCharNum, keysAll, keysHex :: String
keysChar = ['a'..'z'] ++ ['A'..'Z']
keysHex = ['a'..'f']
keysNum = ['0'..'9']
keysPunc = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/? "
keysCharNum = keysChar ++ keysNum
keysAll = keysChar ++ keysNum ++ keysPunc

giveKey ::  String -> Char -> Int -> Char
giveKey keysCustom c n = extractChar $ case c of
    'i'  -> (keysNum ++ keysHex)
    'j'  -> keysNum
    'k'  -> keysChar
    'l'  -> keysCharNum
    ';'  -> keysPunc
    'h'  -> (keysCharNum ++ keysCustom)
    '\n' -> ['\n']
    _    -> keysAll
    where
    extractChar xs = xs!!mod n (length xs)

showRandomKey :: String -> StateT AESRNG IO ()
showRandomKey keysCustom = handleKey =<< liftIO getChar
    where
    handleKey key = case key of
        '\n' -> liftIO (putChar '\n') >> showRandomKey keysCustom
        'q' -> (liftIO $ putStrLn "\nBye!") >> return ()
        _ -> mapM_ f [0..(49)::Int] >> (liftIO $ putStrLn []) >> showRandomKey keysCustom
        where
        f _ = liftIO
            . putChar
            . giveKey keysCustom key
            . (\n -> mod n (length (keysAll ++ keysCustom) - 1))
            =<< aesRandomInt

aesRandomInt :: StateT AESRNG IO Int
aesRandomInt = do
    aesState <- get
    let (bs, aesState') = genRandomBytes aesState 16
    put aesState'
    return (decode $ B.fromChunks [bs])

main :: IO ()
main = do
    hSetBuffering stdin NoBuffering -- disable buffering from STDIN
    hSetBuffering stdout NoBuffering -- disable buffering from STDOUT
    hSetEcho stdin False -- disable terminal echo
    as <- getArgs
    let as' = filter (\c -> elem c keysAll) . nub $ unwords as
    mapM_ putStrLn
        [ []
        , "poke: 'q'     quit"
        , "      'j'     number"
        , "      'k'     letter"
        , "      'l'     alphanumeric"
        , "      ';'     punctuation"
        , "      'h'     alphanumeric" ++ (if null as' then [] else " + " ++ as')
        , "      'i'     hexadecimal"
        , "      'ENTER' newline"
        , "      else    any"
        , []
        ]
    aesState <- makeSystem -- gather entropy from the system to use as the initial seed
    _ <- runStateT (showRandomKey as') aesState -- enter loop
    return ()

Yes, the CPRNG used is the Advanced Encryption Standard (AES) algorithm in counter mode. It sure beats using the default System.Random module in terms of… coolness (for the purposes of this application, the use of a CPRNG over a regular PRNG really gives no benefit). Anyway, here is a sample run:

$ poke \!@#$%
poke: 'q'     quit
      'j'     number
      'k'     letter
      'l'     alphanumeric
      ';'     punctuation
      'h'     alphanumeric + !@#$%
      'i'     hexadecimal
      'ENTER' newline
      else    any

%g@c@geisBaqK81ihYkEC5NyUrWXU2ndCKr3wHkklpjvCWF9I0
zaJ,!z{db.|~vR7,MvOnPU-5v7N;cCy'],bl/d;^s[hI}RM?j>
KfdJKVygPSOufgllMAZlEaLWHSHpDrHIcgmryETcEsx5uUWlQb
49388c0958e9c51f2f4dc06a8097eb8169f715b4fcfb3ca555

I named it “poke” because I couldn’t think of any other short, UNIX-y name.

The program takes a string as input and treats it as a special class of characters to consider when generating a password with the ‘h’ key. This way, you can fit into the requirements of legacy website code that say something like, “You may use alphanumeric characters and also ‘!’ ‘@’ ‘#’ ‘$’ and ‘%’ symbols”.

The output above is from pressing ‘h’, then SPACE, then ‘l’ and finally ‘i’. You could easily extend it to take more fine-tuned options, such as a shorter password length instead of the default 50. (Hint: use this post.)

The interesting side effect of using 50-character long, randomly generated passwords is that I myself do not know these passwords! The only thing I remember is the single password used for my GnuPG private key, used to decrypt the master password file.

In case you are curious, my complete setup regarding passwords is as follows: I store all of my passwords in plaintext in a “master” file, then encrypt it with GnuPG. I use a git repo to track this encrypted file, so that I can sanely remove/delete old passwords without worrying about how to get it back if I need it. Once in a while, I use a simple shell command, gpg2 -d mypasswords.gpg | less, to view the passwords for entry into some website (hooray for copy and paste!). If I need to update/add/delete passwords, I just decrypt the master file, then edit it, and re-encrypt it and commit the change into git (btw, I decrypt it into a RAM partition to avoid leaving any traces of the plaintext file).

The GnuPG private key used to encrypt the master file is itself encrypted with CAST5 (again using GnuPG) and tracked in git. The CAST5 encryption (with the “-c” flag) is a way to encrypt a file with symmetric encryption — i.e., you supply the same password for encryption and decryption, and plus you don’t need a GnuPG key to do it! (You wouldn’t want to encrypt it using another GnuPG key, because then you’d need to encrypt the key for that GnuPG key as well — recursion!) I constantly sync the git repo holding these important, encrypted files across all of my personal machines, thumb drives, etc., for reliability and convenience.

I could learn to use KeyPass or some other software to manage my passwords, but, I’m too lazy. I’m also too paranoid to trust anyone other than myself to handle my passwords. I also take care not to store anything *too* valuable into the passwords file, or anything I type into any file anywhere, just to play it safe.

EDIT: Hey, this is my 100th post! Congratulations to me!

Website Passwords: A Big Mess

TL;DR: You will inevitably be screwed when you try to change your website passwords.

So a few months ago, I changed all of my website passwords. I used a simple pseudorandom ASCII-only character generator to ensure the uniqueness of each one. In the process, I discovered that many websites have horrible, broken password interfaces.

This post is mainly a rant. Setting and changing passwords should never be difficult, and should be 100% transparent. We end users probably collectively wasted millions of hours with broken password interfaces, and will waste millions more until the issues below are addressed each time someone deploys a new website.

Special Characters

Many websites tell you a list of special characters that are not allowed in passwords. Sadly, this list is often incomplete. Worse still, some only accept alphanumeric passwords, but are silent as to this restriction — and to top it off, they don’t even bother to tell you why your chosen password is invalid! The gall.

It appears that the restriction against special characters is largely a matter of legacy vs. modern platforms. Newer websites like Wikipedia allow you to choose any character from a US ASCII keyboard. Many older institutions (Bank of America, for example) have very strange special character restrictions, which almost seem arbitrary (did you know that Bank of America calls passwords “passcodes”?).

What needs to be done: At a minimum, allow input of ALL characters from a US ASCII keyboard ([a-zA-Z0-9] and all punctuation characters and spaces (tabs are impossible to type into a text field in some browsers, so they can be excused)).

Password Length

This is the biggest problem. For roughly 1/2 of my website passwords, they have a maximum character limit. Some even enforce a 12-character limit (socalgas.com is one example). Some enforce a 16-character limit (bugs.freedesktop.org, login.live.com). Barnesandnoble.com has a 15-character limit (no space s allowed, alphanumeric only).

But the best part is this: many of these sites do not tell you about this limit. So, you can spend 5, 10 minutes thinking out a great mnemonic device for a fantastic password, and you’ll get hit with some “Invalid Password” error. Yet another well-meaning user slapped in the face.

Many sites are fixated on only preventing 3, 4 character passwords by implementing an interactive “password strength” meter that rejects short passwords. But they still fail to tell you that your password is too long.

EDIT: Bela pointed out in the comments another common bug: the site will happily accept your chosen password, but will truncate it to a shorter length (without telling you any warnings about it, of course).

What needs to be done: Explicitly tell the user exactly how many characters they may use, and if the password is too long, tell them about it.

Stupidity Award: access.enom.com

If you change your password at this site, be extremely careful: DO NOT choose a password that is more than 30 characters long. When I changed my password to a 50-character long password, it happily accepted it. Unfortunately, the actual log-in interface only lets you type in 30 characters long! Since access.enom.com has no contact information, you’ll have to call someone somewhere somehow to sort out this mess.

Realistic Outlook

Legacy systems are really, really hard to migrate out of. My prediction is that the stupid, broken web interfaces will continue to thrive for at least 20 years. Why? It’s because people in 2031 will still be using passwords that are around 10 characters long with mostly alphanumeric symbols. Sure, web standards will have evolved by that time, but human brains will still be the same. The steady flow of 10-character passwords by the overwhelming majority of users will ensure that legacy systems remain competitive, at least when it comes to dealing with passwords.

Hopefully, by 2111, we’ll have sane password interfaces for all websites. Perhaps it will become a web standard by then, enforced by an international e-court, or some such.