Ejemplo n.º 1
0
 def _rules_path(self):
     """
     The configuration file for custom ignore rules.
     """
     return os.path.join(
         get_path_prefix(standalone=self.standalone),
         "leap", self.CONFIG_NAME)
Ejemplo n.º 2
0
def start_app():
    from leap.bitmask.util import STANDALONE

    mypid = os.getpid()

    # Kill a previously-running process
    for proc in psutil.process_iter():
        if proc.name() == PROCNAME and proc.pid != mypid:
            proc.kill()

    # Allow the frozen binary in the bundle double as the cli entrypoint
    # Why have only a user interface when you can have two?

    if STANDALONE and len(sys.argv) > 1:
        if sys.argv[1] == 'bitmask_helpers':
            from leap.bitmask.vpn.helpers import main
            return main()

        from leap.bitmask.cli import bitmask_cli
        return bitmask_cli.main()

    prev_auth = os.path.join(get_path_prefix(), 'leap', 'authtoken')
    try:
        os.remove(prev_auth)
    except OSError:
        pass

    launch_gui()
Ejemplo n.º 3
0
    def __init__(self, cfg, basepath=None):
        """
        Initialize VPN service. This launches both the firewall and the vpn.
        """
        super(VPNService, self).__init__()

        self._tunnel = None
        self._firewall = FirewallManager([])
        self._domain = ''
        self._cfg = cfg

        if basepath is None:
            self._basepath = get_path_prefix()
        else:
            self._basepath = basepath

        try:
            _cco = self._cfg.get('countries', "")
            self._cco = json.loads(_cco)
        except ValueError:
            self._cco = []
        try:
            _loc = self._cfg.get('locations', "")
            self._loc = json.loads(_loc)
        except ValueError:
            self._loc = []

        if helpers.check() and self._firewall.is_up():
            self._firewall.stop()
Ejemplo n.º 4
0
def start_app():
    from leap.bitmask.util import STANDALONE
    os.environ['QT_AUTO_SCREEN_SCALE_FACTOR'] = '1'

    # Allow the frozen binary in the bundle double as the cli entrypoint
    # Why have only a user interface when you can have two?

    if platform.system() == 'Windows':
        # In windows, there are some args added to the invocation
        # by PyInstaller, I guess...
        MIN_ARGS = 3
    else:
        MIN_ARGS = 1

    # DEBUG ====================================
    if STANDALONE and len(sys.argv) > MIN_ARGS:
        if sys.argv[1] == 'bitmask_helpers':
            from leap.bitmask.vpn.helpers import main
            return main()

        from leap.bitmask.cli import bitmask_cli
        return bitmask_cli.main()

    prev_auth = os.path.join(get_path_prefix(), 'leap', 'authtoken')
    try:
        os.remove(prev_auth)
    except OSError:
        pass

    launch_gui()
Ejemplo n.º 5
0
    def __init__(self, *args, **kw):
        url = kw.pop('url', None)
        first = False
        if not url:
            url = "http://localhost:7070"
            path = os.path.join(get_path_prefix(), 'leap', 'authtoken')
            waiting = 20
            while not os.path.isfile(path):
                if waiting == 0:
                    # If we arrive here, something really messed up happened,
                    # because touching the token file is one of the first
                    # things the backend does, and this BrowserWindow
                    # should be called *right after* launching the backend.
                    raise NoAuthToken('No authentication token found!')
                time.sleep(0.1)
                waiting -= 1
            token = open(path).read().strip()
            url += '#' + token
            first = True
        self.url = url
        self.closing = False

        super(QWebView, self).__init__(*args, **kw)
        self.bitmask_browser = NewPageConnector(self) if first else None
        self.loadPage(self.url)

        self.proxy = AppProxy(self) if first else None
        self.frame.addToJavaScriptWindowObject("bitmaskApp", self.proxy)

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/mask-icon.png"), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        self.setWindowIcon(icon)
Ejemplo n.º 6
0
def _save_config(context, step):
    filepath = _artifact_path(step, 'config')
    try:
        shutil.copytree(get_path_prefix(), filepath)
    except OSError:
        pass
    print('copied config folder to:    file://%s' % filepath)
Ejemplo n.º 7
0
def start_pixelated_user_agent(userid, soledad, keymanager, account):

    try:
        leap_session = LeapSessionAdapter(userid, soledad, keymanager, account)
    except Exception as exc:
        log.error("Got error! %r" % exc)

    config = Config()
    leap_home = os.path.join(get_path_prefix(), 'leap')
    config.leap_home = leap_home
    leap_session.config = config

    services_factory = SingleUserServicesFactory(
        UserAgentMode(is_single_user=True))

    if getattr(sys, 'frozen', False):
        # we are running in a |PyInstaller| bundle
        static_folder = os.path.join(sys._MEIPASS, 'leap', 'pixelated_www')
    else:
        static_folder = os.path.abspath(leap.pixelated_www.__path__[0])

    set_static_folder(static_folder)
    resource = RootResource(services_factory, static_folder=static_folder)

    config.host = 'localhost'
    config.port = 9090
    config.sslkey = None
    config.sslcert = None
    config.manhole = False

    d = leap_session.account.callWhenReady(
        lambda _: _start_in_single_user_mode(leap_session, config, resource,
                                             services_factory))
    return d
Ejemplo n.º 8
0
def test_get_path_prefix(scenario, monkeypatch):
    platform, path_parts, standalone = scenario
    if platform == 'win32':
        pytest.skip()  # TODO: find a way to add test for win32 platform
    # set a custom temporary platform
    monkeypatch.setattr(sys, 'platform', platform)
    expected_prefix = os.path.join(*path_parts)
    assert expected_prefix == get_path_prefix(standalone)
Ejemplo n.º 9
0
def test_get_path_prefix(scenario, monkeypatch):
    platform, path_parts, standalone = scenario
    if platform == 'win32':
        pytest.skip()  # TODO: find a way to add test for win32 platform
    # set a custom temporary platform
    monkeypatch.setattr(sys, 'platform', platform)
    expected_prefix = os.path.join(*path_parts)
    assert expected_prefix == get_path_prefix(standalone)
Ejemplo n.º 10
0
 def __init__(self, path_prefix=None):
     """
     Initialize the txzmq component.
     """
     self._factory = txzmq.ZmqFactory()
     self._factory.registerForShutdown()
     if path_prefix == None:
         path_prefix = get_path_prefix()
     self._config_prefix = os.path.join(path_prefix, "leap", "events")
     self._connections = []
Ejemplo n.º 11
0
 def __init__(self, path_prefix=None):
     """
     Initialize the txzmq component.
     """
     self._factory = txzmq.ZmqFactory()
     self._factory.registerForShutdown()
     if path_prefix is None:
         path_prefix = get_path_prefix()
     self._config_prefix = os.path.join(path_prefix, "leap", "events")
     self._connections = []
Ejemplo n.º 12
0
    def get_vpn_env(kls):
        """
        Returns a dictionary with the custom env for the platform.
        This is mainly used for setting LD_LIBRARY_PATH to the correct
        path when distributing a standalone client

        :rtype: dict
        """
        ld_library_path = os.path.join(get_path_prefix(), "..", "lib")
        ld_library_path.encode(sys.getfilesystemencoding())
        return {"DYLD_LIBRARY_PATH": ld_library_path}
Ejemplo n.º 13
0
def cleanup():
    print('[bitmask] cleaning up files')
    base = os.path.join(get_path_prefix(), 'leap')
    token = os.path.join(base, 'authtoken')
    pid = os.path.join(base, 'bitmaskd.pid')
    for _f in [token, pid]:
        if os.path.isfile(_f):
            try:
                os.unlink(_f)
            except Exception:
                pass
Ejemplo n.º 14
0
def get_smtp_config(provider):
    config_path = os.path.join(get_path_prefix(), 'leap', 'providers',
                               provider, 'smtp-service.json')
    json_config = json.loads(open(config_path).read())
    chosen_host = json_config['hosts'].keys()[0]
    hostname = json_config['hosts'][chosen_host]['hostname']
    port = json_config['hosts'][chosen_host]['port']

    config = Config()
    config.host = hostname
    config.port = port
    return config
