#!/usr/bin/env zsh # Filename: makepass.zsh # Purpose: Creating random passwords. # Authors: Dennis Eriksen # Bug-Reports: Email # License: This file is licensed under the BSD 3-Clause license. ################################################################################ # This file generates random passwords ################################################################################ # Copyright (c) 2018-2023 Dennis Eriksen • d@ennis.no # # Globals # # typeset # -a = array # -i = integer # -g = global # -r = readonly typeset -gri MAX=255 # max length of passwords typeset -gri RANGE_MAX=42 # max length when using random length typeset -gri RANGE_MIN=8 # min length when using random length typeset -gri PASS_WORDS=8 # number of words in passphrases typeset -gr LOWER='abcdefghijklmnopqrstuvwxyz' typeset -gr UPPER='ABCDEFGHIJKLMNOPQRSTUVWXYZ' typeset -gr DIGIT='0123456789' typeset -gr OTHER='!#$%&/()=?+-_,.;:<>[]{}|@*' typeset -gr ALPHA=${LOWER}${UPPER} typeset -gr ALNUM=${ALPHA}${DIGIT} typeset -gr EVERY=${ALNUM}${OTHER} typeset -gi LENGTH=${MAKEPASS_LENGTH:-0} # length of passwords. 0 means "random number between RANGE_MIN and RANGE_MAX" typeset -gi NUMBER=${MAKEPASS_NUMBER:-10} # number of passwords typeset -gi PRINTLEN=${MAKEPASS_PRINTLEN:-0} # print length of passwords typeset -g NORMAL=${MAKEPASS_NORMAL:-$ALNUM'-_'} typeset -g SPECIAL=${MAKEPASS_SPECIAL:-$EVERY} typeset -g WORDLIST=${MAKEPASS_WORDLIST:-/usr/share/dict/words} typeset -ga WORDS # Array of words from WORDLIST typeset -gi COL_WIDTH # Width of columns we will be printing typeset -gi COL_NUM # Number of columns to print # GOTCHAs: # # $RANDOM - from the zsh documentation: # > The values of RANDOM form an intentionally-repeatable pseudo-random sequence; # > subshells that reference RANDOM will result in identical pseudo-random values # > unless the value of RANDOM is referenced or seeded in the parent shell in # > between subshell invocations. # So remember to throw away a $RANDOM between subshell invocations! # # Functions # # main-function. This is where the magic happens function main() { setopt localoptions # Getopts while getopts 'hl:n:p' opt; do case $opt in h) help && return 0;; l) [[ $OPTARG = <0-> && $OPTARG -le $MAX ]] || die "-l takes a number between 0 and $MAX" LENGTH=$OPTARG;; n) [[ $OPTARG = <1-> && $OPTARG -le $MAX ]] || die "-n takes a number between 1 and $MAX" NUMBER=$OPTARG;; p) PRINTLEN=1;; *) die "Unknown argument";; esac done shift $((OPTIND - 1)) # # Some error-checking # # We only take one argument in addition to the optargs (( ARGC > 1 )) && die "only one argument" # if there is an argument, set it to $LENGTH [[ -n $1 ]] && LENGTH=$1 # Check $LENGTH and $NUMBER # Both are integers so no need to check if they are numbers # If they were somehow assigned to, say "xx", they would be 0 (( 0 <= LENGTH && LENGTH <= MAX )) || die "length must be a number between 0 and $MAX" (( 1 <= NUMBER && NUMBER <= MAX )) || die "number-argument must be between 1 and $MAX" # # Some other work # # Seed $RANDOM with a random 32bit integer from /dev/random local r4 # will be filled with 4 random bytes from /dev/random IFS= read -rk4 -u0 r4 < /dev/random || return local b1=$r4[1] b2=$r4[2] b3=$r4[3] b4=$r4[4] RANDOM=$(( #b1 << 24 | #b2 << 16 | #b3 << 8 | #b4 )) # We zero-pad printlength, so we need two extra chars if LENGTH < 100 (three # if LENGTH >= 100). (( PRINTLEN )) && { ((LENGTH < 100)) && PRINTLEN=2 || PRINTLEN=3 } # Calculate width of columns and number of columns to use # add two for spacing between columns COL_WIDTH=$(( ( LENGTH ? LENGTH : RANGE_MAX ) + 2 )) # $COLUMNS is a builtin variable for width of terminal # If $PRINTLEN is set, we have to add one for the space as well COL_NUM=$(( COLUMNS / ( COL_WIDTH + ( PRINTLEN ? PRINTLEN + 1 : 0 )) )) # Just in case COL_NUM=0 because of a small terminal or something (( COL_NUM )) || COL_NUM=1 # # Print! # print_columns "Normal passwords" $NUMBER $NORMAL print; : $RANDOM # Throw away print_columns "Passwords with special characters" $((NUMBER/3*2+1)) $SPECIAL # Passphrases - but only if a wordlist is available if [[ -r $WORDLIST ]] && ((NUMBER / 2 > 0)); then print; : $RANDOM # Throw away print "Passphrases:" # Read wordlist into array WORDS=(${(f)"$(<$WORDLIST)"}) # Run passphrase-function to output passphrases repeat $((NUMBER / 2)) passphrase fi } # Function to print passwords in neat columns function print_columns() { : $RANDOM # Throw away local title=$1 local num=$2 local chars=$3 local -i i=0 local strings=($(repeat $num { randstring $chars })) print -- "${title}:" for s in $strings; do let i++ (( PRINTLEN )) && printf "%0${PRINTLEN}i " $#s printf "%-${COL_WIDTH}s" $s ((i % COL_NUM == 0 || (i == num && i % COL_NUM > 0))) && print done } # Function to create random strings function randstring() { local chars=${1:-$NORMAL} local string local -i len=$(( LENGTH \ ? LENGTH \ : RANDOM % (RANGE_MAX - RANGE_MIN + 1) + RANGE_MIN )) string+=$ALPHA[$((RANDOM % $#ALPHA + 1))] repeat $((len - 2)) string+=$chars[$((RANDOM % $#chars + 1))] (( len >= 2 )) && string+=$ALNUM[$((RANDOM % $#ALNUM + 1))] print -- $string; return } # Create random passphrase function passphrase() { setopt localoptions rematch_pcre local prestring string # Put together $len random words, separated by '-' repeat $PASS_WORDS prestring+=$WORDS[$((RANDOM % $#WORDS + 1))]'-' prestring=$prestring[1,-2] # remove trailing dash # This while-loop removes any characters NOT in '[^0-9a-zA-Z_-]' while [[ -n $prestring ]]; do if [[ $prestring =~ '[^0-9a-zA-Z_-]' ]]; then string+=${prestring[1,MBEGIN-1]} prestring=${prestring[MEND+1,-1]} else break fi done string+=$prestring # append the rest of $prestring printf '%s\n' $string; return } # Function to die function die() { print -u2 -- "$@" print -u2 -- "Maybe try running \`$ZSH_SCRIPT -h\` for help" exit 1 } # Help-function function help() { print -- $'NAME makepass - create several random passwords SYNOPSIS makepass [OPTIONS] [NUM] If a NUM is provided, passwords will be NUM characters long. By default `makepass` will output passwords from the three following classes: - Normal passwords - random strings with letters (both lower and upper case), numbers, and dashes and underscores. - Passwords with special characters - random strings generated from lower and upper case letters, numbers, and the following characters: !#$%&/()=?+-_,.;:<>[]{}|@* - Passphrases - if we find a dictionary, a series of eight random words from the dictionary, separated by dashes. The number of words can not be changed, but you do not have to use all of them. Use as mane as you want. The first character will always be alphabetic, and the last will always be alphanumeric. DESCRIPTION makepass has the following options: -h output this help-text -l length of passwords. See MAKEPASS_LENGTH below -n number of passwords. See MAKEPASS_NUMBER below -p print length of number ENVIRONMENT makepass examines the following environmental variables. MAKEPASS_LENGTH Specifies the length of passwords. Valid values are 0-255. If 0, a random value between 8 and 42 will be used for each password. -l overrides this environmental variable, and the argument NUM overrides that again. So `MAKEPASS_LENGTH=10 makepass -l 12 14` will give passwords that are 14 characters long, even though both -l and MAKEPASS_LENGTH also specifies a length. MAKEPASS_NUMBER The number of passwords to generate. This formula is used to determine how many passwords from each group should be generated: - (n) normal passwords - (n / 3 * 2 + 1) special passwords - (n / 2) passphrases Where n is 10 by default. Valid values for n are 1-255. Floating-poing math is not used, so results may vary. MAKEPASS_PRINTLEN If 1, print length of all passwords. If 0, don\'t. MAKEPASS_NORMAL String of characters from which to generate "normal" passwords. Defaults to: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_ MAKEPASS_SPECIAL String of characters from which to generate passwords with special characters. Defaults to the same characters as in MAKEPASS_NORMAL, plus these: !#$%&/()=?+-_,.;:<>[]{}|@* MAKEPASS_WORDLIST Specifies the dictionary we find words for passphrases in. If this is unset or empty, we try "/usr/share/dict/words". If that file does not exist, no passphrases will be provided. NOTES This scripts makes use of $RANDOM - a builtin in zsh which produces a pseudo-random integer between 0 and 32767, newly generated each time the parameter is referenced. We initially seed the random number generator with a random 32bit integer generated from /dev/random. This should provide enough randomnes to generate sufficiently secure passwords. AUTHOR Dennis Eriksen ' return 0 } # Run main function! GOGOGO! main "${@:-}" # Last time I redid this script I benchmarked some ways to generate random # strings. Here's the results: # subshell with tr | fold | head # % time (repeat 10000 { string=''; string=$(tr -cd '[:alpha:]'