auth.py 8.94 KB
Newer Older
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
#
#

# Copyright (C) 2007, 2008 Google Inc.
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

"""HTTP authentication module.

"""

import logging
import re
import base64
import binascii

from ganeti import utils
from ganeti import http

from cStringIO import StringIO

35
36
37
38
39
try:
  from hashlib import md5
except ImportError:
  from md5 import new as md5

40
41
42
43
44
45

# Digest types from RFC2617
HTTP_BASIC_AUTH = "Basic"
HTTP_DIGEST_AUTH = "Digest"

# Not exactly as described in RFC2616, section 2.2, but good enough
Guido Trotter's avatar
Guido Trotter committed
46
_NOQUOTE = re.compile(r"^[-_a-z0-9]+$", re.I)
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


def _FormatAuthHeader(scheme, params):
  """Formats WWW-Authentication header value as per RFC2617, section 1.2

  @type scheme: str
  @param scheme: Authentication scheme
  @type params: dict
  @param params: Additional parameters
  @rtype: str
  @return: Formatted header value

  """
  buf = StringIO()

  buf.write(scheme)

  for name, value in params.iteritems():
    buf.write(" ")
    buf.write(name)
    buf.write("=")
    if _NOQUOTE.match(value):
      buf.write(value)
    else:
      buf.write("\"")
      # TODO: Better quoting
      buf.write(value.replace("\"", "\\\""))
      buf.write("\"")

  return buf.getvalue()


class HttpServerRequestAuthentication(object):
  # Default authentication realm
  AUTH_REALM = None

83
84
85
86
  # Schemes for passwords
  _CLEARTEXT_SCHEME = "{CLEARTEXT}"
  _HA1_SCHEME = "{HA1}"

87
88
89
  def GetAuthRealm(self, req):
    """Returns the authentication realm for a request.

Michael Hanselmann's avatar
Michael Hanselmann committed
90
    MAY be overridden by a subclass, which then can return different realms for
91
92
93
94
95
96
97
98
99
    different paths. Returning "None" means no authentication is needed for a
    request.

    @type req: L{http.server._HttpServerRequest}
    @param req: HTTP request context
    @rtype: str or None
    @return: Authentication realm

    """
100
101
102
    # today we don't have per-request filtering, but we might want to
    # add it in the future
    # pylint: disable-msg=W0613
103
104
105
106
107
108
109
110
111
112
113
    return self.AUTH_REALM

  def PreHandleRequest(self, req):
    """Called before a request is handled.

    @type req: L{http.server._HttpServerRequest}
    @param req: HTTP request context

    """
    realm = self.GetAuthRealm(req)

114
115
    # Authentication not required, and no credentials given?
    if realm is None and http.HTTP_AUTHORIZATION not in req.request_headers:
116
117
      return

118
119
120
121
    if realm is None: # in case we don't require auth but someone
                      # passed the crendentials anyway
      realm = "Unspecified"

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    # Check "Authorization" header
    if self._CheckAuthorization(req):
      # User successfully authenticated
      return

    # Send 401 Unauthorized response
    params = {
      "realm": realm,
      }

    # TODO: Support for Digest authentication (RFC2617, section 3).
    # TODO: Support for more than one WWW-Authenticate header with the same
    # response (RFC2617, section 4.6).
    headers = {
      http.HTTP_WWW_AUTHENTICATE: _FormatAuthHeader(HTTP_BASIC_AUTH, params),
      }

    raise http.HttpUnauthorized(headers=headers)

  def _CheckAuthorization(self, req):
Iustin Pop's avatar
Iustin Pop committed
142
    """Checks 'Authorization' header sent by client.
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

    @type req: L{http.server._HttpServerRequest}
    @param req: HTTP request context
    @rtype: bool
    @return: Whether user is allowed to execute request

    """
    credentials = req.request_headers.get(http.HTTP_AUTHORIZATION, None)
    if not credentials:
      return False

    # Extract scheme
    parts = credentials.strip().split(None, 2)
    if len(parts) < 1:
      # Missing scheme
      return False

    # RFC2617, section 1.2: "[...] It uses an extensible, case-insensitive
    # token to identify the authentication scheme [...]"
    scheme = parts[0].lower()

    if scheme == HTTP_BASIC_AUTH.lower():
      # Do basic authentication
      if len(parts) < 2:
        raise http.HttpBadRequest(message=("Basic authentication requires"
                                           " credentials"))
      return self._CheckBasicAuthorization(req, parts[1])

    elif scheme == HTTP_DIGEST_AUTH.lower():
      # TODO: Implement digest authentication
      # RFC2617, section 3.3: "Note that the HTTP server does not actually need
      # to know the user's cleartext password. As long as H(A1) is available to
      # the server, the validity of an Authorization header may be verified."
      pass

    # Unsupported authentication scheme
    return False

