daily pastebin goal
7%
SHARE
TWEET

firefox password export plain test

a guest Mar 8th, 2018 80 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8.  
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12. # GNU General Public License for more details.
  13.  
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program.  If not, see <http://www.gnu.org/licenses/>.
  16.  
  17. # Based on original work from: www.dumpzilla.org
  18.  
  19. import argparse
  20. import csv
  21. import ctypes as ct
  22. import json
  23. import logging
  24. import os
  25. import sqlite3
  26. import sys
  27. from base64 import b64decode
  28. from getpass import getpass
  29. from subprocess import PIPE, Popen
  30.  
  31. try:
  32.     # Python 3
  33.     from subprocess import DEVNULL
  34. except ImportError:
  35.     # Python 2
  36.     DEVNULL = open(os.devnull, 'w')
  37.  
  38. try:
  39.     # Python 3
  40.     from urllib.parse import urlparse
  41. except ImportError:
  42.     # Python 2
  43.     from urlparse import urlparse
  44.  
  45. try:
  46.     # Python 3
  47.     from configparser import ConfigParser
  48.     raw_input = input
  49. except ImportError:
  50.     # Python 2
  51.     from ConfigParser import ConfigParser
  52.  
  53. PY3 = sys.version_info.major > 2
  54. LOG = None
  55. VERBOSE = False
  56.  
  57.  
  58. def get_version():
  59.     """Obtain version information from git if available otherwise use
  60.     the internal version number
  61.     """
  62.     def internal_version():
  63.         return '.'.join(map(str, __version_info__))
  64.  
  65.     try:
  66.         p = Popen(["git", "describe", "--tags"], stdout=PIPE, stderr=DEVNULL)
  67.     except OSError:
  68.         return internal_version()
  69.  
  70.     stdout, stderr = p.communicate()
  71.  
  72.     if p.returncode:
  73.         return internal_version()
  74.     else:
  75.         return stdout.strip().decode("utf-8")
  76.  
  77.  
  78. __version_info__ = (0, 7, 0)
  79. __version__ = get_version()
  80.  
  81.  
  82. class NotFoundError(Exception):
  83.     """Exception to handle situations where a credentials file is not found
  84.     """
  85.     pass
  86.  
  87.  
  88. class Exit(Exception):
  89.     """Exception to allow a clean exit from any point in execution
  90.     """
  91.     ERROR = 1
  92.     MISSING_PROFILEINI = 2
  93.     MISSING_SECRETS = 3
  94.     BAD_PROFILEINI = 4
  95.     LOCATION_NO_DIRECTORY = 5
  96.  
  97.     FAIL_LOAD_NSS = 11
  98.     FAIL_INIT_NSS = 12
  99.     FAIL_NSS_KEYSLOT = 13
  100.     FAIL_SHUTDOWN_NSS = 14
  101.     BAD_MASTER_PASSWORD = 15
  102.     NEED_MASTER_PASSWORD = 16
  103.  
  104.     PASSSTORE_NOT_INIT = 20
  105.     PASSSTORE_MISSING = 21
  106.     PASSSTORE_ERROR = 22
  107.  
  108.     READ_GOT_EOF = 30
  109.     MISSING_CHOICE = 31
  110.     NO_SUCH_PROFILE = 32
  111.  
  112.     UNKNOWN_ERROR = 100
  113.     KEYBOARD_INTERRUPT = 102
  114.  
  115.     def __init__(self, exitcode):
  116.         self.exitcode = exitcode
  117.  
  118.     def __unicode__(self):
  119.         return "Premature program exit with exit code {0}".format(self.exitcode)
  120.  
  121.  
  122. class Credentials(object):
  123.     """Base credentials backend manager
  124.     """
  125.     def __init__(self, db):
  126.         self.db = db
  127.  
  128.         LOG.debug("Database location: %s", self.db)
  129.         if not os.path.isfile(db):
  130.             raise NotFoundError("ERROR - {0} database not found\n".format(db))
  131.  
  132.         LOG.info("Using %s for credentials.", db)
  133.  
  134.     def __iter__(self):
  135.         pass
  136.  
  137.     def done(self):
  138.         """Override this method if the credentials subclass needs to do any
  139.         action after interaction
  140.         """
  141.         pass
  142.  
  143.  
  144. class SqliteCredentials(Credentials):
  145.     """SQLite credentials backend manager
  146.     """
  147.     def __init__(self, profile):
  148.         db = os.path.join(profile, "signons.sqlite")
  149.  
  150.         super(SqliteCredentials, self).__init__(db)
  151.  
  152.         self.conn = sqlite3.connect(db)
  153.         self.c = self.conn.cursor()
  154.  
  155.     def __iter__(self):
  156.         LOG.debug("Reading password database in SQLite format")
  157.         self.c.execute("SELECT hostname, encryptedUsername, encryptedPassword, encType "
  158.                        "FROM moz_logins")
  159.         for i in self.c:
  160.             # yields hostname, encryptedUsername, encryptedPassword, encType
  161.             yield i
  162.  
  163.     def done(self):
  164.         """Close the sqlite cursor and database connection
  165.         """
  166.         super(SqliteCredentials, self).done()
  167.  
  168.         self.c.close()
  169.         self.conn.close()
  170.  
  171.  
  172. class JsonCredentials(Credentials):
  173.     """JSON credentials backend manager
  174.     """
  175.     def __init__(self, profile):
  176.         db = os.path.join(profile, "logins.json")
  177.  
  178.         super(JsonCredentials, self).__init__(db)
  179.  
  180.     def __iter__(self):
  181.         with open(self.db) as fh:
  182.             LOG.debug("Reading password database in JSON format")
  183.             data = json.load(fh)
  184.  
  185.             try:
  186.                 logins = data["logins"]
  187.             except:
  188.                 raise Exception("Unrecognized format in {0}".format(self.db))
  189.  
  190.             for i in logins:
  191.                 yield (i["hostname"], i["encryptedUsername"],
  192.                        i["encryptedPassword"], i["encType"])
  193.  
  194.  
  195. class NSSDecoder(object):
  196.     class SECItem(ct.Structure):
  197.         """struct needed to interact with libnss
  198.         """
  199.         _fields_ = [
  200.             ('type', ct.c_uint),
  201.             ('data', ct.c_char_p),  # actually: unsigned char *
  202.             ('len', ct.c_uint),
  203.         ]
  204.  
  205.     class PK11SlotInfo(ct.Structure):
  206.         """opaque structure representing a logical PKCS slot
  207.         """
  208.  
  209.     def __init__(self):
  210.         # Locate libnss and try loading it
  211.         self.NSS = None
  212.         self.load_libnss()
  213.  
  214.         SlotInfoPtr = ct.POINTER(self.PK11SlotInfo)
  215.         SECItemPtr = ct.POINTER(self.SECItem)
  216.  
  217.         self._set_ctypes(ct.c_int, "NSS_Init", ct.c_char_p)
  218.         self._set_ctypes(ct.c_int, "NSS_Shutdown")
  219.         self._set_ctypes(SlotInfoPtr, "PK11_GetInternalKeySlot")
  220.         self._set_ctypes(None, "PK11_FreeSlot", SlotInfoPtr)
  221.         self._set_ctypes(ct.c_int, "PK11_CheckUserPassword", SlotInfoPtr, ct.c_char_p)
  222.         self._set_ctypes(ct.c_int, "PK11SDR_Decrypt", SECItemPtr, SECItemPtr, ct.c_void_p)
  223.         self._set_ctypes(None, "SECITEM_ZfreeItem", SECItemPtr, ct.c_int)
  224.  
  225.         # for error handling
  226.         self._set_ctypes(ct.c_int, "PORT_GetError")
  227.         self._set_ctypes(ct.c_char_p, "PR_ErrorToName", ct.c_int)
  228.         self._set_ctypes(ct.c_char_p, "PR_ErrorToString", ct.c_int, ct.c_uint32)
  229.  
  230.     def _set_ctypes(self, restype, name, *argtypes):
  231.         """Set input/output types on libnss C functions for automatic type casting
  232.         """
  233.         res = getattr(self.NSS, name)
  234.         res.restype = restype
  235.         res.argtypes = argtypes
  236.         setattr(self, "_" + name, res)
  237.  
  238.     @staticmethod
  239.     def find_nss(locations, nssname):
  240.         """Locate nss is one of the many possible locations
  241.         """
  242.         for loc in locations:
  243.             if os.path.exists(os.path.join(loc, nssname)):
  244.                 return loc
  245.  
  246.         LOG.warn("%s not found on any of the default locations for this platform. "
  247.                  "Attempting to continue nonetheless.", nssname)
  248.         return ""
  249.  
  250.     def load_libnss(self):
  251.         """Load libnss into python using the CDLL interface
  252.         """
  253.         if os.name == "nt":
  254.             nssname = "nss3.dll"
  255.             locations = (
  256.                 "",  # Current directory or system lib finder
  257.                 r"C:\Program Files (x86)\Mozilla Firefox",
  258.                 r"C:\Program Files\Mozilla Firefox"
  259.             )
  260.             firefox = self.find_nss(locations, nssname)
  261.  
  262.             os.environ["PATH"] = ';'.join([os.environ["PATH"], firefox])
  263.             LOG.debug("PATH is now %s", os.environ["PATH"])
  264.  
  265.         elif os.uname()[0] == "Darwin":
  266.             nssname = "libnss3.dylib"
  267.             locations = (
  268.                 "",  # Current directory or system lib finder
  269.                 "/usr/local/lib/nss",
  270.                 "/usr/local/lib",
  271.                 "/opt/local/lib/nss",
  272.                 "/sw/lib/firefox",
  273.                 "/sw/lib/mozilla",
  274.                 "/usr/local/opt/nss/lib",  # nss installed with Brew on Darwin
  275.                 "/opt/pkg/lib/nss", # installed via pkgsrc
  276.             )
  277.  
  278.             firefox = self.find_nss(locations, nssname)
  279.         else:
  280.             nssname = "libnss3.so"
  281.             firefox = ""  # Current directory or system lib finder
  282.  
  283.         try:
  284.             nsslib = os.path.join(firefox, nssname)
  285.             LOG.debug("Loading NSS library from %s", nsslib)
  286.  
  287.             self.NSS = ct.CDLL(nsslib)
  288.  
  289.         except Exception as e:
  290.             LOG.error("Problems opening '%s' required for password decryption", nssname)
  291.             LOG.error("Error was %s", e)
  292.             raise Exit(Exit.FAIL_LOAD_NSS)
  293.  
  294.     def handle_error(self):
  295.         """If an error happens in libnss, handle it and print some debug information
  296.         """
  297.         LOG.debug("Error during a call to NSS library, trying to obtain error info")
  298.  
  299.         code = self._PORT_GetError()
  300.         name = self._PR_ErrorToName(code)
  301.         name = "NULL" if name is None else name.decode("ascii")
  302.         # 0 is the default language (localization related)
  303.         text = self._PR_ErrorToString(code, 0)
  304.         text = text.decode("utf8")
  305.  
  306.         LOG.debug("%s: %s", name, text)
  307.  
  308.     def decode(self, data64):
  309.         data = b64decode(data64)
  310.         inp = self.SECItem(0, data, len(data))
  311.         out = self.SECItem(0, None, 0)
  312.  
  313.         e = self._PK11SDR_Decrypt(inp, out, None)
  314.         LOG.debug("Decryption of data returned %s", e)
  315.         try:
  316.             if e == -1:
  317.                 LOG.error("Password decryption failed. Passwords protected by a Master Password!")
  318.                 self.handle_error()
  319.                 raise Exit(Exit.NEED_MASTER_PASSWORD)
  320.  
  321.             res = ct.string_at(out.data, out.len).decode("utf8")
  322.         finally:
  323.             # Avoid leaking SECItem
  324.             self._SECITEM_ZfreeItem(out, 0)
  325.  
  326.         return res
  327.  
  328.  
  329. class NSSInteraction(object):
  330.     """
  331.     Interact with lib NSS
  332.     """
  333.     def __init__(self):
  334.         self.profile = None
  335.         self.NSS = NSSDecoder()
  336.  
  337.     def load_profile(self, profile):
  338.         """Initialize the NSS library and profile
  339.         """
  340.         LOG.debug("Initializing NSS with profile path '%s'", profile)
  341.         self.profile = profile
  342.  
  343.         e = self.NSS._NSS_Init(b"sql:" + self.profile.encode("utf8"))
  344.         LOG.debug("Initializing NSS returned %s", e)
  345.  
  346.         if e != 0:
  347.             LOG.error("Couldn't initialize NSS, maybe '%s' is not a valid profile?", profile)
  348.             self.NSS.handle_error()
  349.             raise Exit(Exit.FAIL_INIT_NSS)
  350.  
  351.     def authenticate(self, interactive):
  352.         """Check if the current profile is protected by a master password,
  353.         prompt the user and unlock the profile.
  354.         """
  355.         LOG.debug("Retrieving internal key slot")
  356.         keyslot = self.NSS._PK11_GetInternalKeySlot()
  357.  
  358.         LOG.debug("Internal key slot %s", keyslot)
  359.         if not keyslot:
  360.             LOG.error("Failed to retrieve internal KeySlot")
  361.             self.NSS.handle_error()
  362.             raise Exit(Exit.FAIL_NSS_KEYSLOT)
  363.  
  364.         try:
  365.             # NOTE It would be great to be able to check if the profile is
  366.             # protected by a master password. In C++ one would do:
  367.             #   if (keyslot->needLogin):
  368.             # however accessing instance methods is not supported by ctypes.
  369.             # More on this topic: http://stackoverflow.com/a/19636310
  370.             # A possibility would be to define such function using cython but
  371.             # this adds an unecessary runtime dependency
  372.             password = ask_password(self.profile, interactive)
  373.  
  374.             if password:
  375.                 LOG.debug("Authenticating with password '%s'", password)
  376.                 e = self.NSS._PK11_CheckUserPassword(keyslot, password.encode("utf8"))
  377.  
  378.                 LOG.debug("Checking user password returned %s", e)
  379.  
  380.                 if e != 0:
  381.                     LOG.error("Master password is not correct")
  382.  
  383.                     self.NSS.handle_error()
  384.                     raise Exit(Exit.BAD_MASTER_PASSWORD)
  385.  
  386.             else:
  387.                 LOG.warn("Attempting decryption with no Master Password")
  388.         finally:
  389.             # Avoid leaking PK11KeySlot
  390.             self.NSS._PK11_FreeSlot(keyslot)
  391.  
  392.     def unload_profile(self):
  393.         """Shutdown NSS and deactive current profile
  394.         """
  395.         e = self.NSS._NSS_Shutdown()
  396.  
  397.         if e != 0:
  398.             LOG.error("Couldn't shutdown current NSS profile")
  399.  
  400.             self.NSS.handle_error()
  401.             raise Exit(Exit.FAIL_SHUTDOWN_NSS)
  402.  
  403.     def decode_entry(self, user64, passw64):
  404.         """Decrypt one entry in the database
  405.         """
  406.         LOG.debug("Decrypting username data '%s'", user64)
  407.         user = self.NSS.decode(user64)
  408.  
  409.         LOG.debug("Decrypting password data '%s'", passw64)
  410.         passw = self.NSS.decode(passw64)
  411.  
  412.         return user, passw
  413.  
  414.     def decrypt_passwords(self, export, output_format="human", csv_delimiter=";", csv_quotechar="|"):
  415.         """
  416.         Decrypt requested profile using the provided password and print out all
  417.         stored passwords.
  418.         """
  419.         def output_line(line):
  420.             if PY3:
  421.                 sys.stdout.write(line)
  422.             else:
  423.                 sys.stdout.write(line.encode("utf8"))
  424.  
  425.         # Any password in this profile store at all?
  426.         got_password = False
  427.         header = True
  428.  
  429.         credentials = obtain_credentials(self.profile)
  430.  
  431.         LOG.info("Decrypting credentials")
  432.         to_export = {}
  433.  
  434.         if output_format == "csv":
  435.             csv_writer = csv.DictWriter(
  436.                 sys.stdout, fieldnames=["url", "user", "password"],
  437.                 lineterminator="\n", delimiter=csv_delimiter,
  438.                 quotechar=csv_quotechar, quoting=csv.QUOTE_ALL,
  439.             )
  440.             if header:
  441.                 csv_writer.writeheader()
  442.  
  443.         for url, user, passw, enctype in credentials:
  444.             got_password = True
  445.  
  446.             # enctype informs if passwords are encrypted and protected by
  447.             # a master password
  448.             if enctype:
  449.                 user, passw = self.decode_entry(user, passw)
  450.  
  451.             LOG.debug("Decoding username '%s' and password '%s' for website '%s'", user, passw, url)
  452.             LOG.debug("Decoding username '%s' and password '%s' for website '%s'", type(user), type(passw), type(url))
  453.  
  454.             if export:
  455.                 # Keep track of web-address, username and passwords
  456.                 # If more than one username exists for the same web-address
  457.                 # the username will be used as name of the file
  458.                 address = urlparse(url)
  459.  
  460.                 if address.netloc not in to_export:
  461.                     to_export[address.netloc] = {user: passw}
  462.  
  463.                 else:
  464.                     to_export[address.netloc][user] = passw
  465.  
  466.             if output_format == "csv":
  467.                 output = {"url": url, "user": user, "password": passw}
  468.                 if PY3:
  469.                     csv_writer.writerow(output)
  470.                 else:
  471.                     csv_writer.writerow({k: v.encode("utf8") for k, v in output.items()})
  472.  
  473.             else:
  474.                 output = (
  475.                     u"\nWebsite:   {0}\n".format(url),
  476.                     u"Username: '{0}'\n".format(user),
  477.                     u"Password: '{0}'\n".format(passw),
  478.                 )
  479.                 for line in output:
  480.                     output_line(line)
  481.  
  482.         credentials.done()
  483.  
  484.         if not got_password:
  485.             LOG.warn("No passwords found in selected profile")
  486.  
  487.         if export:
  488.             return to_export
  489.  
  490.  
  491. def test_password_store(export):
  492.     """Check if pass from passwordstore.org is installed
  493.     If it is installed but not initialized, initialize it
  494.     """
  495.     # Nothing to do here if exporting wasn't requested
  496.     if not export:
  497.         LOG.debug("Skipping password store test, not exporting")
  498.         return
  499.  
  500.     LOG.debug("Testing if password store is installed and configured")
  501.  
  502.     try:
  503.         p = Popen(["pass"], stdout=PIPE, stderr=PIPE)
  504.     except OSError as e:
  505.         if e.errno == 2:
  506.             LOG.error("Password store is not installed and exporting was requested")
  507.             raise Exit(Exit.PASSSTORE_MISSING)
  508.         else:
  509.             LOG.error("Unknown error happened.")
  510.             LOG.error("Error was %s", e)
  511.             raise Exit(Exit.UNKNOWN_ERROR)
  512.  
  513.     out, err = p.communicate()
  514.     LOG.debug("pass returned: %s %s", out, err)
  515.  
  516.     if p.returncode != 0:
  517.         if 'Try "pass init"' in err:
  518.             LOG.error("Password store was not initialized.")
  519.             LOG.error("Initialize the password store manually by using 'pass init'")
  520.             raise Exit(Exit.PASSSTORE_NOT_INIT)
  521.         else:
  522.             LOG.error("Unknown error happened when running 'pass'.")
  523.             LOG.error("Stdout/Stderr was '%s' '%s'", out, err)
  524.             raise Exit(Exit.UNKNOWN_ERROR)
  525.  
  526.  
  527. def obtain_credentials(profile):
  528.     """Figure out which of the 2 possible backend credential engines is available
  529.     """
  530.     try:
  531.         credentials = JsonCredentials(profile)
  532.     except NotFoundError:
  533.         try:
  534.             credentials = SqliteCredentials(profile)
  535.         except NotFoundError:
  536.             LOG.error("Couldn't find credentials file (logins.json or signons.sqlite).")
  537.             raise Exit(Exit.MISSING_SECRETS)
  538.  
  539.     return credentials
  540.  
  541.  
  542. def export_pass(to_export, prefix):
  543.     """Export given passwords to password store
  544.  
  545.     Format of "to_export" should be:
  546.         {"address": {"login": "password", ...}, ...}
  547.     """
  548.     LOG.info("Exporting credentials to password store")
  549.     for address in to_export:
  550.         for user, passw in to_export[address].items():
  551.             # When more than one account exist for the same address, add
  552.             # the login to the password identifier
  553.             if len(to_export[address]) > 1:
  554.                 passname = u"{0}/{1}/{2}".format(prefix, address, user)
  555.  
  556.             else:
  557.                 passname = u"{0}/{1}".format(prefix, address)
  558.  
  559.             LOG.debug("Exporting credentials for '%s'", passname)
  560.  
  561.             data = u"{0}\n{1}\n".format(passw, user)
  562.  
  563.             LOG.debug("Inserting pass '%s' '%s'", passname, data)
  564.  
  565.             # NOTE --force is used. Existing passwords will be overwritten
  566.             cmd = ["pass", "insert", "--force", "--multiline", passname]
  567.  
  568.             LOG.debug("Running command '%s' with stdin '%s'", cmd, data)
  569.  
  570.             p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)
  571.             out, err = p.communicate(data.encode("utf8"))
  572.  
  573.             if p.returncode != 0:
  574.                 LOG.error("ERROR: passwordstore exited with non-zero: %s", p.returncode)
  575.                 LOG.error("Stdout/Stderr was '%s' '%s'", out, err)
  576.                 raise Exit(Exit.PASSSTORE_ERROR)
  577.  
  578.             LOG.debug("Successfully exported '%s'", passname)
  579.  
  580.  
  581. def get_sections(profiles):
  582.     """
  583.     Returns hash of profile numbers and profile names.
  584.     """
  585.     sections = {}
  586.     i = 1
  587.     for section in profiles.sections():
  588.         if section.startswith("Profile"):
  589.             sections[str(i)] = profiles.get(section, "Path")
  590.             i += 1
  591.         else:
  592.             continue
  593.     return sections
  594.  
  595.  
  596. def print_sections(sections, textIOWrapper=sys.stderr):
  597.     """
  598.     Prints all available sections to an textIOWrapper (defaults to sys.stderr)
  599.     """
  600.     for i in sorted(sections):
  601.         textIOWrapper.write("{0} -> {1}\n".format(i, sections[i]))
  602.     textIOWrapper.flush()
  603.  
  604.  
  605. def ask_section(profiles, choice_arg):
  606.     """
  607.     Prompt the user which profile should be used for decryption
  608.     """
  609.     sections = get_sections(profiles)
  610.  
  611.     # Do not ask for choice if user already gave one
  612.     if choice_arg and len(choice_arg) == 1:
  613.         choice = choice_arg[0]
  614.     else:
  615.         # If only one menu entry exists, use it without prompting
  616.         if len(sections) == 1:
  617.             choice = "1"
  618.  
  619.         else:
  620.             choice = None
  621.             while choice not in sections:
  622.                 sys.stderr.write("Select the Firefox profile you wish to decrypt\n")
  623.                 print_sections(sections)
  624.                 try:
  625.                     choice = raw_input()
  626.                 except EOFError:
  627.                     LOG.error("Could not read Choice, got EOF")
  628.                     raise Exit(Exit.READ_GOT_EOF)
  629.  
  630.     try:
  631.         final_choice = sections[choice]
  632.     except KeyError:
  633.         LOG.error("Profile No. %s does not exist!", choice)
  634.         raise Exit(Exit.NO_SUCH_PROFILE)
  635.  
  636.     LOG.debug("Profile selection matched %s", final_choice)
  637.  
  638.     return final_choice
  639.  
  640.  
  641. def ask_password(profile, interactive):
  642.     """
  643.     Prompt for profile password
  644.     """
  645.     utf8 = "UTF-8"
  646.     input_encoding = utf8 if sys.stdin.encoding in (None, 'ascii') else sys.stdin.encoding
  647.     passmsg = "\nMaster Password for profile {}: ".format(profile)
  648.  
  649.     if sys.stdin.isatty() and interactive:
  650.         passwd = getpass(passmsg)
  651.  
  652.     else:
  653.         # Ability to read the password from stdin (echo "pass" | ./firefox_...)
  654.         passwd = sys.stdin.readline().rstrip("\n")
  655.  
  656.     if PY3:
  657.         return passwd
  658.     else:
  659.         return passwd.decode(input_encoding)
  660.  
  661.  
  662. def read_profiles(basepath, list_profiles):
  663.     """
  664.     Parse Firefox profiles in provided location.
  665.     If list_profiles is true, will exit after listing available profiles.
  666.     """
  667.     profileini = os.path.join(basepath, "profiles.ini")
  668.  
  669.     LOG.debug("Reading profiles from %s", profileini)
  670.  
  671.     if not os.path.isfile(profileini):
  672.         LOG.warn("profile.ini not found in %s", basepath)
  673.         raise Exit(Exit.MISSING_PROFILEINI)
  674.  
  675.     # Read profiles from Firefox profile folder
  676.     profiles = ConfigParser()
  677.     profiles.read(profileini)
  678.  
  679.     LOG.debug("Read profiles %s", profiles.sections())
  680.  
  681.     if list_profiles:
  682.         LOG.debug("Listing available profiles...")
  683.         print_sections(get_sections(profiles), sys.stdout)
  684.         raise Exit(0)
  685.  
  686.     return profiles
  687.  
  688.  
  689. def get_profile(basepath, interactive, choice, list_profiles):
  690.     """
  691.     Select profile to use by either reading profiles.ini or assuming given
  692.     path is already a profile
  693.     If interactive is false, will not try to ask which profile to decrypt.
  694.     choice contains the choice the user gave us as an CLI arg.
  695.     If list_profiles is true will exits after listing all available profiles.
  696.     """
  697.     try:
  698.         profiles = read_profiles(basepath, list_profiles)
  699.     except Exit as e:
  700.         if e.exitcode == Exit.MISSING_PROFILEINI:
  701.             LOG.warn("Continuing and assuming '%s' is a profile location", basepath)
  702.             profile = basepath
  703.  
  704.             if list_profiles:
  705.                 LOG.error("Listing single profiles not permitted.")
  706.                 raise
  707.  
  708.             if not os.path.isdir(profile):
  709.                 LOG.error("Profile location '%s' is not a directory", profile)
  710.                 raise
  711.         else:
  712.             raise
  713.     else:
  714.         if not interactive:
  715.  
  716.             sections = get_sections(profiles)
  717.  
  718.             if choice and len(choice) == 1:
  719.  
  720.                 try:
  721.                     section = sections[(choice[0])]
  722.                 except KeyError:
  723.                     LOG.error("Profile No. %s does not exist!", choice[0])
  724.                     raise Exit(Exit.NO_SUCH_PROFILE)
  725.  
  726.             elif len(sections) == 1:
  727.                 section = sections['1']
  728.  
  729.             else:
  730.                 LOG.error("Don't know which profile to decrypt. We are in non-interactive mode and -c/--choice is missing.")
  731.                 raise Exit(Exit.MISSING_CHOICE)
  732.         else:
  733.             # Ask user which profile to open
  734.             section = ask_section(profiles, choice)
  735.  
  736.         profile = os.path.join(basepath, section)
  737.  
  738.         if not os.path.isdir(profile):
  739.             LOG.error("Profile location '%s' is not a directory. Has profiles.ini been tampered with?", profile)
  740.             raise Exit(Exit.BAD_PROFILEINI)
  741.  
  742.     return profile
  743.  
  744.  
  745. def parse_sys_args():
  746.     """Parse command line arguments
  747.     """
  748.  
  749.     if os.name == "nt":
  750.         profile_path = os.path.join(os.environ['APPDATA'], "Mozilla", "Firefox")
  751.     elif os.uname()[0] == "Darwin":
  752.         profile_path = "~/Library/Application Support/Firefox"
  753.     else:
  754.         profile_path = "~/.mozilla/firefox"
  755.  
  756.     parser = argparse.ArgumentParser(
  757.         description="Access Firefox/Thunderbird profiles and decrypt existing passwords"
  758.     )
  759.     parser.add_argument("profile", nargs="?", default=profile_path,
  760.                         help="Path to profile folder (default: {0})".format(profile_path))
  761.     parser.add_argument("-e", "--export-pass", action="store_true",
  762.                         help="Export URL, username and password to pass from passwordstore.org")
  763.     parser.add_argument("-p", "--pass-prefix", action="store", default=u"web",
  764.                         help="Prefix for export to pass from passwordstore.org (default: %(default)s)")
  765.     parser.add_argument("-f", "--format", action="store", choices={"csv", "human"},
  766.                         default="human", help="Format for the output.")
  767.     parser.add_argument("-d", "--delimiter", action="store", default=";",
  768.                         help="The delimiter for csv output")
  769.     parser.add_argument("-q", "--quotechar", action="store", default='"',
  770.                         help="The quote char for csv output")
  771.     parser.add_argument("-t", "--tabular", action="store_true", help=argparse.SUPPRESS)
  772.     parser.add_argument("-n", "--no-interactive", dest="interactive",
  773.                         default=True, action="store_false",
  774.                         help="Disable interactivity.")
  775.     parser.add_argument("-c", "--choice", nargs=1,
  776.                         help="The profile to use (starts with 1). If only one profile, defaults to that.")
  777.     parser.add_argument("-l", "--list", action="store_true",
  778.                         help="List profiles and exit.")
  779.     parser.add_argument("-v", "--verbose", action="count", default=0,
  780.                         help="Verbosity level. Warning on -vv (highest level) user input will be printed on screen")
  781.     parser.add_argument("--version", action="version", version=__version__,
  782.                         help="Display version of firefox_decrypt and exit")
  783.  
  784.     args = parser.parse_args()
  785.  
  786.     # replace character you can't enter as argument
  787.     if args.delimiter == "\\t":
  788.         args.delimiter = "\t"
  789.  
  790.     if args.tabular:
  791.         args.format = "csv"
  792.         args.delimiter = "\t"
  793.         args.quotechar = "'"
  794.  
  795.     return args
  796.  
  797.  
  798. def setup_logging(args):
  799.     """Setup the logging level and configure the basic logger
  800.     """
  801.     if args.verbose == 1:
  802.         level = logging.INFO
  803.     elif args.verbose >= 2:
  804.         level = logging.DEBUG
  805.     else:
  806.         level = logging.WARN
  807.  
  808.     logging.basicConfig(
  809.         format="%(asctime)s - %(levelname)s - %(message)s",
  810.         level=level,
  811.     )
  812.  
  813.     global LOG
  814.     LOG = logging.getLogger(__name__)
  815.  
  816.  
  817. def main():
  818.     """Main entry point
  819.     """
  820.     args = parse_sys_args()
  821.  
  822.     setup_logging(args)
  823.     if args.tabular:
  824.         LOG.warning("--tabular is deprecated. Use `--format csv --delimiter \\t` instead")
  825.  
  826.     LOG.info("Running firefox_decrypt version: %s", __version__)
  827.     LOG.debug("Parsed commandline arguments: %s", args)
  828.  
  829.     # Check whether pass from passwordstore.org is installed
  830.     test_password_store(args.export_pass)
  831.  
  832.     # Initialize nss before asking the user for input
  833.     nss = NSSInteraction()
  834.  
  835.     basepath = os.path.expanduser(args.profile)
  836.  
  837.     # Read profiles from profiles.ini in profile folder
  838.     profile = get_profile(basepath, args.interactive, args.choice, args.list)
  839.  
  840.     # Start NSS for selected profile
  841.     nss.load_profile(profile)
  842.     # Check if profile is password protected and prompt for a password
  843.     nss.authenticate(args.interactive)
  844.     # Decode all passwords
  845.     to_export = nss.decrypt_passwords(
  846.         export=args.export_pass,
  847.         output_format=args.format,
  848.         csv_delimiter=args.delimiter,
  849.         csv_quotechar=args.quotechar,
  850.     )
  851.  
  852.     if args.export_pass:
  853.         export_pass(to_export, args.pass_prefix)
  854.  
  855.     # And shutdown NSS
  856.     nss.unload_profile()
  857.  
  858.  
  859. if __name__ == "__main__":
  860.     try:
  861.         main()
  862.     except KeyboardInterrupt as e:
  863.         print("Quit.")
  864.         sys.exit(Exit.KEYBOARD_INTERRUPT)
  865.     except Exit as e:
  866.         sys.exit(e.exitcode)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top