| 1 |
""" |
| 2 |
Code for checking against our user db. |
| 3 |
|
| 4 |
Todo: evaluate using twisted.cred for this; but then I guess all this needs |
| 5 |
a thorough shakeup looking towards OAuth2 anyway. |
| 6 |
|
| 7 |
We store the passwords hashed with scrypt with 16 bytes of salt. |
| 8 |
Of course, since we only support http basic auth at this point, this |
| 9 |
level of security really only makes sense if credential transmission |
| 10 |
is restricted to https; and with current DaCHS, this means disabling |
| 11 |
http altogether. |
| 12 |
""" |
| 13 |
|
| 14 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 15 |
#c |
| 16 |
#c This program is free software, covered by the GNU GPL. See the |
| 17 |
#c COPYING file in the source distribution. |
| 18 |
|
| 19 |
|
| 20 |
import base64 |
| 21 |
import functools |
| 22 |
import hashlib |
| 23 |
import os |
| 24 |
|
| 25 |
from gavo import base |
| 26 |
from gavo import svcs |
| 27 |
|
| 28 |
from gavo.utils import AllEncompassingSet |
| 29 |
|
| 30 |
# we're limiting the password length to thwart DoS with endless passwords. |
| 31 |
# (and because we don't think overlong passwords make any sense at all) |
| 32 |
MAX_PASSWORD_LENGTH = 64 |
| 33 |
|
| 34 |
# this should only be changed for unit tests |
| 35 |
adminProfile = "admin" |
| 36 |
|
| 37 |
|
| 38 |
# We fix the scrypt parameters to what looks reasonable in 2020. |
| 39 |
# If the default arguments are ever changed, use a different hash prefix. |
| 40 |
scryptN4 = functools.partial(hashlib.scrypt, n=4, r=8, p=1) |
| 41 |
|
| 42 |
|
| 43 |
def hashPassword(pw): |
| 44 |
"""returns pw hashed and encoded with the salt. |
| 45 |
|
| 46 |
Our storage format is: "scrypt:"+b64encode(<16 bytes of salt><hash> |
| 47 |
""" |
| 48 |
if len(pw)>MAX_PASSWORD_LENGTH: |
| 49 |
raise base.ReportableError("Passwords in DaCHS must be shorter than" |
| 50 |
" %d characters") |
| 51 |
|
| 52 |
salt = os.urandom(16) |
| 53 |
payload = pw.encode("utf-8") |
| 54 |
hash = scryptN4(payload, salt=salt) |
| 55 |
return "scrypt:"+base64.b64encode(salt+hash).decode("ascii") |
| 56 |
|
| 57 |
|
| 58 |
def hashMatches(pwIn, storedHash): |
| 59 |
"""returns true if pwIn matches the encoded hash value computed with |
| 60 |
hashPassword. |
| 61 |
""" |
| 62 |
if len(pwIn)>MAX_PASSWORD_LENGTH: |
| 63 |
raise svcs.ForbiddenURI("You passed in an overlong password." |
| 64 |
" The server will not even look at it.") |
| 65 |
if not storedHash.startswith("scrypt:"): |
| 66 |
raise ValueError(f"Bad hash serialisation: '{storedHash}'") |
| 67 |
|
| 68 |
saltAndHash = base64.b64decode(storedHash[7:]) |
| 69 |
salt, hash = saltAndHash[:16], saltAndHash[16:] |
| 70 |
return hash==scryptN4(pwIn.encode("utf-8"), salt=salt) |
| 71 |
|
| 72 |
|
| 73 |
@functools.lru_cache(None) |
| 74 |
def getHashedAdminPassword(): |
| 75 |
password = base.getConfig("web", "adminpasswd") |
| 76 |
if password.startswith("scrypt:"): |
| 77 |
return password |
| 78 |
else: |
| 79 |
return hashPassword(password) |
| 80 |
|
| 81 |
|
| 82 |
def isAdmin(username, password): |
| 83 |
"""returns True if username and password match what's configured |
| 84 |
in gavorc. |
| 85 |
""" |
| 86 |
if (username=='gavoadmin' |
| 87 |
and password |
| 88 |
and hashMatches(password, getHashedAdminPassword())): |
| 89 |
return True |
| 90 |
|
| 91 |
return False |
| 92 |
|
| 93 |
|
| 94 |
def getGroupsForAuthUser(username): |
| 95 |
"""returns the groups username is in. |
| 96 |
""" |
| 97 |
with base.getAdminConn() as conn: |
| 98 |
return set(r[0] for r in |
| 99 |
conn.query( |
| 100 |
"SELECT groupname" |
| 101 |
" FROM dc.groups" |
| 102 |
" WHERE username=%(username)s", locals())) |
| 103 |
|
| 104 |
|
| 105 |
def getGroupsForUser(username, password): |
| 106 |
"""returns a set of all groups user username belongs to. |
| 107 |
|
| 108 |
If username and password don't match, you'll get an empty set. |
| 109 |
""" |
| 110 |
# see below on this sore |
| 111 |
if isinstance(username, bytes): |
| 112 |
username = username.decode("utf-8") |
| 113 |
if isinstance(password, bytes): |
| 114 |
password = password.decode("utf-8") |
| 115 |
|
| 116 |
if username is None: |
| 117 |
return set() |
| 118 |
if isAdmin(username, password): |
| 119 |
return AllEncompassingSet() |
| 120 |
query = ("SELECT groupname, password" |
| 121 |
" FROM dc.groups" |
| 122 |
" NATURAL JOIN dc.users" |
| 123 |
" WHERE username=%(username)s") |
| 124 |
|
| 125 |
res = set() |
| 126 |
storedHash = None |
| 127 |
with base.getAdminConn() as conn: |
| 128 |
for row in conn.query(query, locals()): |
| 129 |
storedHash = row[1] |
| 130 |
res.add(row[0]) |
| 131 |
|
| 132 |
# we only need to check the password once because user is primary in |
| 133 |
# dc.users. |
| 134 |
if storedHash and hashMatches(password, storedHash): |
| 135 |
return res |
| 136 |
else: |
| 137 |
return set() |
| 138 |
|
| 139 |
|
| 140 |
def hasCredentials(user, password, reqGroup): |
| 141 |
"""returns true if user and password match the db entry and the user |
| 142 |
is in the reqGroup. |
| 143 |
|
| 144 |
If reqGroup is None, true will be returned if the user/password pair |
| 145 |
is in the user table. |
| 146 |
""" |
| 147 |
# sometimes my request.getUser returns an empty string (it should be |
| 148 |
# bytes, I guess). I won't hunt this down and just work around it |
| 149 |
if isinstance(user, bytes): |
| 150 |
user = user.decode("utf-8") |
| 151 |
if isinstance(password, bytes): |
| 152 |
password = password.decode("utf-8") |
| 153 |
if isAdmin(user, password): |
| 154 |
return True |
| 155 |
|
| 156 |
with base.getAdminConn() as conn: |
| 157 |
dbRes = list(conn.query("select password from dc.users where" |
| 158 |
" username=%(user)s", {"user": user})) |
| 159 |
|
| 160 |
if not dbRes or not dbRes[0]: |
| 161 |
return False |
| 162 |
storedForm = dbRes[0][0] |
| 163 |
if not hashMatches(password, storedForm): |
| 164 |
return False |
| 165 |
|
| 166 |
if reqGroup: |
| 167 |
dbRes = list(conn.query("select groupname from dc.groups where" |
| 168 |
" username=%(user)s and groupname=%(group)s", |
| 169 |
{"user": user, "group": reqGroup,})) |
| 170 |
return not not dbRes |
| 171 |
else: |
| 172 |
return True |
| 173 |
|
| 174 |
|
| 175 |
def addUser(conn, username, password, remarks): |
| 176 |
"""Adds a user to the users table. |
| 177 |
|
| 178 |
This will always also create a like-named group. It will raise an |
| 179 |
IntegrityError if the user already exists. |
| 180 |
|
| 181 |
This will commit conn in order to catch integrity problems early. |
| 182 |
""" |
| 183 |
storedForm = hashPassword(password) |
| 184 |
conn.execute("INSERT INTO dc.users (username, password, remarks)" |
| 185 |
" VALUES (%(username)s, %(storedForm)s, %(remarks)s)", locals()) |
| 186 |
conn.commit() |
| 187 |
conn.execute("INSERT INTO dc.groups (username, groupname)" |
| 188 |
" VALUES (%(username)s, %(username)s)", locals()) |
| 189 |
conn.commit() |
| 190 |
|
| 191 |
|
| 192 |
def changeUser(conn, username, password, remarks=None): |
| 193 |
"""Changes a user's password and remarks. |
| 194 |
|
| 195 |
This will raise an error if no such user exists. |
| 196 |
""" |
| 197 |
storedForm = hashPassword(password) |
| 198 |
with conn.cursor() as c: |
| 199 |
if remarks is None: |
| 200 |
c.execute("UPDATE dc.users SET password=%(storedForm)s" |
| 201 |
" WHERE username=%(username)s", locals()) |
| 202 |
else: |
| 203 |
c.execute("UPDATE dc.users SET password=%(storedForm)s," |
| 204 |
" remarks=%(remarks)s WHERE username=%(username)s", locals()) |
| 205 |
|
| 206 |
if not c.rowcount: |
| 207 |
raise base.ReportableError(f"User {username} does not exist.") |
| 208 |
|
| 209 |
|
| 210 |
def addToGroup(conn, username, groupname): |
| 211 |
"""Adds a user to a group. |
| 212 |
|
| 213 |
A group would come into being by this operation if it didn't exist before. |
| 214 |
Adding a non-existent user will raise an IntegrityError. |
| 215 |
|
| 216 |
This will commit conn in order to catch integrity problems early. |
| 217 |
""" |
| 218 |
conn.execute("INSERT INTO dc.groups (username, groupname)" |
| 219 |
" VALUES (%(username)s, %(groupname)s)", locals()) |
| 220 |
conn.commit() |
| 221 |
|
| 222 |
|
| 223 |
def removeFromGroup(conn, username, groupname): |
| 224 |
"""Removes a user from a group. |
| 225 |
|
| 226 |
It is not an error to remove a user from a group they are not in. |
| 227 |
This returns the number of rows removed in the operation (which should |
| 228 |
be 1 when the user has been a member of the group). |
| 229 |
""" |
| 230 |
c = conn.cursor() |
| 231 |
c.execute("DELETE FROM dc.groups WHERE groupname=%(groupname)s" |
| 232 |
" and username=%(username)s", locals()) |
| 233 |
return c.rowcount |
| 234 |
|
| 235 |
conn.execute("INSERT INTO dc.groups (username, groupname)" |
| 236 |
" VALUES (%(username)s, %(group)s)", locals()) |
| 237 |
|
| 238 |
|
| 239 |
def delUser(conn, username): |
| 240 |
"""Removes a user and their associated group memberships from the |
| 241 |
users and groups tables. |
| 242 |
|
| 243 |
This returns then number of database rows affected; if this is 0, nothing |
| 244 |
was removed. |
| 245 |
""" |
| 246 |
cursor = conn.cursor() |
| 247 |
cursor.execute("DELETE FROM dc.users WHERE username=%(username)s", |
| 248 |
locals()) |
| 249 |
rowsAffected = cursor.rowcount |
| 250 |
cursor.execute("DELETE FROM dc.groups WHERE username=%(username)s", |
| 251 |
locals()) |
| 252 |
rowsAffected += cursor.rowcount |
| 253 |
cursor.close() |
| 254 |
return rowsAffected |