Iustin Pop's avatar
Iustin Pop committed
181
  def _CheckBasicAuthorization(self, req, in_data):
182
183
184
185
    """Checks credentials sent for basic authentication.

    @type req: L{http.server._HttpServerRequest}
    @param req: HTTP request context
Iustin Pop's avatar
Iustin Pop committed
186
187
    @type in_data: str
    @param in_data: Username and password encoded as Base64
188
189
190
191
192
    @rtype: bool
    @return: Whether user is allowed to execute request

    """
    try:
Iustin Pop's avatar
Iustin Pop committed
193
      creds = base64.b64decode(in_data.encode('ascii')).decode('ascii')
194
195
196
197
198
199
200
201
202
203
204
    except (TypeError, binascii.Error, UnicodeError):
      logging.exception("Error when decoding Basic authentication credentials")
      return False

    if ":" not in creds:
      return False

    (user, password) = creds.split(":", 1)

    return self.Authenticate(req, user, password)

205
  def Authenticate(self, req, user, password):
206
207
    """Checks the password for a user.

Michael Hanselmann's avatar
Michael Hanselmann committed
208
    This function MUST be overridden by a subclass.
209
210
211

    """
    raise NotImplementedError()
212

213
214
215
  def VerifyBasicAuthPassword(self, req, username, password, expected):
    """Checks the password for basic authentication.

Michael Hanselmann's avatar
Michael Hanselmann committed
216
217
    As long as they don't start with an opening brace ("E{lb}"), old passwords
    are supported. A new scheme uses H(A1) from RFC2617, where H is MD5 and A1
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
    consists of the username, the authentication realm and the actual password.

    @type req: L{http.server._HttpServerRequest}
    @param req: HTTP request context
    @type username: string
    @param username: Username from HTTP headers
    @type password: string
    @param password: Password from HTTP headers
    @type expected: string
    @param expected: Expected password with optional scheme prefix (e.g. from
                     users file)

    """
    # Backwards compatibility for old-style passwords without a scheme
    if not expected.startswith("{"):
      expected = self._CLEARTEXT_SCHEME + expected

    # Check again, just to be sure
    if not expected.startswith("{"):
      raise AssertionError("Invalid scheme")

    scheme_end_idx = expected.find("}", 1)

    # Ensure scheme has a length of at least one character
    if scheme_end_idx <= 1:
      logging.warning("Invalid scheme in password for user '%s'", username)
      return False

    scheme = expected[:scheme_end_idx + 1].upper()
    expected_password = expected[scheme_end_idx + 1:]

    # Good old plain text password
    if scheme == self._CLEARTEXT_SCHEME:
      return password == expected_password

    # H(A1) as described in RFC2617
    if scheme == self._HA1_SCHEME:
      realm = self.GetAuthRealm(req)
      if not realm:
        # There can not be a valid password for this case
        return False

      expha1 = md5()
      expha1.update("%s:%s:%s" % (username, realm, password))

      return (expected_password.lower() == expha1.hexdigest().lower())

    logging.warning("Unknown scheme '%s' in password for user '%s'",
                    scheme, username)

    return False

270
271
272
273
274
275
276
277
278
279
280
281
282
283

class PasswordFileUser(object):
  """Data structure for users from password file.

  """
  def __init__(self, name, password, options):
    self.name = name
    self.password = password
    self.options = options


def ReadPasswordFile(file_name):
  """Reads a password file.

Iustin Pop's avatar
Iustin Pop committed
284
  Lines in the password file are of the following format::
285

Iustin Pop's avatar
Iustin Pop committed
286
      <username> <password> [options]
287
288

  Fields are separated by whitespace. Username and password are mandatory,
Iustin Pop's avatar
Iustin Pop committed
289
290
  options are optional and separated by comma (','). Empty lines and comments
  ('#') are ignored.
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
318
319
320
321
322
323

  @type file_name: str
  @param file_name: Path to password file
  @rtype: dict
  @return: Dictionary containing L{PasswordFileUser} instances

  """
  users = {}

  for line in utils.ReadFile(file_name).splitlines():
    line = line.strip()

    # Ignore empty lines and comments
    if not line or line.startswith("#"):
      continue

    parts = line.split(None, 2)
    if len(parts) < 2:
      # Invalid line
      continue

    name = parts[0]
    password = parts[1]

    # Extract options
    options = []
    if len(parts) >= 3:
      for part in parts[2].split(","):
        options.append(part.strip())

    users[name] = PasswordFileUser(name, password, options)

  return users