xkcd_password.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. import random
  4. import os
  5. import os.path
  6. import argparse
  7. import re
  8. import math
  9. import sys
  10. __LICENSE__ = """
  11. Copyright (c) 2011 - 2016, Steven Tobin and Contributors.
  12. All rights reserved.
  13. Redistribution and use in source and binary forms, with or without
  14. modification, are permitted provided that the following conditions are met:
  15. * Redistributions of source code must retain the above copyright
  16. notice, this list of conditions and the following disclaimer.
  17. * Redistributions in binary form must reproduce the above copyright
  18. notice, this list of conditions and the following disclaimer in the
  19. documentation and/or other materials provided with the distribution.
  20. * Neither the name of the <organization> nor the
  21. names of its contributors may be used to endorse or promote products
  22. derived from this software without specific prior written permission.
  23. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  24. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  25. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  26. DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  27. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  28. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  29. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  30. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  32. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. """
  34. # random.SystemRandom() should be cryptographically secure
  35. try:
  36. rng = random.SystemRandom
  37. except AttributeError as ex:
  38. sys.stderr.write("WARNING: System does not support cryptographically "
  39. "secure random number generator or you are using Python "
  40. "version < 2.4.\n")
  41. if "XKCDPASS_ALLOW_WEAKRNG" in os.environ or \
  42. "--allow-weak-rng" in sys.argv:
  43. sys.stderr.write("Continuing with less-secure generator.\n")
  44. rng = random.Random
  45. else:
  46. raise ex
  47. # Python 3 compatibility
  48. if sys.version_info[0] >= 3:
  49. raw_input = input
  50. xrange = range
  51. def validate_options(parser, options):
  52. """
  53. Given a parsed collection of options, performs various validation checks.
  54. """
  55. if options.max_length < options.min_length:
  56. sys.stderr.write("The maximum length of a word can not be "
  57. "less than the minimum length.\n"
  58. "Check the specified settings.\n")
  59. sys.exit(1)
  60. if options.wordfile is not None:
  61. if not os.path.isfile(os.path.abspath(options.wordfile)):
  62. sys.stderr.write("Could not open the specified word file.\n")
  63. sys.exit(1)
  64. else:
  65. options.wordfile = locate_wordfile()
  66. if not options.wordfile:
  67. sys.stderr.write("Could not find a word file, or word file does "
  68. "not exist.\n")
  69. sys.exit(1)
  70. def locate_wordfile():
  71. static_default = os.path.join(
  72. os.path.dirname(os.path.abspath(__file__)),
  73. 'static',
  74. 'default.txt')
  75. common_word_files = ["/usr/share/cracklib/cracklib-small",
  76. static_default,
  77. "/usr/dict/words",
  78. "/usr/share/dict/words"]
  79. for wfile in common_word_files:
  80. if os.path.isfile(wfile):
  81. return wfile
  82. def generate_wordlist(wordfile=None,
  83. min_length=5,
  84. max_length=9,
  85. valid_chars='.'):
  86. """
  87. Generate a word list from either a kwarg wordfile, or a system default
  88. valid_chars is a regular expression match condition (default - all chars)
  89. """
  90. if wordfile is None:
  91. wordfile = locate_wordfile()
  92. words = []
  93. regexp = re.compile("^{0}{{{1},{2}}}$".format(valid_chars,
  94. min_length,
  95. max_length))
  96. # At this point wordfile is set
  97. wordfile = os.path.expanduser(wordfile) # just to be sure
  98. # read words from file into wordlist
  99. with open(wordfile) as wlf:
  100. for line in wlf:
  101. thisword = line.strip()
  102. if regexp.match(thisword) is not None:
  103. words.append(thisword)
  104. return list(set(words)) # deduplicate, just in case
  105. def wordlist_to_worddict(wordlist):
  106. """
  107. Takes a wordlist and returns a dictionary keyed by the first letter of
  108. the words. Used for acrostic pass phrase generation
  109. """
  110. worddict = {}
  111. # Maybe should be a defaultdict, but this reduces dependencies
  112. for word in wordlist:
  113. try:
  114. worddict[word[0]].append(word)
  115. except KeyError:
  116. worddict[word[0]] = [word, ]
  117. return worddict
  118. def verbose_reports(length, numwords, wordfile):
  119. """
  120. Report entropy metrics based on word list and requested password size"
  121. """
  122. bits = math.log(length, 2)
  123. print("The supplied word list is located at"
  124. " {0}.".format(os.path.abspath(wordfile)))
  125. if int(bits) == bits:
  126. print("Your word list contains {0} words, or 2^{1} words."
  127. "".format(length, bits))
  128. else:
  129. print("Your word list contains {0} words, or 2^{1:.2f} words."
  130. "".format(length, bits))
  131. print("A {0} word password from this list will have roughly "
  132. "{1} ({2:.2f} * {3}) bits of entropy,"
  133. "".format(numwords, int(bits * numwords), bits, numwords)),
  134. print("assuming truly random word selection.")
  135. def find_acrostic(acrostic, worddict):
  136. """
  137. Constrain choice of words to those beginning with the letters of the
  138. given word (acrostic).
  139. Second argument is a dictionary (output of wordlist_to_worddict)
  140. """
  141. words = []
  142. for letter in acrostic:
  143. try:
  144. words.append(rng().choice(worddict[letter]))
  145. except KeyError:
  146. sys.stderr.write("No words found starting with " + letter + "\n")
  147. sys.exit(1)
  148. return words
  149. def choose_words(wordlist, numwords):
  150. """
  151. Choose numwords randomly from wordlist
  152. """
  153. return [rng().choice(wordlist) for i in xrange(numwords)]
  154. def try_input(prompt, validate):
  155. """
  156. Suppress stack trace on user cancel and validate input with supplied
  157. validate callable.
  158. """
  159. try:
  160. answer = raw_input(prompt)
  161. except (KeyboardInterrupt, EOFError):
  162. # user cancelled
  163. print("")
  164. sys.exit(0)
  165. # validate input
  166. return validate(answer)
  167. def generate_xkcdpassword(wordlist,
  168. numwords=6,
  169. interactive=False,
  170. acrostic=False,
  171. delimiter=" "):
  172. """
  173. Generate an XKCD-style password from the words in wordlist.
  174. """
  175. passwd = None
  176. # generate the worddict if we are looking for acrostics
  177. if acrostic:
  178. worddict = wordlist_to_worddict(wordlist)
  179. # useful if driving the logic from other code
  180. if not interactive:
  181. if not acrostic:
  182. passwd = delimiter.join(choose_words(wordlist, numwords))
  183. else:
  184. passwd = delimiter.join(find_acrostic(acrostic, worddict))
  185. return passwd
  186. # else, interactive session
  187. # define input validators
  188. def n_words_validator(answer):
  189. """
  190. Validate custom number of words input
  191. """
  192. if isinstance(answer, str) and len(answer) == 0:
  193. return numwords
  194. try:
  195. number = int(answer)
  196. if number < 1:
  197. raise ValueError
  198. return number
  199. except ValueError:
  200. sys.stderr.write("Please enter a positive integer\n")
  201. sys.exit(1)
  202. def accepted_validator(answer):
  203. return answer.lower().strip() in ["y", "yes"]
  204. if not acrostic:
  205. n_words_prompt = ("Enter number of words (default {0}):"
  206. " ".format(numwords))
  207. numwords = try_input(n_words_prompt, n_words_validator)
  208. else:
  209. numwords = len(acrostic)
  210. # generate passwords until the user accepts
  211. accepted = False
  212. while not accepted:
  213. if not acrostic:
  214. passwd = delimiter.join(choose_words(wordlist, numwords))
  215. else:
  216. passwd = delimiter.join(find_acrostic(acrostic, worddict))
  217. print("Generated: " + passwd)
  218. accepted = try_input("Accept? [yN] ", accepted_validator)
  219. return passwd
  220. def emit_passwords(wordlist, options):
  221. """ Generate the specified number of passwords and output them. """
  222. count = options.count
  223. while count > 0:
  224. print(generate_xkcdpassword(
  225. wordlist,
  226. interactive=options.interactive,
  227. numwords=options.numwords,
  228. acrostic=options.acrostic,
  229. delimiter=options.delimiter))
  230. count -= 1
  231. class XkcdPassArgumentParser(argparse.ArgumentParser):
  232. """ Command-line argument parser for this program. """
  233. def __init__(self, *args, **kwargs):
  234. super(XkcdPassArgumentParser, self).__init__(*args, **kwargs)
  235. self._add_arguments()
  236. def _add_arguments(self):
  237. """ Add the arguments needed for this program. """
  238. self.add_argument(
  239. "-w", "--wordfile",
  240. dest="wordfile", default=None, metavar="WORDFILE",
  241. help=(
  242. "Specify that the file WORDFILE contains the list"
  243. " of valid words from which to generate passphrases."))
  244. self.add_argument(
  245. "--min",
  246. dest="min_length", type=int, default=5, metavar="MIN_LENGTH",
  247. help="Generate passphrases containing at least MIN_LENGTH words.")
  248. self.add_argument(
  249. "--max",
  250. dest="max_length", type=int, default=9, metavar="MAX_LENGTH",
  251. help="Generate passphrases containing at most MAX_LENGTH words.")
  252. self.add_argument(
  253. "-n", "--numwords",
  254. dest="numwords", type=int, default=6, metavar="NUM_WORDS",
  255. help="Generate passphrases containing exactly NUM_WORDS words.")
  256. self.add_argument(
  257. "-i", "--interactive",
  258. action="store_true", dest="interactive", default=False,
  259. help=(
  260. "Generate and output a passphrase, query the user to"
  261. " accept it, and loop until one is accepted."))
  262. self.add_argument(
  263. "-v", "--valid-chars",
  264. dest="valid_chars", default=".", metavar="VALID_CHARS",
  265. help=(
  266. "Limit passphrases to only include words matching the regex"
  267. " pattern VALID_CHARS (e.g. '[a-z]')."))
  268. self.add_argument(
  269. "-V", "--verbose",
  270. action="store_true", dest="verbose", default=False,
  271. help="Report various metrics for given options.")
  272. self.add_argument(
  273. "-a", "--acrostic",
  274. dest="acrostic", default=False,
  275. help="Generate passphrases with an acrostic matching ACROSTIC.")
  276. self.add_argument(
  277. "-c", "--count",
  278. dest="count", type=int, default=1, metavar="COUNT",
  279. help="Generate COUNT passphrases.")
  280. self.add_argument(
  281. "-d", "--delimiter",
  282. dest="delimiter", default=" ", metavar="DELIM",
  283. help="Separate words within a passphrase with DELIM.")
  284. self.add_argument(
  285. "--allow-weak-rng",
  286. action="store_true", dest="allow_weak_rng", default=False,
  287. help=(
  288. "Allow fallback to weak RNG if the "
  289. "system does not support cryptographically secure RNG. "
  290. "Only use this if you know what you are doing."))
  291. def main(argv=None):
  292. """ Mainline code for this program. """
  293. if argv is None:
  294. argv = sys.argv
  295. exit_status = 0
  296. try:
  297. program_name = os.path.basename(argv[0])
  298. parser = XkcdPassArgumentParser(prog=program_name)
  299. options = parser.parse_args(argv[1:])
  300. validate_options(parser, options)
  301. my_wordlist = generate_wordlist(
  302. wordfile=options.wordfile,
  303. min_length=options.min_length,
  304. max_length=options.max_length,
  305. valid_chars=options.valid_chars)
  306. if options.verbose:
  307. verbose_reports(
  308. len(my_wordlist),
  309. options.numwords,
  310. options.wordfile)
  311. emit_passwords(my_wordlist, options)
  312. except SystemExit as exc:
  313. exit_status = exc.code
  314. return exit_status
  315. if __name__ == '__main__':
  316. exit_status = main(sys.argv)
  317. sys.exit(exit_status)