aboutsummaryrefslogtreecommitdiffstats
path: root/deluge/core/authmanager.py
blob: 291a2066f416f6d41bc5402b1d32df2d6f0eadbf (plain) (blame)
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#
# Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
# Copyright (C) 2011 Pedro Algarvio <pedro@algarvio.me>
#
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
#

import logging
import os
import shutil

import deluge.component as component
import deluge.configmanager as configmanager
from deluge.common import (
    AUTH_LEVEL_ADMIN,
    AUTH_LEVEL_DEFAULT,
    AUTH_LEVEL_NONE,
    AUTH_LEVEL_NORMAL,
    AUTH_LEVEL_READONLY,
    create_localclient_account,
)
from deluge.error import (
    AuthenticationRequired,
    AuthManagerError,
    BadLoginError,
    InvalidHashError,
)
from deluge.security import check_password_hash, generate_password_hash

log = logging.getLogger(__name__)

AUTH_LEVELS_MAPPING = {
    'NONE': AUTH_LEVEL_NONE,
    'READONLY': AUTH_LEVEL_READONLY,
    'DEFAULT': AUTH_LEVEL_DEFAULT,
    'NORMAL': AUTH_LEVEL_NORMAL,
    'ADMIN': AUTH_LEVEL_ADMIN,
}
AUTH_LEVELS_MAPPING_REVERSE = {v: k for k, v in AUTH_LEVELS_MAPPING.items()}


class Account:
    __slots__ = ('username', 'password', 'authlevel')

    def __init__(self, username, password, authlevel):
        self.username = username
        self.password = password
        self.authlevel = authlevel

    def data(self):
        return {
            'username': self.username,
            'password': self.password,
            'authlevel': AUTH_LEVELS_MAPPING_REVERSE[self.authlevel],
            'authlevel_int': self.authlevel,
        }

    def __repr__(self):
        return '<Account username="{username}" authlevel={authlevel}>'.format(
            username=self.username,
            authlevel=self.authlevel,
        )


