| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
# Copyright (c) Twisted Matrix Laboratories. |
| 4 |
# See LICENSE for details. |
| 5 |
|
| 6 |
""" |
| 7 |
Simple example of a db checker: define a L{ICredentialsChecker} implementation |
| 8 |
that deals with a database backend to authenticate a user. |
| 9 |
""" |
| 10 |
|
| 11 |
from zope.interface import implementer |
| 12 |
|
| 13 |
from twisted.cred import error |
| 14 |
from twisted.cred.checkers import ICredentialsChecker |
| 15 |
from twisted.cred.credentials import IUsernameHashedPassword, IUsernamePassword |
| 16 |
from twisted.internet.defer import Deferred |
| 17 |
|
| 18 |
|
| 19 |
@implementer(ICredentialsChecker) |
| 20 |
class DBCredentialsChecker: |
| 21 |
""" |
| 22 |
This class checks the credentials of incoming connections |
| 23 |
against a user table in a database. |
| 24 |
""" |
| 25 |
|
| 26 |
def __init__( |
| 27 |
self, |
| 28 |
runQuery, |
| 29 |
query="SELECT username, password FROM user WHERE username = %s", |
| 30 |
customCheckFunc=None, |
| 31 |
caseSensitivePasswords=True, |
| 32 |
): |
| 33 |
""" |
| 34 |
@param runQuery: This will be called to get the info from the db. |
| 35 |
Generally you'd want to create a |
| 36 |
L{twisted.enterprice.adbapi.ConnectionPool} and pass it's runQuery |
| 37 |
method here. Otherwise pass a function with the same prototype. |
| 38 |
@type runQuery: C{callable} |
| 39 |
|
| 40 |
@type query: query used to authenticate user. |
| 41 |
@param query: C{str} |
| 42 |
|
| 43 |
@param customCheckFunc: Use this if the passwords in the db are stored |
| 44 |
as hashes. We'll just call this, so you can do the checking |
| 45 |
yourself. It takes the following params: |
| 46 |
(username, suppliedPass, dbPass) and must return a boolean. |
| 47 |
@type customCheckFunc: C{callable} |
| 48 |
|
| 49 |
@param caseSensitivePasswords: If true requires that every letter in |
| 50 |
C{credentials.password} is exactly the same case as the it's |
| 51 |
counterpart letter in the database. |
| 52 |
This is only relevant if C{customCheckFunc} is not used. |
| 53 |
@type caseSensitivePasswords: C{bool} |
| 54 |
""" |
| 55 |
self.runQuery = runQuery |
| 56 |
self.caseSensitivePasswords = caseSensitivePasswords |
| 57 |
self.customCheckFunc = customCheckFunc |
| 58 |
# We can't support hashed password credentials if we only have a hash |
| 59 |
# in the DB |
| 60 |
if customCheckFunc: |
| 61 |
self.credentialInterfaces = (IUsernamePassword,) |
| 62 |
else: |
| 63 |
self.credentialInterfaces = ( |
| 64 |
IUsernamePassword, |
| 65 |
IUsernameHashedPassword, |
| 66 |
) |
| 67 |
|
| 68 |
self.sql = query |
| 69 |
|
| 70 |
def requestAvatarId(self, credentials): |
| 71 |
""" |
| 72 |
Authenticates the kiosk against the database. |
| 73 |
""" |
| 74 |
# Check that the credentials instance implements at least one of our |
| 75 |
# interfaces |
| 76 |
for interface in self.credentialInterfaces: |
| 77 |
if interface.providedBy(credentials): |
| 78 |
break |
| 79 |
else: |
| 80 |
raise error.UnhandledCredentials() |
| 81 |
# Ask the database for the username and password |
| 82 |
dbDeferred = self.runQuery(self.sql, (credentials.username,)) |
| 83 |
# Setup our deferred result |
| 84 |
deferred = Deferred() |
| 85 |
dbDeferred.addCallbacks( |
| 86 |
self._cbAuthenticate, |
| 87 |
self._ebAuthenticate, |
| 88 |
callbackArgs=(credentials, deferred), |
| 89 |
errbackArgs=(credentials, deferred), |
| 90 |
) |
| 91 |
return deferred |
| 92 |
|
| 93 |
def _cbAuthenticate(self, result, credentials, deferred): |
| 94 |
""" |
| 95 |
Checks to see if authentication was good. Called once the info has |
| 96 |
been retrieved from the DB. |
| 97 |
""" |
| 98 |
if len(result) == 0: |
| 99 |
# Username not found in db |
| 100 |
deferred.errback(error.UnauthorizedLogin("Username unknown")) |
| 101 |
else: |
| 102 |
username, password = result[0] |
| 103 |
if self.customCheckFunc: |
| 104 |
# Let the owner do the checking |
| 105 |
if self.customCheckFunc(username, credentials.password, password): |
| 106 |
deferred.callback(credentials.username) |
| 107 |
else: |
| 108 |
deferred.errback(error.UnauthorizedLogin("Password mismatch")) |
| 109 |
else: |
| 110 |
# It's up to us or the credentials object to do the checking |
| 111 |
# now |
| 112 |
if IUsernameHashedPassword.providedBy(credentials): |
| 113 |
# Let the hashed password checker do the checking |
| 114 |
if credentials.checkPassword(password): |
| 115 |
deferred.callback(credentials.username) |
| 116 |
else: |
| 117 |
deferred.errback(error.UnauthorizedLogin("Password mismatch")) |
| 118 |
elif IUsernamePassword.providedBy(credentials): |
| 119 |
# Compare the passwords, deciging whether or not to use |
| 120 |
# case sensitivity |
| 121 |
if self.caseSensitivePasswords: |
| 122 |
passOk = password.lower() == credentials.password.lower() |
| 123 |
else: |
| 124 |
passOk = password == credentials.password |
| 125 |
# See if they match |
| 126 |
if passOk: |
| 127 |
deferred.callback(credentials.username) |
| 128 |
else: |
| 129 |
deferred.errback(error.UnauthorizedLogin("Password mismatch")) |
| 130 |
else: |
| 131 |
# OK, we don't know how to check this |
| 132 |
deferred.errback(error.UnhandledCredentials()) |
| 133 |
|
| 134 |
def _ebAuthenticate(self, message, credentials, deferred): |
| 135 |
""" |
| 136 |
The database lookup failed for some reason. |
| 137 |
""" |
| 138 |
deferred.errback(error.LoginFailed(message)) |
| 139 |
|
| 140 |
|
| 141 |
def main(): |
| 142 |
""" |
| 143 |
Run a simple echo pb server to test the checker. It defines a custom query |
| 144 |
for dealing with sqlite special quoting, but otherwise it's a |
| 145 |
straightforward use of the object. |
| 146 |
|
| 147 |
You can test it running C{pbechoclient.py}. |
| 148 |
""" |
| 149 |
import sys |
| 150 |
|
| 151 |
from twisted.python import log |
| 152 |
|
| 153 |
log.startLogging(sys.stdout) |
| 154 |
import os |
| 155 |
|
| 156 |
if os.path.isfile("testcred"): |
| 157 |
os.remove("testcred") |
| 158 |
from twisted.enterprise import adbapi |
| 159 |
|
| 160 |
pool = adbapi.ConnectionPool("pysqlite2.dbapi2", "testcred") |
| 161 |
# Create the table that will be used |
| 162 |
query1 = """CREATE TABLE user ( |
| 163 |
username string, |
| 164 |
password string |
| 165 |
)""" |
| 166 |
# Insert a test user |
| 167 |
query2 = """INSERT INTO user VALUES ('guest', 'guest')""" |
| 168 |
|
| 169 |
def cb(res): |
| 170 |
pool.runQuery(query2) |
| 171 |
|
| 172 |
pool.runQuery(query1).addCallback(cb) |
| 173 |
|
| 174 |
checker = DBCredentialsChecker( |
| 175 |
pool.runQuery, query="SELECT username, password FROM user WHERE username = ?" |
| 176 |
) |
| 177 |
import pbecho |
| 178 |
|
| 179 |
from twisted.cred.portal import Portal |
| 180 |
from twisted.spread import pb |
| 181 |
|
| 182 |
portal = Portal(pbecho.SimpleRealm()) |
| 183 |
portal.registerChecker(checker) |
| 184 |
reactor.listenTCP(pb.portno, pb.PBServerFactory(portal)) |
| 185 |
|
| 186 |
|
| 187 |
if __name__ == "__main__": |
| 188 |
from twisted.internet import reactor |
| 189 |
|
| 190 |
reactor.callWhenRunning(main) |
| 191 |
reactor.run() |