Ejemplo n.º 15
0
 def __init__(self, emit_addr, reg_addr):
     """
     Initialize the events client.
     """
     threading.Thread.__init__(self)
     EventsClient.__init__(self, emit_addr, reg_addr)
     self._lock = threading.Lock()
     self._initialized = threading.Event()
     self._config_prefix = os.path.join(get_path_prefix(), "leap", "events")
     self._loop = None
     self._context = None
     self._push = None
     self._sub = None
Ejemplo n.º 16
0
    def __init__(self, standalone=False):
        """
        Constructor

        :param standalone: parameter used to define the location of the config.
        :type standalone: bool
        """
        self._path_prefix = get_path_prefix(standalone=standalone)
        settings_path = os.path.join(self._path_prefix,
                                     "leap", self.CONFIG_NAME)

        self._settings = QtCore.QSettings(settings_path,
                                          QtCore.QSettings.IniFormat)
Ejemplo n.º 17
0
 def __init__(self, path_prefix=None, enable_curve=True, factory=None):
     """
     Initialize the txzmq component.
     """
     if path_prefix is None:
         path_prefix = get_path_prefix(flags.STANDALONE)
     if factory is not None:
         self._factory = factory
     self._config_prefix = os.path.join(path_prefix, "leap", "events")
     self._connections = []
     if enable_curve:
         self.use_curve = zmq_has_curve()
     else:
         self.use_curve = False
Ejemplo n.º 18
0
    def __init__(self, basepath=None):
        """
        Initialize VPN service. This launches both the firewall and the vpn.
        """
        super(VPNService, self).__init__()

        self._started = False
        self._vpn = None
        self._domain = ''

        if basepath is None:
            self._basepath = get_path_prefix()
        else:
            self._basepath = basepath
Ejemplo n.º 19
0
 def __init__(self, emit_addr, reg_addr):
     """
     Initialize the events client.
     """
     threading.Thread.__init__(self)
     EventsClient.__init__(self, emit_addr, reg_addr)
     self._lock = threading.Lock()
     self._initialized = threading.Event()
     self._config_prefix = os.path.join(
         get_path_prefix(), "leap", "events")
     self._loop = None
     self._context = None
     self._push = None
     self._sub = None
Ejemplo n.º 20
0
def initial_run(context):
    if context.mode == 'virtualenv':
        cmd = commands.getoutput('which bitmaskctl')
        # print("CMD PATH", cmd)
        commands.getoutput('bitmaskctl stop')
        # TODO: fix bitmaskctl to only exit once bitmaskd has stopped
        time.sleep(2)
        _initialize_home_path()
        commands.getoutput('bitmaskctl start')
        time.sleep(1)
    elif context.mode in ('bundle', 'bundle-ci'):
        commands.getoutput(context.bundle_path)
        time.sleep(2)
    tokenpath = os.path.join(get_path_prefix(), 'leap', 'authtoken')
    token = open(tokenpath).read().strip()
    context.login_url = "http://localhost:7070/#%s" % token
Ejemplo n.º 21
0
def get_authenticated_url():
    url = "http://localhost:7070"
    path = os.path.join(get_path_prefix(), 'leap', 'authtoken')
    waiting = 20
    while not os.path.isfile(path):
        if waiting == 0:
            # If we arrive here, something really messed up happened,
            # because touching the token file is one of the first
            # things the backend does, and this BrowserWindow
            # should be called *right after* launching the backend.
            raise NoAuthTokenError(
                'No authentication token found!')
        time.sleep(0.1)
        waiting -= 1
    token = open(path).read().strip()
    url += '#' + token
    return url
Ejemplo n.º 22
0
def check_stale_pidfile():

    def is_pid_running(pidno):
        return 1 == len(
            filter(lambda p: p.pid == int(pidno), psutil.process_iter()))

    pidno = None
    pidfile = os.path.join(get_path_prefix(), 'leap', 'bitmaskd.pid')
    try:
        if os.path.isfile(pidfile):
            with open(pidfile, 'r') as pid_fd:
                pidno = pid_fd.readline().strip()
        if pidno and pidno.isdigit():
            if not is_pid_running(pidno):
                os.unlink(pidfile)
    except Exception as exc:
        print('[bitmask] Error while removing stale file: %r' % exc)
Ejemplo n.º 23
0
    def __init__(self, emit_addr, reg_addr, factory=None, enable_curve=True):
        """
        Initialize the events client.
        """
        threading.Thread.__init__(self)
        EventsClient.__init__(self, emit_addr, reg_addr)
        self._lock = threading.Lock()
        self._initialized = threading.Event()
        self._config_prefix = os.path.join(
            get_path_prefix(flags.STANDALONE), "leap", "events")
        self._loop = None
        self._factory = factory
        self._context = None
        self._push = None
        self._sub = None

        if enable_curve:
            self.use_curve = zmq_has_curve()
        else:
            self.use_curve = False
Ejemplo n.º 24
0
    def __init__(self, userid, soledad, keymanager):

        self.userid = userid
        self.soledad = soledad

        # XXX this needs to be converged with our public apis.
        _n = NickNym(keymanager, userid)
        self.nicknym = self.keymanager = _n
        self.mail_store = LeapMailStore(soledad)

        self.user_auth = Config()
        self.user_auth.uuid = soledad.uuid

        self.fresh_account = False
        self.incoming_mail_fetcher = None
        self.account = Account(soledad, userid)

        username, provider = userid.split('@')
        smtp_client_cert = os.path.join(
            get_path_prefix(),
            'leap', 'providers', provider, 'keys',
            'client',
            'smtp_{username}.pem'.format(
                username=username))

        _prov = Config()
        _prov.server_name = provider
        self.provider = _prov

        assert(os.path.isfile(smtp_client_cert))

        smtp_config = get_smtp_config(provider)
        smtp_host = smtp_config.host
        smtp_port = smtp_config.port

        self.smtp_config = LeapSMTPConfig(
            userid,
            smtp_client_cert, smtp_host, smtp_port)
Ejemplo n.º 25
0
    def __init__(self, *args, **kw):
        url = kw.pop('url', None)
        first = False
        if not url:
            url = "http://localhost:7070"
            path = os.path.join(get_path_prefix(), 'leap', 'authtoken')
            waiting = 20
            while not os.path.isfile(path):
                if waiting == 0:
                    # If we arrive here, something really messed up happened,
                    # because touching the token file is one of the first
                    # things the backend does, and this BrowserWindow
                    # should be called *right after* launching the backend.
                    raise NoAuthToken('No authentication token found!')
                time.sleep(0.1)
                waiting -= 1
            token = open(path).read().strip()
            url += '#' + token
            first = True
        self.url = url
        self.closing = False

        webview.create_window('Bitmask', self.url)
Ejemplo n.º 26
0
    def __init__(self, cfg, basepath=None):
        """
        Initialize VPN service. This launches both the firewall and the vpn.
        """
        super(VPNService, self).__init__()

        self._tunnel = None
        self._firewall = FirewallManager([])
        self._domain = ''
        self._cfg = cfg

        if basepath is None:
            self._basepath = get_path_prefix()
        else:
            self._basepath = basepath

        try:
            _cco = self._cfg.get('countries', "")
            self._cco = json.loads(_cco)
        except ValueError:
            self._cco = []
        try:
            _loc = self._cfg.get('locations', "")
            self._loc = json.loads(_loc)
        except ValueError:
            self._loc = []

        _autostart = self._cfg.get('autostart', False, boolean=True)
        self._autostart = _autostart

        _anonymous = self._cfg.get('anonymous', True, boolean=True)
        self._anonymous_enabled = _anonymous

        if helpers.check() and self._firewall.is_up():
            self._firewall.stop()

        self.watchdog = LoopingCall(self.push_status)