class AuthManager(component.Component):
    def __init__(self):
        component.Component.__init__(self, 'AuthManager', interval=10)
        self.__auth = {}
        self.__auth_modification_time = None

    def start(self):
        self.__load_auth_file()

    def stop(self):
        self.__auth = {}

    def shutdown(self):
        pass

    def update(self):
        auth_file = configmanager.get_config_dir('auth')
        # Check for auth file and create if necessary
        if not os.path.isfile(auth_file):
            log.info('Authfile not found, recreating it.')
            self.__load_auth_file()
            return

        auth_file_modification_time = os.stat(auth_file).st_mtime
        if self.__auth_modification_time != auth_file_modification_time:
            log.info('Auth file changed, reloading it!')
            self.__load_auth_file()

    def authorize(self, username: str, password: str) -> int:
        """Authorizes users based on username and password.

        Args:
            username: Username
            password: Password

        Returns:
            The auth level for this user.

        Raises:
            AuthenticationRequired: If additional details are required to authenticate.
            BadLoginError: If the username does not exist or password does not match.

        """
        if not username:
            raise AuthenticationRequired(
                'Username and Password are required.', username
            )

        if username not in self.__auth:
            # Let's try to re-load the file.. Maybe it's been updated
            self.__load_auth_file()
            if username not in self.__auth:
                raise BadLoginError('Username does not exist', username)

        stored_password = self.__auth[username].password
        if not password and stored_password:
            raise AuthenticationRequired('Password is required', username)

        if not self._verify_password(username, password, stored_password):
            raise BadLoginError('Password does not match', username)

        return self.__auth[username].authlevel

    @staticmethod
    def _verify_password(username: str, password: str, stored_password: str) -> bool:
        """Verifies a user's password either as hash or plaintext."""
        if username == 'localclient':
            # Plaintext validation to maintain localclient autologin compatibility
            return stored_password == password

        try:
            return check_password_hash(stored_password, password)
        except InvalidHashError as ex:
            log.warning(
                'Invalid hash method in password for user %s: %s'
                ' Falling back to plaintext validation.',
                username,
                ex.method,
            )
            return stored_password == password

    def has_account(self, username):
        return username in self.__auth

    def get_known_accounts(self):
        """Returns a list of known deluge usernames."""
        self.__load_auth_file()
        return [account.data() for account in self.__auth.values()]

    def create_account(self, username, password, authlevel):
        password_hash = generate_password_hash(password)

        if username in self.__auth:
            raise AuthManagerError('Username in use.', username)
        if authlevel not in AUTH_LEVELS_MAPPING:
            raise AuthManagerError('Invalid auth level: %s' % authlevel, username)
        try:
            self.__auth[username] = Account(
                username, password_hash, AUTH_LEVELS_MAPPING[authlevel]
            )
            self.write_auth_file()
            return True
        except Exception as ex:
            log.exception(ex)
            raise ex

    def update_account(self, username, password, authlevel):
        # If the username is 'localclient', we don't hash the password
        # to keep compatability with the current localclient autologin.
        password_hash = None
        if username != 'localclient':
            password_hash = generate_password_hash(password)
        if username not in self.__auth:
            raise AuthManagerError('Username not known', username)
        if authlevel not in AUTH_LEVELS_MAPPING:
            raise AuthManagerError('Invalid auth level: %s' % authlevel, username)
        try:
            self.__auth[username].username = username
            self.__auth[username].password = password_hash or password
            self.__auth[username].authlevel = AUTH_LEVELS_MAPPING[authlevel]
            self.write_auth_file()
            return True
        except Exception as ex:
            log.exception(ex)
            raise ex

    def remove_account(self, username):
        if username not in self.__auth:
            raise AuthManagerError('Username not known', username)
        elif username == component.get('RPCServer').get_session_user():
            raise AuthManagerError(
                'You cannot delete your own account while logged in!', username
            )

        del self.__auth[username]
        self.write_auth_file()
        return True

    def write_auth_file(self):
        filename = 'auth'
        filepath = os.path.join(configmanager.get_config_dir(), filename)
        filepath_bak = filepath + '.bak'
        filepath_tmp = filepath + '.tmp'

        try:
            if os.path.isfile(filepath):
                log.debug('Creating backup of %s at: %s', filename, filepath_bak)
                shutil.copy2(filepath, filepath_bak)
        except OSError as ex:
            log.error('Unable to backup %s to %s: %s', filepath, filepath_bak, ex)
        else:
            log.info('Saving the %s at: %s', filename, filepath)
            try:
                with open(filepath_tmp, 'w', encoding='utf8') as _file:
                    for account in self.__auth.values():
                        _file.write(
                            '%(username)s:%(password)s:%(authlevel_int)s\n'
                            % account.data()
                        )
                    _file.flush()
                    os.fsync(_file.fileno())
                shutil.move(filepath_tmp, filepath)
            except OSError as ex:
                log.error('Unable to save %s: %s', filename, ex)
                if os.path.isfile(filepath_bak):
                    log.info('Restoring backup of %s from: %s', filename, filepath_bak)
                    shutil.move(filepath_bak, filepath)

        self.__load_auth_file()

    def __load_auth_file(self):
        save_and_reload = False
        filename = 'auth'
        auth_file = configmanager.get_config_dir(filename)
        auth_file_bak = auth_file + '.bak'

        # Check for auth file and create if necessary
        if not os.path.isfile(auth_file):
            create_localclient_account()
            return self.__load_auth_file()

        auth_file_modification_time = os.stat(auth_file).st_mtime_ns
        if self.__auth_modification_time is None:
            self.__auth_modification_time = auth_file_modification_time
        elif self.__auth_modification_time == auth_file_modification_time:
            log.debug('Auth file unchanged, skipping re-parsing.')
            return

        file_data = []
        for _filepath in (auth_file, auth_file_bak):
            log.info('Opening %s for load: %s', filename, _filepath)
            try:
                with open(_filepath, encoding='utf8') as _file:
                    file_data = _file.readlines()
            except OSError as ex:
                log.warning('Unable to load %s: %s', _filepath, ex)
            else:
                log.info('Successfully loaded %s: %s', filename, _filepath)
                break

        # Load the auth file into a dictionary: {username: Account(...)}
        for line in file_data:
            line = line.strip()
            if line.startswith('#') or not line:
                # This line is a comment or empty
                continue
            lsplit = line.split(':')
            if len(lsplit) == 2:
                username, password = lsplit
                log.warning(
                    'Your auth entry for %s contains no auth level, '
                    'using AUTH_LEVEL_DEFAULT(%s)..',
                    username,
                    AUTH_LEVEL_DEFAULT,
                )
                if username == 'localclient':
                    authlevel = AUTH_LEVEL_ADMIN
                else:
                    authlevel = AUTH_LEVEL_DEFAULT
                # This is probably an old auth file
                save_and_reload = True
            elif len(lsplit) == 3:
                username, password, authlevel = lsplit
            else:
                log.error('Your auth file is malformed: Incorrect number of fields!')
                continue

            username = username.strip()
            password = password.strip()
            try:
                authlevel = int(authlevel)
            except ValueError:
                try:
                    authlevel = AUTH_LEVELS_MAPPING[str(authlevel)]
                except KeyError:
                    log.error(
                        'Your auth file is malformed: %r is not a valid auth level',
                        authlevel,
                    )
                    continue

            self.__auth[username] = Account(username, password, authlevel)

        if 'localclient' not in self.__auth:
            create_localclient_account(True)
            return self.__load_auth_file()

        if save_and_reload:
            log.info('Re-writing auth file (upgrade)')
            self.write_auth_file()
        self.__auth_modification_time = auth_file_modification_time