xkcd_password.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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:
  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. "Continuing with less-secure generator.\n")
  42. rng = random.Random
  43. # Python 3 compatibility
  44. if sys.version_info[0] >= 3:
  45. raw_input = input
  46. xrange = range
  47. def validate_options(parser, options):
  48. """
  49. Given a parsed collection of options, performs various validation checks.
  50. """
  51. if options.max_length < options.min_length:
  52. sys.stderr.write("The maximum length of a word can not be "
  53. "lesser then minimum length.\n"
  54. "Check the specified settings.\n")
  55. sys.exit(1)
  56. if options.wordfile is not None:
  57. if not os.path.exists(os.path.abspath(options.wordfile)):
  58. sys.stderr.write("Could not open the specified word file.\n")
  59. sys.exit(1)
  60. else:
  61. options.wordfile = locate_wordfile()
  62. if not options.wordfile:
  63. sys.stderr.write("Could not find a word file, or word file does "
  64. "not exist.\n")
  65. sys.exit(1)
  66. def locate_wordfile():
  67. static_default = os.path.join(
  68. os.path.dirname(os.path.abspath(__file__)),
  69. 'static',
  70. 'default.txt')
  71. common_word_files = ["/usr/share/cracklib/cracklib-small",
  72. static_default,
  73. "/usr/dict/words",
  74. "/usr/share/dict/words"]
  75. for wfile in common_word_files:
  76. if os.path.exists(wfile):
  77. return wfile
  78. def generate_wordlist(wordfile=None,
  79. min_length=5,
  80. max_length=9,
  81. valid_chars='.'):
  82. """
  83. Generate a word list from either a kwarg wordfile, or a system default
  84. valid_chars is a regular expression match condition (default - all chars)
  85. """
  86. words = []
  87. regexp = re.compile("^%s{%i,%i}$" % (valid_chars, min_length, max_length))
  88. # At this point wordfile is set
  89. wordfile = os.path.expanduser(wordfile) # just to be sure
  90. wlf = open(wordfile)
  91. for line in wlf:
  92. thisword = line.strip()
  93. if regexp.match(thisword) is not None:
  94. words.append(thisword)
  95. wlf.close()
  96. return words
  97. def wordlist_to_worddict(wordlist):
  98. """
  99. Takes a wordlist and returns a dictionary keyed by the first letter of
  100. the words. Used for acrostic pass phrase generation
  101. """
  102. worddict = {}
  103. # Maybe should be a defaultdict, but this reduces dependencies
  104. for word in wordlist:
  105. try:
  106. worddict[word[0]].append(word)
  107. except KeyError:
  108. worddict[word[0]] = [word, ]
  109. return worddict
  110. def verbose_reports(length, numwords, wordfile):
  111. """
  112. Report entropy metrics based on word list and requested password size"
  113. """
  114. bits = math.log(length, 2)
  115. print("The supplied word list is located at %s."
  116. % os.path.abspath(wordfile))
  117. if int(bits) == bits:
  118. print("Your word list contains %i words, or 2^%i words."
  119. % (length, bits))
  120. else:
  121. print("Your word list contains %i words, or 2^%0.2f words."
  122. % (length, bits))
  123. print("A %i word password from this list will have roughly "
  124. "%i (%0.2f * %i) bits of entropy," %
  125. (numwords, int(bits * numwords), bits, numwords)),
  126. print("assuming truly random word selection.")
  127. def find_acrostic(acrostic, worddict):
  128. """
  129. Constrain choice of words to those beginning with the letters of the
  130. given word (acrostic).
  131. Second argument is a dictionary (output of wordlist_to_worddict)
  132. """
  133. words = []
  134. for letter in acrostic:
  135. try:
  136. words.append(rng().choice(worddict[letter]))
  137. except KeyError:
  138. sys.stderr.write("No words found starting with " + letter + "\n")
  139. sys.exit(1)
  140. return words
  141. def choose_words(wordlist, numwords):
  142. s = []
  143. for i in xrange(numwords):
  144. s.append(rng().choice(wordlist))
  145. return s
  146. def generate_xkcdpassword(wordlist,
  147. numwords=6,
  148. interactive=False,
  149. acrostic=False,
  150. delimiter=" "):
  151. """
  152. Generate an XKCD-style password from the words in wordlist.
  153. """
  154. passwd = False
  155. # generate the worddict if we are looking for acrostics
  156. if acrostic:
  157. worddict = wordlist_to_worddict(wordlist)
  158. # useful if driving the logic from other code
  159. if not interactive:
  160. if not acrostic:
  161. passwd = delimiter.join(choose_words(wordlist, numwords))
  162. else:
  163. passwd = delimiter.join(find_acrostic(acrostic, worddict))
  164. return passwd
  165. # else, interactive session
  166. if not acrostic:
  167. custom_n_words = raw_input("Enter number of words (default 6): ")
  168. if custom_n_words:
  169. numwords = int(custom_n_words)
  170. else:
  171. numwords = len(acrostic)
  172. accepted = "n"
  173. while accepted.lower() not in ["y", "yes"]:
  174. if not acrostic:
  175. passwd = delimiter.join(choose_words(wordlist, numwords))
  176. else:
  177. passwd = delimiter.join(find_acrostic(acrostic, worddict))
  178. print("Generated: ", passwd)
  179. accepted = raw_input("Accept? [yN] ")
  180. return passwd
  181. def emit_passwords(wordlist, options):
  182. """ Generate the specified number of passwords and output them. """
  183. count = options.count
  184. while count > 0:
  185. print(generate_xkcdpassword(
  186. wordlist,
  187. interactive=options.interactive,
  188. numwords=options.numwords,
  189. acrostic=options.acrostic,
  190. delimiter=options.delimiter))
  191. count -= 1
  192. class XkcdPassArgumentParser(argparse.ArgumentParser):
  193. """ Command-line argument parser for this program. """
  194. def __init__(self, *args, **kwargs):
  195. super(XkcdPassArgumentParser, self).__init__(*args, **kwargs)
  196. self._add_arguments()
  197. def _add_arguments(self):
  198. """ Add the arguments needed for this program. """
  199. self.add_argument(
  200. "-w", "--wordfile",
  201. dest="wordfile", default=None, metavar="WORDFILE",
  202. help=(
  203. "Specify that the file WORDFILE contains the list"
  204. " of valid words from which to generate passphrases."))
  205. self.add_argument(
  206. "--min",
  207. dest="min_length", type=int, default=5, metavar="MIN_LENGTH",
  208. help="Generate passphrases containing at least MIN_LENGTH words.")
  209. self.add_argument(
  210. "--max",
  211. dest="max_length", type=int, default=9, metavar="MAX_LENGTH",
  212. help="Generate passphrases containing at most MAX_LENGTH words.")
  213. self.add_argument(
  214. "-n", "--numwords",
  215. dest="numwords", type=int, default=6, metavar="NUM_WORDS",
  216. help="Generate passphrases containing exactly NUM_WORDS words.")
  217. self.add_argument(
  218. "-i", "--interactive",
  219. action="store_true", dest="interactive", default=False,
  220. help=(
  221. "Generate and output a passphrase, query the user to"
  222. " accept it, and loop until one is accepted."))
  223. self.add_argument(
  224. "-v", "--valid-chars",
  225. dest="valid_chars", default=".", metavar="VALID_CHARS",
  226. help=(
  227. "Limit passphrases to only include words matching the regex"
  228. " pattern VALID_CHARS (e.g. '[a-z]')."))
  229. self.add_argument(
  230. "-V", "--verbose",
  231. action="store_true", dest="verbose", default=False,
  232. help="Report various metrics for given options.")
  233. self.add_argument(
  234. "-a", "--acrostic",
  235. dest="acrostic", default=False,
  236. help="Generate passphrases with an acrostic matching ACROSTIC.")
  237. self.add_argument(
  238. "-c", "--count",
  239. dest="count", type=int, default=1, metavar="COUNT",
  240. help="Generate COUNT passphrases.")
  241. self.add_argument(
  242. "-d", "--delimiter",
  243. dest="delimiter", default=" ", metavar="DELIM",
  244. help="Separate words within a passphrase with DELIM.")
  245. self.add_argument(
  246. "wordfile",
  247. default=None, metavar="WORDFILE", nargs="?",
  248. help=(
  249. "Specify that the file WORDFILE contains the list"
  250. " of valid words from which to generate passphrases."))
  251. def main(argv=None):
  252. """ Mainline code for this program. """
  253. if argv is None:
  254. argv = sys.argv
  255. exit_status = 0
  256. try:
  257. program_name = os.path.basename(argv[0])
  258. parser = XkcdPassArgumentParser(prog=program_name)
  259. options = parser.parse_args(argv[1:])
  260. validate_options(parser, options)
  261. my_wordlist = generate_wordlist(
  262. wordfile=options.wordfile,
  263. min_length=options.min_length,
  264. max_length=options.max_length,
  265. valid_chars=options.valid_chars)
  266. if options.verbose:
  267. verbose_reports(
  268. len(my_wordlist),
  269. options.numwords,
  270. options.wordfile)
  271. emit_passwords(my_wordlist, options)
  272. except SystemExit as exc:
  273. exit_status = exc.code
  274. return exit_status
  275. if __name__ == '__main__':
  276. exit_status = main(sys.argv)
  277. sys.exit(exit_status)