xkcd_password.py 10 KB

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