Ejemplo n.º 27
0
class Soledad(object):
    """
    Soledad provides encrypted data storage and sync.

    A Soledad instance is used to store and retrieve data in a local encrypted
    database and synchronize this database with Soledad server.

    This class is also responsible for bootstrapping users' account by
    creating cryptographic secrets and/or storing/fetching them on Soledad
    server.

    Soledad uses ``leap.common.events`` to signal events. The possible events
    to be signaled are:

        SOLEDAD_CREATING_KEYS: emitted during bootstrap sequence when key
            generation starts.
        SOLEDAD_DONE_CREATING_KEYS: emitted during bootstrap sequence when key
            generation finishes.
        SOLEDAD_UPLOADING_KEYS: emitted during bootstrap sequence when soledad
            starts sending keys to server.
        SOLEDAD_DONE_UPLOADING_KEYS: emitted during bootstrap sequence when
            soledad finishes sending keys to server.
        SOLEDAD_DOWNLOADING_KEYS: emitted during bootstrap sequence when
            soledad starts to retrieve keys from server.
        SOLEDAD_DONE_DOWNLOADING_KEYS: emitted during bootstrap sequence when
            soledad finishes downloading keys from server.
        SOLEDAD_NEW_DATA_TO_SYNC: emitted upon call to C{need_sync()} when
          there's indeed new data to be synchronized between local database
          replica and server's replica.
        SOLEDAD_DONE_DATA_SYNC: emitted inside C{sync()} method when it has
            finished synchronizing with remote replica.
    """
    implements(soledad_interfaces.ILocalStorage,
               soledad_interfaces.ISyncableStorage,
               soledad_interfaces.ISecretsStorage)

    local_db_file_name = 'soledad.u1db'
    secrets_file_name = "soledad.json"
    default_prefix = os.path.join(get_path_prefix(), 'leap', 'soledad')

    def __init__(self,
                 uuid,
                 passphrase,
                 secrets_path,
                 local_db_path,
                 server_url,
                 cert_file,
                 shared_db=None,
                 auth_token=None,
                 defer_encryption=False,
                 syncable=True):
        """
        Initialize configuration, cryptographic keys and dbs.

        :param uuid: User's uuid.
        :type uuid: str

        :param passphrase:
            The passphrase for locking and unlocking encryption secrets for
            local and remote storage.
        :type passphrase: unicode

        :param secrets_path:
            Path for storing encrypted key used for symmetric encryption.
        :type secrets_path: str

        :param local_db_path: Path for local encrypted storage db.
        :type local_db_path: str

        :param server_url:
            URL for Soledad server. This is used either to sync with the user's
            remote db and to interact with the shared recovery database.
        :type server_url: str

        :param cert_file:
            Path to the certificate of the ca used to validate the SSL
            certificate used by the remote soledad server.
        :type cert_file: str

        :param shared_db:
            The shared database.
        :type shared_db: HTTPDatabase

        :param auth_token:
            Authorization token for accessing remote databases.
        :type auth_token: str

        :param defer_encryption:
            Whether to defer encryption/decryption of documents, or do it
            inline while syncing.
        :type defer_encryption: bool

        :param syncable:
            If set to ``False``, this database will not attempt to synchronize
            with remote replicas (default is ``True``)
        :type syncable: bool

        :raise BootstrapSequenceError:
            Raised when the secret initialization sequence (i.e. retrieval
            from server or generation and storage on server) has failed for
            some reason.
        """
        # store config params
        self._uuid = uuid
        self._passphrase = passphrase
        self._local_db_path = local_db_path
        self._server_url = server_url
        self._defer_encryption = defer_encryption
        self._secrets_path = None

        self.shared_db = shared_db

        # configure SSL certificate
        global SOLEDAD_CERT
        SOLEDAD_CERT = cert_file

        # init crypto variables
        self._set_token(auth_token)
        self._crypto = SoledadCrypto(self)

        self._init_config_with_defaults()
        self._init_working_dirs()

        self._secrets_path = secrets_path

        # Initialize shared recovery database
        self.init_shared_db(server_url, uuid, self._creds, syncable=syncable)

        # The following can raise BootstrapSequenceError, that will be
        # propagated upwards.
        self._init_secrets()
        self._init_u1db_sqlcipher_backend()

        if syncable:
            self._init_u1db_syncer()

    #
    # initialization/destruction methods
    #
    def _init_config_with_defaults(self):
        """
        Initialize configuration using default values for missing params.
        """
        soledad_assert_type(self._passphrase, unicode)
        initialize = lambda attr, val: getattr(
            self, attr, None) is None and setattr(self, attr, val)

        initialize("_secrets_path",
                   os.path.join(self.default_prefix, self.secrets_file_name))
        initialize("_local_db_path",
                   os.path.join(self.default_prefix, self.local_db_file_name))
        # initialize server_url
        soledad_assert(self._server_url is not None,
                       'Missing URL for Soledad server.')

    def _init_working_dirs(self):
        """
        Create work directories.

        :raise OSError: in case file exists and is not a dir.
        """
        paths = map(lambda x: os.path.dirname(x),
                    [self._local_db_path, self._secrets_path])
        for path in paths:
            create_path_if_not_exists(path)

    def _init_secrets(self):
        """
        Initialize Soledad secrets.
        """
        self._secrets = SoledadSecrets(self.uuid, self._passphrase,
                                       self._secrets_path, self.shared_db,
                                       self._crypto)
        self._secrets.bootstrap()

    def _init_u1db_sqlcipher_backend(self):
        """
        Initialize the U1DB SQLCipher database for local storage.

        Instantiates a modified twisted adbapi that will maintain a threadpool
        with a u1db-sqclipher connection for each thread, and will return
        deferreds for each u1db query.

        Currently, Soledad uses the default SQLCipher cipher, i.e.
        'aes-256-cbc'. We use scrypt to derive a 256-bit encryption key,
        and internally the SQLCipherDatabase initialization uses the 'raw
        PRAGMA key' format to handle the key to SQLCipher.
        """
        tohex = binascii.b2a_hex
        # sqlcipher only accepts the hex version
        key = tohex(self._secrets.get_local_storage_key())
        sync_db_key = tohex(self._secrets.get_sync_db_key())

        opts = SQLCipherOptions(
            self._local_db_path,
            key,
            is_raw_key=True,
            create=True,
            defer_encryption=self._defer_encryption,
            sync_db_key=sync_db_key,
        )
        self._sqlcipher_opts = opts
        self._dbpool = adbapi.getConnectionPool(opts)

    def _init_u1db_syncer(self):
        """
        Initialize the U1DB synchronizer.
        """
        replica_uid = self._dbpool.replica_uid
        self._dbsyncer = SQLCipherU1DBSync(
            self._sqlcipher_opts,
            self._crypto,
            replica_uid,
            SOLEDAD_CERT,
            defer_encryption=self._defer_encryption)

    #
    # Closing methods
    #

    def close(self):
        """
        Close underlying U1DB database.
        """
        logger.debug("Closing soledad")
        self._dbpool.close()
        if getattr(self, '_dbsyncer', None):
            self._dbsyncer.close()

    #
    # ILocalStorage
    #

    def _defer(self, meth, *args, **kw):
        """
        Defer a method to be run on a U1DB connection pool.

        :param meth: A method to defer to the U1DB connection pool.
        :type meth: callable
        :return: A deferred.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._dbpool.runU1DBQuery(meth, *args, **kw)

    def put_doc(self, doc):
        """
        Update a document.

        If the document currently has conflicts, put will fail.
        If the database specifies a maximum document size and the document
        exceeds it, put will fail and raise a DocumentTooBig exception.

        ============================== WARNING ==============================
        This method converts the document's contents to unicode in-place. This
        means that after calling `put_doc(doc)`, the contents of the
        document, i.e. `doc.content`, might be different from before the
        call.
        ============================== WARNING ==============================

        :param doc: A document with new content.
        :type doc: leap.soledad.common.document.SoledadDocument
        :return: A deferred whose callback will be invoked with the new
            revision identifier for the document. The document object will
            also be updated.
        :rtype: twisted.internet.defer.Deferred
        """
        doc.content = _convert_to_unicode(doc.content)
        return self._defer("put_doc", doc)

    def delete_doc(self, doc):
        """
        Mark a document as deleted.

        Will abort if the current revision doesn't match doc.rev.
        This will also set doc.content to None.

        :param doc: A document to be deleted.
        :type doc: leap.soledad.common.document.SoledadDocument
        :return: A deferred.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("delete_doc", doc)

    def get_doc(self, doc_id, include_deleted=False):
        """
        Get the JSON string for the given document.

        :param doc_id: The unique document identifier
        :type doc_id: str
        :param include_deleted: If set to True, deleted documents will be
            returned with empty content. Otherwise asking for a deleted
            document will return None.
        :type include_deleted: bool
        :return: A deferred whose callback will be invoked with a document
            object.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_doc", doc_id, include_deleted=include_deleted)

    def get_docs(self,
                 doc_ids,
                 check_for_conflicts=True,
                 include_deleted=False):
        """
        Get the JSON content for many documents.

        :param doc_ids: A list of document identifiers.
        :type doc_ids: list
        :param check_for_conflicts: If set to False, then the conflict check
            will be skipped, and 'None' will be returned instead of True/False.
        :type check_for_conflicts: bool
        :param include_deleted: If set to True, deleted documents will be
            returned with empty content. Otherwise deleted documents will not
            be included in the results.
        :type include_deleted: bool
        :return: A deferred whose callback will be invoked with an iterable
            giving the document object for each document id in matching
            doc_ids order.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_docs",
                           doc_ids,
                           check_for_conflicts=check_for_conflicts,
                           include_deleted=include_deleted)

    def get_all_docs(self, include_deleted=False):
        """
        Get the JSON content for all documents in the database.

        :param include_deleted: If set to True, deleted documents will be
            returned with empty content. Otherwise deleted documents will not
            be included in the results.
        :type include_deleted: bool

        :return: A deferred which, when fired, will pass the a tuple
            containing (generation, [Document]) to the callback, with the
            current generation of the database, followed by a list of all the
            documents in the database.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_all_docs", include_deleted)

    def create_doc(self, content, doc_id=None):
        """
        Create a new document.

        You can optionally specify the document identifier, but the document
        must not already exist. See 'put_doc' if you want to override an
        existing document.
        If the database specifies a maximum document size and the document
        exceeds it, create will fail and raise a DocumentTooBig exception.

        :param content: A Python dictionary.
        :type content: dict
        :param doc_id: An optional identifier specifying the document id.
        :type doc_id: str
        :return: A deferred whose callback will be invoked with a document.
        :rtype: twisted.internet.defer.Deferred
        """
        # TODO we probably should pass an optional "encoding" parameter to
        # create_doc (and probably to put_doc too). There are cases (mail
        # payloads for example) in which we already have the encoding in the
        # headers, so we don't need to guess it.
        return self._defer("create_doc",
                           _convert_to_unicode(content),
                           doc_id=doc_id)

    def create_doc_from_json(self, json, doc_id=None):
        """
        Create a new document.

        You can optionally specify the document identifier, but the document
        must not already exist. See 'put_doc' if you want to override an
        existing document.
        If the database specifies a maximum document size and the document
        exceeds it, create will fail and raise a DocumentTooBig exception.

        :param json: The JSON document string
        :type json: dict
        :param doc_id: An optional identifier specifying the document id.
        :type doc_id: str
        :return: A deferred whose callback will be invoked with a document.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("create_doc_from_json", json, doc_id=doc_id)

    def create_index(self, index_name, *index_expressions):
        """
        Create a named index, which can then be queried for future lookups.

        Creating an index which already exists is not an error, and is cheap.
        Creating an index which does not match the index_expressions of the
        existing index is an error.
        Creating an index will block until the expressions have been evaluated
        and the index generated.

        :param index_name: A unique name which can be used as a key prefix
        :type index_name: str
        :param index_expressions: index expressions defining the index
            information.

            Examples:

            "fieldname", or "fieldname.subfieldname" to index alphabetically
            sorted on the contents of a field.

            "number(fieldname, width)", "lower(fieldname)"
        :type index_expresions: list of str
        :return: A deferred.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("create_index", index_name, *index_expressions)

    def delete_index(self, index_name):
        """
        Remove a named index.

        :param index_name: The name of the index we are removing
        :type index_name: str
        :return: A deferred.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("delete_index", index_name)

    def list_indexes(self):
        """
        List the definitions of all known indexes.

        :return: A deferred whose callback will be invoked with a list of
            [('index-name', ['field', 'field2'])] definitions.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("list_indexes")

    def get_from_index(self, index_name, *key_values):
        """
        Return documents that match the keys supplied.

        You must supply exactly the same number of values as have been defined
        in the index. It is possible to do a prefix match by using '*' to
        indicate a wildcard match. You can only supply '*' to trailing entries,
        (eg 'val', '*', '*' is allowed, but '*', 'val', 'val' is not.)
        It is also possible to append a '*' to the last supplied value (eg
        'val*', '*', '*' or 'val', 'val*', '*', but not 'val*', 'val', '*')

        :param index_name: The index to query
        :type index_name: str
        :param key_values: values to match. eg, if you have
            an index with 3 fields then you would have:
            get_from_index(index_name, val1, val2, val3)
        :type key_values: list
        :return: A deferred whose callback will be invoked with a list of
            [Document].
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_from_index", index_name, *key_values)

    def get_count_from_index(self, index_name, *key_values):
        """
        Return the count for a given combination of index_name
        and key values.

        Extension method made from similar methods in u1db version 13.09

        :param index_name: The index to query
        :type index_name: str
        :param key_values: values to match. eg, if you have
                           an index with 3 fields then you would have:
                           get_from_index(index_name, val1, val2, val3)
        :type key_values: tuple
        :return: A deferred whose callback will be invoked with the count.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_count_from_index", index_name, *key_values)

    def get_range_from_index(self, index_name, start_value, end_value):
        """
        Return documents that fall within the specified range.

        Both ends of the range are inclusive. For both start_value and
        end_value, one must supply exactly the same number of values as have
        been defined in the index, or pass None. In case of a single column
        index, a string is accepted as an alternative for a tuple with a single
        value. It is possible to do a prefix match by using '*' to indicate
        a wildcard match. You can only supply '*' to trailing entries, (eg
        'val', '*', '*' is allowed, but '*', 'val', 'val' is not.) It is also
        possible to append a '*' to the last supplied value (eg 'val*', '*',
        '*' or 'val', 'val*', '*', but not 'val*', 'val', '*')

        :param index_name: The index to query
        :type index_name: str
        :param start_values: tuples of values that define the lower bound of
            the range. eg, if you have an index with 3 fields then you would
            have: (val1, val2, val3)
        :type start_values: tuple
        :param end_values: tuples of values that define the upper bound of the
            range. eg, if you have an index with 3 fields then you would have:
            (val1, val2, val3)
        :type end_values: tuple
        :return: A deferred whose callback will be invoked with a list of
            [Document].
        :rtype: twisted.internet.defer.Deferred
        """

        return self._defer("get_range_from_index", index_name, start_value,
                           end_value)

    def get_index_keys(self, index_name):
        """
        Return all keys under which documents are indexed in this index.

        :param index_name: The index to query
        :type index_name: str
        :return: A deferred whose callback will be invoked with a list of
            tuples of indexed keys.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_index_keys", index_name)

    def get_doc_conflicts(self, doc_id):
        """
        Get the list of conflicts for the given document.

        The order of the conflicts is such that the first entry is the value
        that would be returned by "get_doc".

        :param doc_id: The unique document identifier
        :type doc_id: str
        :return: A deferred whose callback will be invoked with a list of the
            Document entries that are conflicted.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_doc_conflicts", doc_id)

    def resolve_doc(self, doc, conflicted_doc_revs):
        """
        Mark a document as no longer conflicted.

        We take the list of revisions that the client knows about that it is
        superseding. This may be a different list from the actual current
        conflicts, in which case only those are removed as conflicted.  This
        may fail if the conflict list is significantly different from the
        supplied information. (sync could have happened in the background from
        the time you GET_DOC_CONFLICTS until the point where you RESOLVE)

        :param doc: A Document with the new content to be inserted.
        :type doc: SoledadDocument
        :param conflicted_doc_revs: A list of revisions that the new content
            supersedes.
        :type conflicted_doc_revs: list(str)
        :return: A deferred.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("resolve_doc", doc, conflicted_doc_revs)

    @property
    def local_db_path(self):
        return self._local_db_path

    @property
    def uuid(self):
        return self._uuid

    #
    # ISyncableStorage
    #

    def sync(self, defer_decryption=True):
        """
        Synchronize documents with the server replica.

        :param defer_decryption:
            Whether to defer decryption of documents, or do it inline while
            syncing.
        :type defer_decryption: bool

        :return: A deferred whose callback will be invoked with the local
            generation before the synchronization was performed.
        :rtype: twisted.internet.defer.Deferred
        """

        # -----------------------------------------------------------------
        # TODO this needs work.
        # Should review/write tests to check that this:

        # (1) Defer to the syncer pool -- DONE (on dbsyncer)
        # (2) Return the deferred
        # (3) Add the callback for signaling the event (executed on reactor
        #     thread)
        # (4) Check that the deferred is called with the local gen.

        # -----------------------------------------------------------------

        sync_url = urlparse.urljoin(self._server_url, 'user-%s' % self.uuid)
        d = self._dbsyncer.sync(sync_url,
                                creds=self._creds,
                                defer_decryption=defer_decryption)

        def _sync_callback(local_gen):
            self._last_received_docs = docs = self._dbsyncer.received_docs

            # Post-Sync Hooks
            if docs:
                iface = soledad_interfaces.ISoledadPostSyncPlugin
                suitable_plugins = collect_plugins(iface)
                for plugin in suitable_plugins:
                    watched = plugin.watched_doc_types
                    r = [
                        filter(lambda s: s.startswith(preffix), docs)
                        for preffix in watched
                    ]
                    filtered = list(chain(*r))
                    plugin.process_received_docs(filtered)

            soledad_events.emit(soledad_events.SOLEDAD_DONE_DATA_SYNC,
                                self.uuid)
            return local_gen

        def _sync_errback(failure):
            s = StringIO()
            failure.printDetailedTraceback(file=s)
            msg = "Soledad exception when syncing!\n" + s.getvalue()
            logger.error(msg)
            return failure

        d.addCallbacks(_sync_callback, _sync_errback)
        return d

    @property
    def syncing(self):
        """
        Return wether Soledad is currently synchronizing with the server.

        :return: Wether Soledad is currently synchronizing with the server.
        :rtype: bool
        """
        return self._dbsyncer.syncing

    def _set_token(self, token):
        """
        Set the authentication token for remote database access.

        Internally, this builds the credentials dictionary with the following
        format:

            {
                'token': {
                    'uuid': '<uuid>'
                    'token': '<token>'
                }
            }

        :param token: The authentication token.
        :type token: str
        """
        self._creds = {
            'token': {
                'uuid': self.uuid,
                'token': token,
            }
        }

    def _get_token(self):
        """
        Return current token from credentials dictionary.
        """
        return self._creds['token']['token']

    token = property(_get_token, _set_token, doc='The authentication Token.')

    #
    # ISecretsStorage
    #

    def init_shared_db(self, server_url, uuid, creds, syncable=True):
        """
        Initialize the shared database.

        :param server_url: URL of the remote database.
        :type server_url: str
        :param uuid: The user's unique id.
        :type uuid: str
        :param creds: A tuple containing the authentication method and
            credentials.
        :type creds: tuple
        :param syncable:
            If syncable is False, the database will not attempt to sync against
            a remote replica.
        :type syncable: bool
        """
        # only case this is False is for testing purposes
        if self.shared_db is None:
            shared_db_url = urlparse.urljoin(server_url, SHARED_DB_NAME)
            self.shared_db = SoledadSharedDatabase.open_database(
                shared_db_url, uuid, creds=creds, syncable=syncable)

    @property
    def storage_secret(self):
        """
        Return the secret used for local storage encryption.

        :return: The secret used for local storage encryption.
        :rtype: str
        """
        return self._secrets.storage_secret

    @property
    def remote_storage_secret(self):
        """
        Return the secret used for encryption of remotely stored data.

        :return: The secret used for remote storage  encryption.
        :rtype: str
        """
        return self._secrets.remote_storage_secret

    @property
    def secrets(self):
        """
        Return the secrets object.

        :return: The secrets object.
        :rtype: SoledadSecrets
        """
        return self._secrets

    def change_passphrase(self, new_passphrase):
        """
        Change the passphrase that encrypts the storage secret.

        :param new_passphrase: The new passphrase.
        :type new_passphrase: unicode

        :raise NoStorageSecret: Raised if there's no storage secret available.
        """
        self._secrets.change_passphrase(new_passphrase)

    #
    # Raw SQLCIPHER Queries
    #

    def raw_sqlcipher_query(self, *args, **kw):
        """
        Run a raw sqlcipher query in the local database, and return a deferred
        that will be fired with the result.
        """
        return self._dbpool.runQuery(*args, **kw)

    def raw_sqlcipher_operation(self, *args, **kw):
        """
        Run a raw sqlcipher operation in the local database, and return a
        deferred that will be fired with None.
        """
        return self._dbpool.runOperation(*args, **kw)
