summaryrefslogtreecommitdiff
path: root/src/leap/bitmask/core/uuid_map.py
blob: e7d02a3133a9978d71b378738085881774ab5f3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# -*- coding: utf-8 -*-
# uuid_map.py
# Copyright (C) 2015,2016 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# 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/>.
"""
UUID Map: a persistent mapping between user-ids and uuids.
"""

import base64
import os
import re
import platform

import scrypt

from leap.common.config import get_path_prefix

IS_WIN = platform.system() == "Windows"

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()

    def add(self, userid, uuid, passwd):
        """
        Add a new userid-uuid mapping, and encrypt the record with the user
        password.
        """
        self._add_to_cache(userid, uuid)
        self._lines.add(_encode_uuid_map(userid, uuid, passwd))
        self.dump()

    def _add_to_cache(self, userid, uuid):
        self._d[userid] = uuid

    def load(self):
        """
        Load a mapping from a default file.
        """
        with open(MAP_PATH, 'r') as infile:
            lines = infile.readlines()
            self._lines = set(lines)

    def dump(self):
        """
        Dump the mapping to a default file.
        """
        with open(MAP_PATH, 'w') as out:
            out.write('\n'.join(self._lines))

    def lookup_uuid(self, userid, passwd=None):
        """
        Lookup the uuid for a given userid.

        If no password is given, try to lookup on cache.
        Else, try to decrypt all the records that we know about with the
        passed password.
        """
        if not passwd:
            return self._d.get(userid)

        for line in self._lines:
            guess = _decode_uuid_line(line, passwd)
            if guess:
                record_userid, uuid = guess
                if record_userid == userid:
                    self._add_to_cache(userid, uuid)
                    return uuid

    def lookup_userid(self, uuid):
        """
        Get the userid for the given uuid from cache.
        """
        rev_d = {v: k for (k, v) in self._d.items()}
        return rev_d.get(uuid)


def _encode_uuid_map(userid, uuid, passwd):
    data = 'userid:%s:uuid:%s' % (userid, uuid)

    # FIXME scrypt.encrypt is broken in windows.
    # This is a quick hack. The hostname might not be unique enough though.
    # We could use a long random hash per entry and store it in the file.
    # Other option is to use a different KDF that is supported by cryptography
    # (ie, pbkdf)

    if IS_WIN:
        key = scrypt.hash(passwd, socket.gethostname())
        key = base64.urlsafe_b64encode(key[:32])
        f = Fernet(key, backend=crypto_backend)
        encrypted = f.encrypt(data)
    else:
        encrypted = scrypt.encrypt(data, passwd, maxtime=0.05)
    return base64.urlsafe_b64encode(encrypted)


def _decode_uuid_line(line, passwd):
    decoded = base64.urlsafe_b64decode(line)
    if IS_WIN:
        key = scrypt.hash(passwd, socket.gethostname())
        key = base64.urlsafe_b64encode(key[:32])
        try:
            f = Fernet(key, backend=crypto_backend)
            maybe_decrypted = f.decrypt(key)
        except Exception:
            return None
    else:
        try:
            maybe_decrypted = scrypt.decrypt(decoded, passwd, maxtime=0.1)
        except scrypt.error:
            return None
    match = re.findall("userid\:(.+)\:uuid\:(.+)", maybe_decrypted)
    if match:
        return match[0]