summaryrefslogtreecommitdiffstats
path: root/src/modules/rlm_python3/prepaid.py
blob: 28e548b47cbf63ca55f1445cd1f5f0adf0bd436a (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
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
#! /usr/bin/env python3
#
# Example Python module for prepaid usage using MySQL

# 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 St, Fifth Floor, Boston, MA 02110-1301, USA
#
# Copyright 2002 Miguel A.L. Paraz <mparaz@mparaz.com>
# Copyright 2002 Imperium Technology, Inc.
#
# $Id$

import radiusd
import MySQLdb

# Configuration
configDb = 'python'                     # Database name
configHost = 'localhost'                # Database host
configUser = 'python'                   # Database user and password
configPasswd = 'python'

# xxx Database

# Globals
dbHandle = None

def log(level, s):
    """Log function."""
    radiusd.radlog(level, 'prepaid.py: ' + s)

def instantiate(p):
    """Module Instantiation.  0 for success, -1 for failure.
    p is a dummy variable here."""
    global dbHandle

    try:
    	dbHandle = MySQLdb.connect(db=configDb, host=configHost,
    				   user=configUser, passwd=configPasswd)

    except MySQLdb.OperationalError as e:
    	# Report the error and return -1 for failure.
    	# xxx A more advanced module would retry the database.
    	log(radiusd.L_ERR, str(e))
    	return -1

    log(radiusd.L_INFO, 'db connection: ' + str(dbHandle))

    return 0


def authorize(authData):
    """Authorization and authentication are done in one step."""

    # Extract the data we need.
    userName = None
    userPasswd = None

    for t in authData:
    	if t[0] == 'User-Name':
    		userName = t[1]
    	elif t[0] == 'Password':
    		userPasswd = t[1]

    # Build and log the SQL statement
    # radiusd puts double quotes (") around the string representation of
    # the RADIUS packet.
    sql = 'select passwd, maxseconds from users where username = ' +  userName

    log(radiusd.L_DBG, sql)

    # Get a cursor
    # xxx Or should this be one cursor all throughout?
    try:
    	dbCursor = dbHandle.cursor()
    except MySQLdb.OperationalError as e:
    	log(radiusd.L_ERR, str(e))
    	return radiusd.RLM_MODULE_FAIL

    # Execute the SQL statement
    try:
    	dbCursor.execute(sql)
    except MySQLdb.OperationalError as e:
    	log(radiusd.L_ERR, str(e))
    	dbCursor.close()
    	return radiusd.RLM_MODULE_FAIL

    # Get the result. (passwd, maxseconds)
    result = dbCursor.fetchone()
    if not result:
    	# User not found
    	log(radiusd.L_INFO, 'user not found: ' + userName)
    	dbCursor.close()
    	return radiusd.RLM_MODULE_NOTFOUND



    # Compare passwords
    # Ignore the quotes around userPasswd.
    if result[0] != userPasswd[1:-1]:
    	log(radiusd.L_DBG, 'user password mismatch: ' + userName)
    	return radiusd.RLM_MODULE_REJECT

    maxSeconds = result[1]

    # Compute their session limit

    # Build and log the SQL statement
    sql = 'select sum(seconds) from sessions where username = ' + userName

    log(radiusd.L_DBG, sql)

    # Execute the SQL statement
    try:
    	dbCursor.execute(sql)
    except MySQLdb.OperationalError as e:
    	log(radiusd.L_ERR, str(e))
    	dbCursor.close()
    	return radiusd.RLM_MODULE_FAIL

    # Get the result. (sum,)
    result = dbCursor.fetchone()
    if (not result) or (not result[0]):
    	# No usage yet
    	secondsUsed = 0
    else:
    	secondsUsed = result[0]

    # Done with cursor
    dbCursor.close()

    # Note that MySQL returns the result of SUM() as a float.
    sessionTimeout = maxSeconds - int(secondsUsed)

    if sessionTimeout <= 0:
    	# No more time, reject outright
    	log(radiusd.L_INFO, 'user out of time: ' + userName)
    	return radiusd.RLM_MODULE_REJECT

    # Log the success
    log(radiusd.L_DBG, 'user accepted: %s, %d seconds' %
    		(userName, sessionTimeout))

    # We are adding to the RADIUS packet
    # Note that the session timeout integer must be converted to string.
    # We need to set an Auth-Type.

    return (radiusd.RLM_MODULE_UPDATED,
    	(('Session-Timeout', str(sessionTimeout)),),
    	(('Auth-Type', 'python'),))
    # If you want to use different operators
    # you can do
    # return (radiusd.RLM_MODULE_UPDATED,
    #         (
    #            ('Session-Timeout', ':=', str(sessionTimeout)),
    #            ('Some-other-option', '-=', Value'),
    #         ),
    #         (
    #            ('Auth-Type', ':=', 'python'),
    #         ),
    #        )

def authenticate(p):
    return radiusd.RLM_MODULE_OK


def preacct(p):
    return radiusd.RLM_MODULE_OK


def accounting(acctData):
    """Accounting."""
    # Extract the data we need.

    userName = None
    acctSessionTime = None
    acctStatusType = None

    # xxx A dict would make this nice.
    for t in acctData:
    	if t[0] == 'User-Name':
    		userName = t[1]
    	elif t[0] == 'Acct-Session-Time':
    		acctSessionTime = t[1]
    	elif t[0] == 'Acct-Status-Type':
    		acctStatusType = t[1]


    # We will not deal with Start for now.
    # We may later, for simultaneous checks and the like.
    if acctStatusType == 'Start':
    	return radiusd.RLM_MODULE_OK

    # Build and log the SQL statement
    # radiusd puts double quotes (") around the string representation of
    # the RADIUS packet.
    #
    # xxx This is simplistic as it does not record the time, etc.
    #
    sql = 'insert into sessions (username, seconds) values (%s, %d)' % \
    (userName, int(acctSessionTime))

    log(radiusd.L_DBG, sql)

    # Get a cursor
    # xxx Or should this be one cursor all throughout?
    try:
    	dbCursor = dbHandle.cursor()
    except MySQLdb.OperationalError as e:
    	log(radiusd.L_ERR, str(e))
    	return radiusd.RLM_MODULE_FAIL

    # Execute the SQL statement
    try:
    	dbCursor.execute(sql)
    except MySQLdb.OperationalError as e:
    	log(radiusd.L_ERR, str(e))
    	dbCursor.close()
    	return radiusd.RLM_MODULE_FAIL


    return radiusd.RLM_MODULE_OK


def detach():
    """Detach and clean up."""
    # Shut down the database connection.
    global dbHandle
    log(radiusd.L_DBG, 'closing database handle: ' + str(dbHandle))
    dbHandle.close()

    return radiusd.RLM_MODULE_OK



# Test the modules
if __name__ == '__main__':
    instantiate(None)
    print(authorize((('User-Name', '"map"'), ('User-Password', '"abc"'))))