Ejemplo n.º 28
0
 def get_path_prefix(self):
     """
     Returns the platform dependant path prefixer
     """
     return get_path_prefix(standalone=self.standalone)
Ejemplo n.º 29
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Configuration parser/writter
"""
import ConfigParser
import os

from leap.common import files
from leap.common.config import get_path_prefix

DEFAULT_BASEDIR = os.path.join(get_path_prefix(), 'leap')


class MissingConfigEntry(Exception):
    """
    A required config entry was not found.
    """


class Configuration(object):
    def __init__(self,
                 config_file,
                 basedir=DEFAULT_BASEDIR,
                 default_config=""):
        path = os.path.abspath(os.path.expanduser(basedir))
        if not os.path.isdir(path):
Ejemplo n.º 30
0
 def test_standalone_path(self):
     expected_path = os.path.join('expected', 'path', 'config')
     fake_cwd = os.path.join('expected', 'path')
     with mock.patch('os.getcwd', lambda: fake_cwd):
         path = get_path_prefix(standalone=True)
     self.assertEquals(path, expected_path)
Ejemplo n.º 31
0
A minimal entrypoint to the Bitmask UI,
that depends on chromium being installed in the system.
"""

import commands
import os
import sys
import time

from multiprocessing import Process

from leap.bitmask.core.launcher import run_bitmaskd, pid
from leap.common.config import get_path_prefix


