Modify FastCGI server to use MySQL for auth
[matches/MCTX3420.git] / server / login.c
1 /**
2  * @file login.c
3  * @brief Implementation of Login related functionality
4  */
5
6
7 #include "common.h"
8 #include "options.h"
9 #include <ctype.h>
10 #include <unistd.h>
11
12 // LDAP stuff
13 #define LDAP_DEPRECATED 1 // Required to use ldap_simple_bind_s
14 #include <ldap.h>
15
16 // MySQL stuff
17 #undef _GNU_SOURCE // HACK to silence compiler warning on redefinition in my_global.h
18 #include <my_global.h>
19 #include <mysql.h>
20
21
22
23
24
25 /**
26  * Attempt to login by searching a MySQL database
27  * @param user - Username
28  * @param pass - Password
29  * @param db_host - Host running the DataBase
30  * @param db_user - User to search the database as
31  * @param db_pass - Password for the database user
32  * @param db_name - Name of the database to use
33  * @param db_table - Table to search in
34  * @returns Privelage level of the user or USER_UNAUTH for failure to authenticate
35  */
36 UserType Login_MySQL(const char * user, const char * pass, 
37         const char * db_host, const char * db_user, const char * db_pass, const char * db_name, const char * db_table)
38 {
39         MYSQL * con = mysql_init(NULL);
40         if (con == NULL)
41         {
42                 Log(LOGERR, "mysql_init failed - %s", mysql_error(con));
43                 return USER_UNAUTH;
44         }
45
46         if (mysql_real_connect(con, db_host, db_user, db_pass, NULL, 0, NULL, 0) == NULL)
47         {
48                 Log(LOGERR, "mysql_real_connect failed - %s", mysql_error(con));
49                 mysql_close(con);
50                 return USER_UNAUTH;
51         }
52
53         char buffer[BUFSIZ];
54
55         // Select the database
56         sprintf(buffer, "USE %s;", db_name);
57         if (mysql_query(con, buffer))
58         {
59                 Log(LOGERR, "mysql_query failed - %s", mysql_error(con));
60                 mysql_close(con);
61                 return USER_UNAUTH;
62         }
63
64         // Search for the user
65         sprintf(buffer, "SELECT password FROM %s WHERE user_name = \"%s\";", db_table, user);
66         if (mysql_query(con, buffer))
67         {
68                 Log(LOGERR, "mysql_query failed - %s", mysql_error(con));
69                 mysql_close(con);
70                 return USER_UNAUTH;
71         }
72         
73         // Process the result
74         MYSQL_RES * result = mysql_store_result(con);
75         if (result == NULL)
76         {
77                 Log(LOGERR, "mysql_store_result failed - %s", mysql_error(con));
78                 mysql_close(con);
79                 return USER_UNAUTH;
80         }
81
82         int num_fields = mysql_num_fields(result);
83         if (num_fields != 1)
84         {
85                 Log(LOGERR, "The database may be corrupt; %d fields found, expected %d", num_fields, 1);
86                 mysql_close(con);
87                 return USER_UNAUTH;
88         }
89
90         UserType user_type = USER_UNAUTH;
91         MYSQL_ROW row;
92
93         // Get first row
94         if ((row = mysql_fetch_row(result)))
95         {
96                 if (strcmp(crypt(pass, row[0]), row[0]) == 0)
97                 {
98                         user_type = USER_NORMAL;
99                 }
100
101                 // There should only be one row. Through a hissy fit if we see any more.
102                 if ((row = mysql_fetch_row(result)))
103                 {
104                         Log(LOGERR, "Too many rows found.");
105                         user_type = USER_UNAUTH;
106                 }
107         }
108         else
109         {
110                 Log(LOGERR, "No user matching %s", user);
111         }
112
113
114         mysql_free_result(result);
115         mysql_close(con);
116         return user_type;
117 }
118
119 /**
120  * Attempt to login using a file formatted like /etc/shadow
121  * This is here... because all better options have been exhausted
122  * @param user - The username
123  * @param pass - The password
124  * @param shadow - The file to use
125  * @returns Privelage level of the user or USER_UNAUTH for failure to authenticate
126  */
127 UserType Login_Shadow(const char * user, const char * pass, const char * shadow)
128 {
129         if (strlen(user) + strlen(pass) >= BUFSIZ-1)
130         {
131                 Log(LOGERR, "User/Password too long!\n");
132                 return USER_UNAUTH;
133         }
134
135         FILE * f = fopen(shadow, "r");
136         if (f == NULL)
137         {
138                 Log(LOGERR,"Can't open %s - %s\n", shadow, strerror(errno));
139                 return USER_UNAUTH;
140         }
141
142         char buffer[BUFSIZ];
143         int passwd_index = -1;
144
145         while (fgets(buffer, BUFSIZ, f) != NULL) // NOTE: Restrict username+password strings to BUFSIZ... what could possibly go wrong?
146         {
147
148                 //Log(LOGDEBUG,"Scanning %d: %s", strlen(buffer), buffer);
149         
150                 for (int i = 0; i < BUFSIZ-1 && buffer[i] != '\0'; ++i)
151                 {
152                         if (buffer[i] == ':')
153                         {
154                                 buffer[i] = '\0';
155                                 passwd_index = i+1;
156                                 break;
157                         }
158                 }
159
160                 if (strcmp(user,buffer) == 0)
161                 {
162                         //Log(LOGDEBUG,"User matches! %s\n", buffer);
163                         break;
164                 } 
165                 passwd_index = -1;
166         }
167
168         if (passwd_index <= 0)
169         {
170                 //Log(LOGDEBUG,"No user found matching %s\n", user);
171                 return USER_UNAUTH;
172         }
173
174         int gid_index = -1;
175         for (int i = passwd_index; i < BUFSIZ-1 && buffer[i] != '\0'; ++i)
176         {
177                 if (buffer[i] == ':')
178                 {
179                         gid_index = i+1;
180                         buffer[i] = '\0';
181                 }
182                 if (buffer[i] == '\n')
183                         buffer[i] = '\0';
184         }
185         char * end = buffer+gid_index;
186         UserType user_type = USER_NORMAL;
187         if (gid_index > passwd_index && gid_index < BUFSIZ-1)
188         {
189                 int gid = strtol(buffer+gid_index, &end,10);
190                 Log(LOGDEBUG, "Usertype %d %s", gid, buffer+gid_index);
191                 if (*end == '\0' && gid == 0)
192                 {
193                         Log(LOGDEBUG, "Admin");
194                         user_type = USER_ADMIN;
195                 }
196         }
197         
198         // Determine the salt
199         char salt[BUFSIZ];
200         int s = 0; int count = 0;
201         for (int i = passwd_index; i < BUFSIZ-1; ++i)
202         {
203                 salt[s++] = buffer[i];
204                 if (salt[s] == '$' && ++count >= 3)
205                         break;
206         }
207
208 //      Log(LOGDEBUG,"Salted Entry: %s\n", buffer+passwd_index);
209 //      Log(LOGDEBUG,"Salted Attempt: %s\n", crypt(pass, salt));
210         
211         if (strcmp(crypt(pass, salt), buffer+passwd_index) == 0)
212         {
213                 return user_type;
214         }
215         return USER_UNAUTH;
216 }
217
218 /**
219  * Attempt to bind to a LDAP uri
220  * @param uri - The uri
221  * @param dn - The DN
222  * @param pass - The password
223  * @returns An error code according to libldap; LDAP_SUCCESS if everything worked
224  */
225 int Login_LDAP_Bind(const char * uri, const char * dn, const char * pass)
226 {
227         Log(LOGDEBUG, "Bind to %s with dn %s and pass %s", uri, dn, pass);
228
229         // Initialise LDAP; prepares to connect to the server
230         LDAP * ld = NULL;
231         int err = ldap_initialize(&ld, uri);
232         if (err != LDAP_SUCCESS || ld == NULL)
233         {
234                 Log(LOGERR,"ldap_initialize failed - %s (ld = %p)", ldap_err2string(err), ld);
235                 return err;
236         }
237
238         // Set the LDAP version...
239         int version = LDAP_VERSION3;
240         err = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version); // specify the version
241         if (err != LDAP_SUCCESS)
242         {
243                 Log(LOGERR,"ldap_set_option failed - %s", ldap_err2string(err));
244                 return err;
245         }
246
247         // Attempt to bind using the supplied credentials.
248         // NOTE: ldap_simple_bind_s is "deprecated" in <ldap.h>, but not listed as such in the man pages :S
249         err = ldap_simple_bind_s(ld, dn, pass);
250         if (err != LDAP_SUCCESS)
251         {
252                 Log(LOGERR, "ldap_simple_bind_s failed - %s", ldap_err2string(err));
253         }
254         else
255         {
256                 Log(LOGDEBUG, "Successfully bound to %s with dn %s", uri, dn);
257         }
258
259         int err2 = ldap_unbind_s(ld);
260         if (err2 != LDAP_SUCCESS)
261         {
262                 Log(LOGERR, "ldap_unbind_s failed - %s", ldap_err2string(err2));
263                 err = err2;
264         }
265         return err;
266 }
267
268 /**
269  * Logout
270  * @param context - The context. The key will be cleared.
271  * @param params - Parameter string, UNUSED
272  */
273 void Logout_Handler(FCGIContext * context, char * params)
274 {
275         FCGI_ReleaseControl(context);
276         FCGI_SendControlCookie(context, false); //Unset the cookie
277         FCGI_AcceptJSON(context, "Logged out");
278 }
279
280
281 /**
282  * Handle a Login Request
283  * @param context - The context
284  * @param params - Parameter string, should contain username and password
285  */
286 void Login_Handler(FCGIContext * context, char * params)
287 {
288         char * user; // The username supplied through CGI
289         char * pass; // The password supplied through CGI
290
291         FCGIValue values[] = {
292                 {"user", &user, FCGI_REQUIRED(FCGI_STRING_T)},
293                 {"pass", &pass, FCGI_REQUIRED(FCGI_STRING_T)},
294         };
295
296         //enum to avoid the use of magic numbers
297         typedef enum {
298                 USER,
299                 PASS,
300                 LOGOUT
301         } LoginParams;
302
303         // Fill values appropriately
304         if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
305         {
306                 // Error occured; FCGI_RejectJSON already called
307                 return;
308         }
309
310         // Trim leading whitespace
311         int i = 0;
312         for (i = 0; isspace(user[0]) && user[0] != '\0'; ++i, ++user);
313
314         // Truncate string at first non alphanumeric character
315         for (i = 0; isalnum(user[i]) && user[i] != '\0'; ++i);
316         user[i] = '\0';
317
318         
319         UserType user_type = USER_UNAUTH;
320         
321         switch (g_options.auth_method)
322         {
323
324                 case AUTH_LDAP:
325                 {
326                         if (strlen(pass) <= 0)
327                         {
328                                 FCGI_RejectJSON(context, "No password supplied.");
329                                 return;
330                         }
331
332                         //TODO: Generate the DN in some sane way
333                         char dn[BUFSIZ];
334
335
336                 
337                         // On a simple LDAP server:
338                         //int len = sprintf(dn, "uid=%s,%s", user, g_options.auth_options);
339         
340                         // At UWA (hooray)
341                         char * user_group = "Students";
342                         if (user[0] == '0')
343                                 user_group = "Staff";
344                         int len = sprintf(dn, "cn=%s,ou=%s,%s", user, user_group, g_options.auth_options);
345                 
346
347                         if (len >= BUFSIZ)
348                         {
349                                 FCGI_RejectJSON(context, "DN too long! Recompile with increased BUFSIZ");
350                                 return;
351                         }
352                 
353                         if (Login_LDAP_Bind(g_options.auth_uri, dn, pass) == LDAP_SUCCESS)
354                         {
355                                 if (user[0] == '0')
356                                         user_type = USER_ADMIN;
357                                 else
358                                         user_type = USER_NORMAL;
359                         }
360                         break;
361                 }
362                 case AUTH_SHADOW:
363                 {
364                         user_type = Login_Shadow(user, pass, g_options.auth_uri);
365                         break;
366                 }
367                 case AUTH_MYSQL:
368                 {
369                         //WARNING: C string manipulation code approaching!
370                         // Non reentrent; uses strsep and modifies g_options.auth_options
371                         // If problems happen, try strdup ...
372                         static char * db_opts[] = {"root", "", "users", "uc_users"};
373                         static bool db_init_opts = false;
374                         if (!db_init_opts)
375                         {
376                                 db_init_opts = true;
377                                 db_opts[0] = (char*)g_options.auth_options;
378                                 for (int i = 1; i < sizeof(db_opts)/sizeof(char*); ++i)
379                                 {
380                                         char * def = db_opts[i];
381                                         db_opts[i] = db_opts[i-1];
382
383                                         strsep(db_opts+i, ",");
384                                         if (db_opts[i] == NULL)
385                                         {
386                                                 db_opts[i] = def;
387                                                 break;
388                                         }
389                                 }                       
390                                 Log(LOGDEBUG, "MySQL: user %s pass %s name %s table %s", db_opts[0], db_opts[1], db_opts[2], db_opts[3]);       
391                         }
392
393                         user_type = Login_MySQL(user, pass, g_options.auth_uri, db_opts[0],db_opts[1], db_opts[2], db_opts[3]);
394                         break;
395                 }
396                 default:
397                 {
398                         Log(LOGWARN, "No authentication!");
399                         user_type = USER_ADMIN;
400                         break;
401                 }
402         }
403                 
404         // error check  
405         
406         if (user_type == USER_UNAUTH)
407         {
408                 Log(LOGDEBUG, "Authentication failure for %s", user);
409                 FCGI_RejectJSONEx(context, STATUS_UNAUTHORIZED, "Authentication failure.");
410         }
411         else
412         {
413                 // Try and gain control over the system
414                 if (FCGI_LockControl(context, user, user_type))
415                 {
416                         FCGI_EscapeText(context->user_name); //Don't break javascript pls
417                         // Give the user a cookie
418                         FCGI_SendControlCookie(context, true); //Send the control key
419                         FCGI_AcceptJSON(context, "Logged in");
420                         Log(LOGDEBUG, "Successful authentication for %s", user);
421                 }
422                 else
423                 {
424                         Log(LOGDEBUG, "%s successfully authenticated but system was in use by %s", user, context->user_name);
425                         FCGI_RejectJSON(context, "Someone else is already logged in (and you are not an admin)");
426                 }
427         }
428 }

UCC git Repository :: git.ucc.asn.au