AUTHTOKEN_PATH = os.path.join(get_path_prefix(), 'leap', 'authtoken')


def get_url():
    url = "http://localhost:7070"
    waiting = 20
    while not os.path.isfile(AUTHTOKEN_PATH):
        if waiting == 0:
            # If we arrive here, something really messed up happened,
            # because touching the token file is one of the first
            # things the backend does, and this BrowserWindow
            # should be called *right after* launching the backend.
            raise NoAuthToken(
                'No authentication token found!')
        time.sleep(0.1)
        waiting -= 1
Ejemplo n.º 32
0
"""
Bonafide Service.
"""
import os
from collections import defaultdict

from leap.common.config import get_path_prefix
from leap.common.service_hooks import HookableService
from leap.bonafide._protocol import BonafideProtocol

from twisted.internet import defer
from twisted.python import log


_preffix = get_path_prefix()


class BonafideService(HookableService):

    def __init__(self, basedir=None):
        if not basedir:
            basedir = os.path.join(_preffix, 'leap')
        self._basedir = os.path.expanduser(basedir)
        self._bonafide = BonafideProtocol()
        self.service_hooks = defaultdict(list)

        # XXX this is a quick hack to get a ref
        # to the latest authenticated user.
        self._active_user = None
Ejemplo n.º 33
0
from leap.bitmask.bonafide.session import Session, OK
from leap.common.config import get_path_prefix

from twisted.cred.credentials import UsernamePassword
from twisted.internet.defer import fail
from twisted.logger import Logger


# TODO [ ] enable-disable services
# TODO [ ] read provider info

logger = Logger()


COMMANDS = 'signup', 'authenticate', 'logout', 'stats'
_preffix = get_path_prefix()


class BonafideProtocol(object):
    """
    Expose the protocol that interacts with the Bonafide Service API.
    """

    _apis = defaultdict(None)
    _sessions = defaultdict(None)

    def _get_api(self, provider):
        # TODO should get deferred
        if provider.domain in self._apis:
            return self._apis[provider.domain]
Ejemplo n.º 34
0
 def test_path_prefix(self):
     standalone_path = get_path_prefix(standalone=True)
     path = get_path_prefix(standalone=False)
     self.assertNotEquals(path, standalone_path)
Ejemplo n.º 35
0
class Soledad(object):
    """
    Soledad provides encrypted data storage and sync.

    A Soledad instance is used to store and retrieve data in a local encrypted
    database and synchronize this database with Soledad server.

    This class is also responsible for bootstrapping users' account by
    creating cryptographic secrets and/or storing/fetching them on Soledad
    server.
    """

    local_db_file_name = 'soledad.u1db'
    secrets_file_name = "soledad.json"
    default_prefix = os.path.join(get_path_prefix(), 'leap', 'soledad')

    """
    A dictionary that holds locks which avoid multiple sync attempts from the
    same database replica. The dictionary indexes are the paths to each local
    db, so we guarantee that only one sync happens for a local db at a time.
    """
    _sync_lock = defaultdict(defer.DeferredLock)

    def __init__(self, uuid, passphrase, secrets_path, local_db_path,
                 server_url, cert_file, shared_db=None,
                 auth_token=None, with_blobs=False):
        """
        Initialize configuration, cryptographic keys and dbs.

        :param uuid: User's uuid.
        :type uuid: str

        :param passphrase:
            The passphrase for locking and unlocking encryption secrets for
            local and remote storage.
        :type passphrase: unicode

        :param secrets_path:
            Path for storing encrypted key used for symmetric encryption.
        :type secrets_path: str

        :param local_db_path: Path for local encrypted storage db.
        :type local_db_path: str

        :param server_url:
            URL for Soledad server. This is used either to sync with the user's
            remote db and to interact with the shared recovery database.
        :type server_url: str

        :param cert_file:
            Path to the certificate of the ca used to validate the SSL
            certificate used by the remote soledad server.
        :type cert_file: str

        :param shared_db:
            The shared database.
        :type shared_db: HTTPDatabase

        :param auth_token:
            Authorization token for accessing remote databases.
        :type auth_token: str

        :param with_blobs:
            A boolean that specifies if this soledad instance should enable
            blobs storage when initialized. This will raise if it's not the
            first initialization and the passed value is different from when
            the database was first initialized.

        :raise BootstrapSequenceError:
            Raised when the secret initialization sequence (i.e. retrieval
            from server or generation and storage on server) has failed for
            some reason.
        """
        # store config params
        self.uuid = uuid
        self.passphrase = passphrase
        self.secrets_path = secrets_path
        self._local_db_path = local_db_path
        self.server_url = server_url
        self.shared_db = shared_db
        self.token = auth_token

        self._dbsyncer = None

        # configure SSL certificate
        global SOLEDAD_CERT
        SOLEDAD_CERT = cert_file

        self._init_config_with_defaults()
        self._init_working_dirs()

        self._recovery_code = RecoveryCode()
        self._secrets = Secrets(self)
        self._crypto = SoledadCrypto(self._secrets.remote_secret)

        try:
            # initialize database access, trap any problems so we can shutdown
            # smoothly.
            self._init_u1db_sqlcipher_backend()
            self._init_u1db_syncer()
        except DatabaseAccessError:
            # oops! something went wrong with backend initialization. We
            # have to close any thread-related stuff we have already opened
            # here, otherwise there might be zombie threads that may clog the
            # reactor.
            if hasattr(self, '_dbpool'):
                self._dbpool.close()
            raise

        if with_blobs:
            self._init_blobmanager()
        else:
            self.blobmanager = None

    #
    # initialization/destruction methods
    #

    def _init_config_with_defaults(self):
        """
        Initialize configuration using default values for missing params.
        """
        soledad_assert_type(self.passphrase, unicode)

        def initialize(attr, val):
            return ((getattr(self, attr, None) is None) and
                    setattr(self, attr, val))

        initialize("_secrets_path", os.path.join(
            self.default_prefix, self.secrets_file_name))
        initialize("_local_db_path", os.path.join(
            self.default_prefix, self.local_db_file_name))
        # initialize server_url
        soledad_assert(self.server_url is not None,
                       'Missing URL for Soledad server.')

    def _init_working_dirs(self):
        """
        Create work directories.

        :raise OSError: in case file exists and is not a dir.
        """
        paths = map(lambda x: os.path.dirname(x), [
            self._local_db_path, self._secrets_path])
        for path in paths:
            create_path_if_not_exists(path)

    def _init_u1db_sqlcipher_backend(self):
        """
        Initialize the U1DB SQLCipher database for local storage.

        Instantiates a modified twisted adbapi that will maintain a threadpool
        with a u1db-sqclipher connection for each thread, and will return
        deferreds for each u1db query.

        Currently, Soledad uses the default SQLCipher cipher, i.e.
        'aes-256-cbc'. We use scrypt to derive a 256-bit encryption key,
        and internally the SQLCipherDatabase initialization uses the 'raw
        PRAGMA key' format to handle the key to SQLCipher.
        """
        tohex = binascii.b2a_hex
        # sqlcipher only accepts the hex version
        key = tohex(self._secrets.local_key)

        opts = sqlcipher.SQLCipherOptions(
            self._local_db_path, key,
            is_raw_key=True, create=True)
        self._sqlcipher_opts = opts
        self._dbpool = adbapi.getConnectionPool(opts)

    def _init_u1db_syncer(self):
        """
        Initialize the U1DB synchronizer.
        """
        replica_uid = self._dbpool.replica_uid
        self._dbsyncer = sqlcipher.SQLCipherU1DBSync(
            self._sqlcipher_opts, self._crypto, replica_uid,
            SOLEDAD_CERT)

    def sync_stats(self):
        sync_phase = 0
        if getattr(self._dbsyncer, 'sync_phase', None):
            sync_phase = self._dbsyncer.sync_phase[0]
        sync_exchange_phase = 0
        if getattr(self._dbsyncer, 'syncer', None):
            if getattr(self._dbsyncer.syncer, 'sync_exchange_phase', None):
                _p = self._dbsyncer.syncer.sync_exchange_phase[0]
                sync_exchange_phase = _p
        return sync_phase, sync_exchange_phase

    def _init_blobmanager(self):
        path = os.path.dirname(self._local_db_path)
        url = urlparse.urljoin(self.server_url, 'blobs/%s' % self.uuid)
        key = self._secrets.local_key
        self.blobmanager = blobs.BlobManager(
            path, url, key, self._secrets.remote_secret,
            self.uuid, self.token, SOLEDAD_CERT)

    #
    # Closing methods
    #

    def close(self):
        """
        Close underlying U1DB database.
        """
        logger.debug("closing soledad")
        self._dbpool.close()
        if self.blobmanager:
            self.blobmanager.close()
        if getattr(self, '_dbsyncer', None):
            self._dbsyncer.close()

    #
    # ILocalStorage
    #

    def _defer(self, meth, *args, **kw):
        """
        Defer a method to be run on a U1DB connection pool.

        :param meth: A method to defer to the U1DB connection pool.
        :type meth: callable
        :return: A deferred.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._dbpool.runU1DBQuery(meth, *args, **kw)

    def put_doc(self, doc):
        """
        Update a document.

        If the document currently has conflicts, put will fail.
        If the database specifies a maximum document size and the document
        exceeds it, put will fail and raise a DocumentTooBig exception.

        ============================== WARNING ==============================
        This method converts the document's contents to unicode in-place. This
        means that after calling `put_doc(doc)`, the contents of the
        document, i.e. `doc.content`, might be different from before the
        call.
        ============================== WARNING ==============================

        :param doc: A document with new content.
        :type doc: leap.soledad.common.document.Document
        :return: A deferred whose callback will be invoked with the new
            revision identifier for the document. The document object will
            also be updated.
        :rtype: twisted.internet.defer.Deferred
        """
        d = self._defer("put_doc", doc)
        return d

    def delete_doc(self, doc):
        """
        Mark a document as deleted.

        Will abort if the current revision doesn't match doc.rev.
        This will also set doc.content to None.

        :param doc: A document to be deleted.
        :type doc: leap.soledad.common.document.Document
        :return: A deferred.
        :rtype: twisted.internet.defer.Deferred
        """
        soledad_assert(doc is not None, "delete_doc doesn't accept None.")
        return self._defer("delete_doc", doc)

    def get_doc(self, doc_id, include_deleted=False):
        """
        Get the JSON string for the given document.

        :param doc_id: The unique document identifier
        :type doc_id: str
        :param include_deleted: If set to True, deleted documents will be
            returned with empty content. Otherwise asking for a deleted
            document will return None.
        :type include_deleted: bool
        :return: A deferred whose callback will be invoked with a document
            object.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer(
            "get_doc", doc_id, include_deleted=include_deleted)

    def get_docs(
            self, doc_ids, check_for_conflicts=True, include_deleted=False):
        """
        Get the JSON content for many documents.

        :param doc_ids: A list of document identifiers.
        :type doc_ids: list
        :param check_for_conflicts: If set to False, then the conflict check
            will be skipped, and 'None' will be returned instead of True/False.
        :type check_for_conflicts: bool
        :param include_deleted: If set to True, deleted documents will be
            returned with empty content. Otherwise deleted documents will not
            be included in the results.
        :type include_deleted: bool
        :return: A deferred whose callback will be invoked with an iterable
            giving the document object for each document id in matching
            doc_ids order.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer(
            "get_docs", doc_ids, check_for_conflicts=check_for_conflicts,
            include_deleted=include_deleted)

    def get_all_docs(self, include_deleted=False):
        """
        Get the JSON content for all documents in the database.

        :param include_deleted: If set to True, deleted documents will be
            returned with empty content. Otherwise deleted documents will not
            be included in the results.
        :type include_deleted: bool

        :return: A deferred which, when fired, will pass the a tuple
            containing (generation, [Document]) to the callback, with the
            current generation of the database, followed by a list of all the
            documents in the database.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_all_docs", include_deleted)

    @defer.inlineCallbacks
    def create_doc(self, content, doc_id=None):
        """
        Create a new document.

        You can optionally specify the document identifier, but the document
        must not already exist. See 'put_doc' if you want to override an
        existing document.
        If the database specifies a maximum document size and the document
        exceeds it, create will fail and raise a DocumentTooBig exception.

        :param content: A Python dictionary.
        :type content: dict
        :param doc_id: An optional identifier specifying the document id.
        :type doc_id: str
        :return: A deferred whose callback will be invoked with a document.
        :rtype: twisted.internet.defer.Deferred
        """
        # TODO we probably should pass an optional "encoding" parameter to
        # create_doc (and probably to put_doc too). There are cases (mail
        # payloads for example) in which we already have the encoding in the
        # headers, so we don't need to guess it.
        doc = yield self._defer("create_doc", content, doc_id=doc_id)
        doc.set_store(self)
        defer.returnValue(doc)

    def create_doc_from_json(self, json, doc_id=None):
        """
        Create a new document.

        You can optionally specify the document identifier, but the document
        must not already exist. See 'put_doc' if you want to override an
        existing document.
        If the database specifies a maximum document size and the document
        exceeds it, create will fail and raise a DocumentTooBig exception.

        :param json: The JSON document string
        :type json: dict
        :param doc_id: An optional identifier specifying the document id.
        :type doc_id: str
        :return: A deferred whose callback will be invoked with a document.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("create_doc_from_json", json, doc_id=doc_id)

    def create_index(self, index_name, *index_expressions):
        """
        Create a named index, which can then be queried for future lookups.

        Creating an index which already exists is not an error, and is cheap.
        Creating an index which does not match the index_expressions of the
        existing index is an error.
        Creating an index will block until the expressions have been evaluated
        and the index generated.

        :param index_name: A unique name which can be used as a key prefix
        :type index_name: str
        :param index_expressions: index expressions defining the index
            information.

            Examples:

            "fieldname", or "fieldname.subfieldname" to index alphabetically
            sorted on the contents of a field.

            "number(fieldname, width)", "lower(fieldname)"
        :type index_expresions: list of str
        :return: A deferred.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("create_index", index_name, *index_expressions)

    def delete_index(self, index_name):
        """
        Remove a named index.

        :param index_name: The name of the index we are removing
        :type index_name: str
        :return: A deferred.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("delete_index", index_name)

    def list_indexes(self):
        """
        List the definitions of all known indexes.

        :return: A deferred whose callback will be invoked with a list of
            [('index-name', ['field', 'field2'])] definitions.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("list_indexes")

    def get_from_index(self, index_name, *key_values):
        """
        Return documents that match the keys supplied.

        You must supply exactly the same number of values as have been defined
        in the index. It is possible to do a prefix match by using '*' to
        indicate a wildcard match. You can only supply '*' to trailing entries,
        (eg 'val', '*', '*' is allowed, but '*', 'val', 'val' is not.)
        It is also possible to append a '*' to the last supplied value (eg
        'val*', '*', '*' or 'val', 'val*', '*', but not 'val*', 'val', '*')

        :param index_name: The index to query
        :type index_name: str
        :param key_values: values to match. eg, if you have
            an index with 3 fields then you would have:
            get_from_index(index_name, val1, val2, val3)
        :type key_values: list
        :return: A deferred whose callback will be invoked with a list of
            [Document].
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_from_index", index_name, *key_values)

    def get_count_from_index(self, index_name, *key_values):
        """
        Return the count for a given combination of index_name
        and key values.

        Extension method made from similar methods in u1db version 13.09

        :param index_name: The index to query
        :type index_name: str
        :param key_values: values to match. eg, if you have
                           an index with 3 fields then you would have:
                           get_from_index(index_name, val1, val2, val3)
        :type key_values: tuple
        :return: A deferred whose callback will be invoked with the count.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_count_from_index", index_name, *key_values)

    def get_range_from_index(self, index_name, start_value, end_value):
        """
        Return documents that fall within the specified range.

        Both ends of the range are inclusive. For both start_value and
        end_value, one must supply exactly the same number of values as have
        been defined in the index, or pass None. In case of a single column
        index, a string is accepted as an alternative for a tuple with a single
        value. It is possible to do a prefix match by using '*' to indicate
        a wildcard match. You can only supply '*' to trailing entries, (eg
        'val', '*', '*' is allowed, but '*', 'val', 'val' is not.) It is also
        possible to append a '*' to the last supplied value (eg 'val*', '*',
        '*' or 'val', 'val*', '*', but not 'val*', 'val', '*')

        :param index_name: The index to query
        :type index_name: str
        :param start_values: tuples of values that define the lower bound of
            the range. eg, if you have an index with 3 fields then you would
            have: (val1, val2, val3)
        :type start_values: tuple
        :param end_values: tuples of values that define the upper bound of the
            range. eg, if you have an index with 3 fields then you would have:
            (val1, val2, val3)
        :type end_values: tuple
        :return: A deferred whose callback will be invoked with a list of
            [Document].
        :rtype: twisted.internet.defer.Deferred
        """

        return self._defer(
            "get_range_from_index", index_name, start_value, end_value)

    def get_index_keys(self, index_name):
        """
        Return all keys under which documents are indexed in this index.

        :param index_name: The index to query
        :type index_name: str
        :return: A deferred whose callback will be invoked with a list of
            tuples of indexed keys.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_index_keys", index_name)

    def get_doc_conflicts(self, doc_id):
        """
        Get the list of conflicts for the given document.

        The order of the conflicts is such that the first entry is the value
        that would be returned by "get_doc".

        :param doc_id: The unique document identifier
        :type doc_id: str
        :return: A deferred whose callback will be invoked with a list of the
            Document entries that are conflicted.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("get_doc_conflicts", doc_id)

    def resolve_doc(self, doc, conflicted_doc_revs):
        """
        Mark a document as no longer conflicted.

        We take the list of revisions that the client knows about that it is
        superseding. This may be a different list from the actual current
        conflicts, in which case only those are removed as conflicted.  This
        may fail if the conflict list is significantly different from the
        supplied information. (sync could have happened in the background from
        the time you GET_DOC_CONFLICTS until the point where you RESOLVE)

        :param doc: A Document with the new content to be inserted.
        :type doc: Document
        :param conflicted_doc_revs: A list of revisions that the new content
            supersedes.
        :type conflicted_doc_revs: list(str)
        :return: A deferred.
        :rtype: twisted.internet.defer.Deferred
        """
        return self._defer("resolve_doc", doc, conflicted_doc_revs)

    @property
    def local_db_path(self):
        return self._local_db_path

    @property
    def userid(self):
        return self.uuid

    #
    # ISyncableStorage
    #

    def sync(self):
        """
        Synchronize documents with the server replica.

        This method uses a lock to prevent multiple concurrent sync processes
        over the same local db file.

        :return: A deferred lock that will run the actual sync process when
                 the lock is acquired, and which will fire with with the local
                 generation before the synchronization was performed.
        :rtype: twisted.internet.defer.Deferred
        """
        # maybe bypass sync
        # TODO: That's because bitmask may not provide us a token, but
        # this should be handled on the caller side. Here, calling us without
        # a token is a real error.
        if not self.token:
            generation = self._dbsyncer.get_generation()
            return defer.succeed(generation)

        d = self.sync_lock.run(
            self._sync)
        return d

    def _sync(self):
        """
        Synchronize documents with the server replica.

        :return: A deferred whose callback will be invoked with the local
            generation before the synchronization was performed.
        :rtype: twisted.internet.defer.Deferred
        """
        sync_url = urlparse.urljoin(self.server_url, 'user-%s' % self.uuid)
        if not self._dbsyncer:
            return
        creds = {'token': {'uuid': self.uuid, 'token': self.token}}
        d = self._dbsyncer.sync(sync_url, creds=creds)

        def _sync_callback(local_gen):
            self._last_received_docs = docs = self._dbsyncer.received_docs

            # Post-Sync Hooks
            if docs:
                iface = soledad_interfaces.ISoledadPostSyncPlugin
                suitable_plugins = collect_plugins(iface)
                for plugin in suitable_plugins:
                    watched = plugin.watched_doc_types
                    r = [filter(
                        lambda s: s.startswith(preffix),
                        docs) for preffix in watched]
                    filtered = list(chain(*r))
                    plugin.process_received_docs(filtered)

            return local_gen

        def _sync_errback(failure):
            s = StringIO()
            failure.printDetailedTraceback(file=s)
            msg = "got exception when syncing!\n" + s.getvalue()
            logger.error(msg)
            return failure

        def _emit_done_data_sync(passthrough):
            user_data = {'uuid': self.uuid, 'userid': self.userid}
            soledad_events.emit_async(
                soledad_events.SOLEDAD_DONE_DATA_SYNC, user_data)
            return passthrough

        d.addCallbacks(_sync_callback, _sync_errback)
        d.addCallback(_emit_done_data_sync)
        return d

    @property
    def sync_lock(self):
        """
        Class based lock to prevent concurrent syncs using the same local db
        file.

        :return: A shared lock based on this instance's db file path.
        :rtype: DeferredLock
        """
        return self._sync_lock[self._local_db_path]

    @property
    def syncing(self):
        """
        Return wether Soledad is currently synchronizing with the server.

        :return: Wether Soledad is currently synchronizing with the server.
        :rtype: bool
        """
        return self.sync_lock.locked

    #
    # ISecretsStorage
    #

    @property
    def secrets(self):
        """
        Return the secrets object.

        :return: The secrets object.
        :rtype: Secrets
        """
        return self._secrets

    def change_passphrase(self, new_passphrase):
        """
        Change the passphrase that encrypts the storage secret.

        :param new_passphrase: The new passphrase.
        :type new_passphrase: unicode

        :raise NoStorageSecret: Raised if there's no storage secret available.
        """
        self.passphrase = new_passphrase
        self._secrets.store_secrets()

    #
    # Raw SQLCIPHER Queries
    #

    def raw_sqlcipher_query(self, *args, **kw):
        """
        Run a raw sqlcipher query in the local database, and return a deferred
        that will be fired with the result.
        """
        return self._dbpool.runQuery(*args, **kw)

    def raw_sqlcipher_operation(self, *args, **kw):
        """
        Run a raw sqlcipher operation in the local database, and return a
        deferred that will be fired with None.
        """
        return self._dbpool.runOperation(*args, **kw)

    #
    # Service authentication
    #

    @defer.inlineCallbacks
    def get_or_create_service_token(self, service):
        """
        Return the stored token for a given service, or generates and stores a
        random one if it does not exist.

        These tokens can be used to authenticate services.
        """
        # FIXME this could use the local sqlcipher database, to avoid
        # problems with different replicas creating different tokens.

        yield self.create_index('by-servicetoken', 'type', 'service')
        docs = yield self._get_token_for_service(service)
        if docs:
            doc = docs[0]
            defer.returnValue(doc.content['token'])
        else:
            token = str(uuid.uuid4()).replace('-', '')[-24:]
            yield self._set_token_for_service(service, token)
            defer.returnValue(token)

    def _get_token_for_service(self, service):
        return self.get_from_index('by-servicetoken', 'servicetoken', service)

    def _set_token_for_service(self, service, token):
        doc = {'type': 'servicetoken', 'service': service, 'token': token}
        return self.create_doc(doc)

    def create_recovery_code(self):
        return self._recovery_code.generate()
Ejemplo n.º 36
0
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Run bitmask daemon.
"""
from os.path import join, abspath, dirname
import sys

from twisted.scripts.twistd import run

from leap.bitmask import core
from leap.bitmask.core import flags
from leap.bitmask.core.logs import getLogPath
from leap.common.config import get_path_prefix

pid = abspath(join(get_path_prefix(), 'leap', 'bitmaskd.pid'))

STANDALONE = getattr(sys, 'frozen', False)


def here(module=None):
    if STANDALONE:
        # we are running in a |PyInstaller| bundle
        return sys._MEIPASS
    else:
        if module:
            return dirname(module.__file__)
        else:
            return dirname(__file__)

Ejemplo n.º 37
0
import base64
import os
import re
import scrypt

from leap.common.config import get_path_prefix
from leap.bitmask.system import IS_WIN

if IS_WIN:

    import socket
    from cryptography.fernet import Fernet
    from cryptography.hazmat.backends import default_backend
    crypto_backend = default_backend()

MAP_PATH = os.path.join(get_path_prefix(), 'leap', 'uuids')


class UserMap(object):
    """
    A persistent mapping between user-ids and uuids.
    """

    # TODO Add padding to the encrypted string

    def __init__(self):
        self._d = {}
        self._lines = set([])
        if os.path.isfile(MAP_PATH):
            self.load()