5499f3b13f3ac48c011879d6c6ab83eab86c4684
[public/libpam-csc.git] / pam_csc.c
1 #define PAM_SM_ACCOUNT
2 #include <unistd.h>
3 #include <sys/types.h>
4 #include <sys/time.h>
5 #include <time.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <stdbool.h>
9 #include <string.h>
10 #include <security/pam_modules.h>
11 #include <security/pam_appl.h>
12 #include <ldap.h>
13 #include <sasl/sasl.h>
14 #include <syslog.h>
15 #include <pwd.h>
16
17 /* TODO
18  *
19  * We need to create a cronjob (that runs on logon and every hour) to run
20  * 'kinit -p TODO@STUDENT.CS.UWATERLOO.CA -k -c /tmp/krb5cc_pam_csc'
21  *
22  * We also need to add a keytab entry for TODO@STUDENT.CS.UWATERLOO.CA
23  *
24  */
25
26 #define PAM_CSC_CSC_BASE_DN         "ou=People,dc=csclub,dc=uwaterloo,dc=ca"
27 #define PAM_CSC_CSCF_URI \
28     "ldaps://eponina.student.cs.uwaterloo.ca" \
29     "ldaps://canadenis.student.cs.uwaterloo.ca"
30 #define PAM_CSC_CSCF_BASE_DN        "dc=student,dc=cs,dc=uwateloo,dc=ca"
31 #define PAM_CSC_CSCF_BIND_DN \
32     "uid=TODO,dc=student,dc=cs,dc=uwaterloo,dc=ca"
33 #define PAM_CSC_CSCF_SASL_USER \
34     "dn:uid=TODO,cn=STUDENT.CS.UWATERLOO.CA,cn=DIGEST-MD5,cn=auth"
35 #define PAM_CSC_CSCF_PASSWORD_FILE  "/etc/security/pam_csc_cscf_password"
36 #define PAM_CSC_CSCF_SASL_REALM     "STUDENT.CS.UWATERLOO.CA"
37 #define PAM_CSC_LDAP_TIMEOUT        5
38 #define PAM_CSC_MINIMUM_UID         1000
39 #define PAM_CSC_ALLOWED_USERNAMES   {"nobody"}
40 #define PAM_CSC_EXPIRED_MSG \
41     "*****************************************************************************\n" \
42     "*                                                                           *\n" \
43     "*    Your account has expired - please contact the Computer Science Club    *\n" \
44     "*                                                                           *\n" \
45     "*****************************************************************************\n"
46 #define PAM_CSC_CSCF_DISALLOWED_MSG \
47     "You are not registered as a CS student - login denied."
48
49 #define PAM_CSC_SYSLOG_EXPIRED_WARNING \
50     "(pam_csc): %s was not registered for current term or previous term - denying login\n"
51 #define PAM_CSC_SYSLOG_EXPIRED_ERROR \
52     "(pam_csc): %s was not registered for current term but was registered for previous term - permitting login\n"
53 #define PAM_CSC_SYSLOG_NOT_A_MEMBER \
54     "(pam_csc): %s is not a member account - permitting login\n"
55 #define PAM_CSC_SYSLOG_CSCF_DISALLOWED \
56     "(pam_csc): %s is using a CSCF machine but is not enrolled in CS - denying login\n"
57 #define PAM_CSC_SYSLOG_SASL_UNRECOGNIZED_CALLBACK \
58     "(pam_csc): %ld is not a recognized SASL callback option\n"
59
60 /*
61  * User terms are defined as (3 * year + term) where term is:
62  *   0 = Winter, 1 = Spring, 2 = Fall
63  * Term is a string in the form [f|w|s][year]
64  */
65
66 #define HANDLE_WARN \
67 { \
68     syslog(LOG_AUTHPRIV | LOG_WARNING, "pam_csc generated a warning on line %d of %s\n", __LINE__, __FILE__); \
69     retval = PAM_SUCCESS; \
70     goto cleanup; \
71 }
72
73 #define WARN_ZERO(x) \
74     if( (x) == 0 ) HANDLE_WARN
75
76 #define WARN_NEG1(x) \
77     if( (x) == -1 ) HANDLE_WARN
78
79 #define WARN_PAM(x) \
80     if( (x) != PAM_SUCCESS ) HANDLE_WARN
81
82 #define WARN_LDAP(x) \
83     if( (x) != LDAP_SUCCESS ) HANDLE_WARN
84
85 struct pam_csc_sasl_interact_param
86 {
87     const char* realm;
88     const char* user;
89     char pass[100];
90 };
91 typedef struct pam_csc_sasl_interact_param pam_csc_sasl_interact_param_t;
92
93 int pam_csc_sasl_interact(LDAP* ld, unsigned flags, void* def, void* inter)
94 {
95     pam_csc_sasl_interact_param_t* param = (pam_csc_sasl_interact_param_t*)def;
96     sasl_interact_t* interact = (sasl_interact_t*)interact;
97     while(interact->id != SASL_CB_LIST_END)
98     {
99         switch(interact->id)
100         {
101         case SASL_CB_GETREALM:
102             interact->result = param->realm;
103             interact->len = strlen(param->realm);
104         case SASL_CB_USER:
105             interact->result = param->user;
106             interact->len = strlen(param->user);
107             break;
108         case SASL_CB_PASS:
109             interact->result = param->pass;
110             interact->len = strlen(param->pass);
111         default:
112             syslog(LOG_AUTHPRIV | LOG_NOTICE,
113                 PAM_CSC_SYSLOG_SASL_UNRECOGNIZED_CALLBACK, interact->id);
114             interact->result = "";
115             interact->len = 0;
116         }
117     }
118
119     return LDAP_SUCCESS;
120 }
121
122 char* pam_csc_escape_ldap_string(const char* src)
123 {
124     char *dst, *dst_ptr;
125     int i;
126
127     if(!(dst = malloc(2 * strlen(src) + 1)))
128         return NULL;
129     dst_ptr = dst;
130
131     for(i = 0; i < strlen(src); i++)
132     {
133         if(src[i] == '*' || src[i] == '(' || src[i] == ')' || src[i] == '\\')
134         {
135             dst_ptr[0] = '\\';
136             dst_ptr++;
137         }
138         dst_ptr[0] = src[i];
139         dst_ptr++;
140     }
141     dst_ptr[0] = '\0';
142
143     return dst;
144 }
145
146 int pam_csc_print_message(pam_handle_t* pamh, char* msg, int style)
147 {
148     int retval = PAM_SUCCESS;
149     struct pam_conv* conv;
150     struct pam_message message;
151     struct pam_message* messages[1];
152     struct pam_response* response;
153
154     /* output message */
155     WARN_PAM( pam_get_item(pamh, PAM_CONV, (void**)&conv) )
156     messages[0] = &message;
157     message.msg_style = style;
158     message.msg = msg;
159     WARN_PAM( conv->conv(1, (const struct pam_message**)messages, 
160         &response, conv->appdata_ptr) )
161
162 cleanup:
163
164     return retval;
165 }
166
167 PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t* pamh, int flags, int argc, const char* argv[])
168 {
169     int retval = PAM_SUCCESS;
170     const char* username;
171     struct passwd* pwd;
172     const char* allowed_usernames[] = PAM_CSC_ALLOWED_USERNAMES;
173     int i;
174     time_t cur_time;
175     struct tm* local_time;
176     int long_term;
177     static const char term_chars[] = {'w', 's', 'f'};
178     char cur_term[6], prev_term[6];
179     LDAP *ld_csc = NULL, *ld_cscf = NULL;
180     bool cscf;
181     FILE* pass_file = NULL;
182     char* username_escaped = NULL;
183     char *filter_csc = NULL, *filter_cscf = NULL;
184     char *attrs_csc[] = {"objectClass", "term", NULL}, 
185         *attrs_cscf[] = {"objectClass", NULL};
186     bool expired;
187     const char* pam_rhost;
188     int msg_csc, msg_cscf;
189     LDAPMessage *res_csc = NULL, *res_cscf = NULL;
190     struct timeval timeout = {PAM_CSC_LDAP_TIMEOUT, 0};
191     LDAPMessage* entry = NULL;
192     char **values = NULL, **values_iter = NULL;
193
194     /* determine username */
195     if((pam_get_user(pamh, &username, NULL) != PAM_SUCCESS) || !username)
196     {
197         return PAM_USER_UNKNOWN;
198     }
199
200     /* check uid */
201     pwd = getpwnam(username);
202     if(pwd && pwd->pw_uid < PAM_CSC_MINIMUM_UID)
203     {
204         return PAM_SUCCESS;
205     }
206
207     /* check username */
208     for(i = 0; i < sizeof(allowed_usernames) / sizeof(char*); i++)
209     {
210         if(strcmp(allowed_usernames[i], username) == 0)
211         {
212             return PAM_SUCCESS;
213         }
214     }
215
216     /* escape username */
217     WARN_ZERO( username_escaped = pam_csc_escape_ldap_string(username) );
218
219     /* get term info and compute current and previous term */
220     WARN_NEG1( cur_time = time(NULL) )
221     WARN_ZERO( local_time = localtime(&cur_time) )
222     long_term = 3 * (1900 + local_time->tm_year) + (local_time->tm_mon / 4);
223     sprintf(cur_term, "%c%d", term_chars[long_term % 3], long_term / 3);
224     long_term--;
225     sprintf(prev_term, "%c%d", term_chars[long_term % 3], long_term / 3);
226
227     /* connect to CSC */
228     WARN_LDAP( ldap_create(&ld_csc) )
229     WARN_NEG1( ldap_simple_bind(ld_csc, NULL, NULL) )
230
231     /* check if we are logging in from a CSCF teaching thin client */
232     cscf = false;
233     if(pam_get_item(pamh, PAM_RHOST, (void**)&pam_rhost) && pam_rhost)
234     {
235         /* TODO: check pam_rhost
236          * It appears that the thin clients all have hostnames of the form
237          * tc[0-9]+\.cs
238          */
239     }
240
241     if(cscf)
242     {
243         pam_csc_sasl_interact_param_t interact_param = {
244             PAM_CSC_CSCF_SASL_REALM,
245             PAM_CSC_CSCF_SASL_USER
246         };
247         int ret;
248
249         /* read password file */
250         WARN_ZERO( pass_file = fopen(PAM_CSC_CSCF_PASSWORD_FILE, "r") )
251         ret = fread(interact_param.pass, sizeof(char), 
252             sizeof(interact_param.pass) - 1, pass_file);
253         interact_param.pass[ret] = '\0';
254         if(ret && interact_param.pass[ret - 1] == '\n')
255             interact_param.pass[ret - 1] = '\0';
256         fclose(pass_file); pass_file = NULL;
257
258         /* connect to CSCF */
259         WARN_LDAP( ldap_initialize(&ld_cscf, PAM_CSC_CSCF_URI) )
260         WARN_NEG1( ldap_sasl_interactive_bind_s(ld_cscf, PAM_CSC_CSCF_BIND_DN,
261             "DIGEST-MD5", NULL, NULL, LDAP_SASL_INTERACTIVE | LDAP_SASL_QUIET,
262             pam_csc_sasl_interact, &interact_param) )
263     }
264
265     /* create CSC request string */
266     WARN_ZERO( filter_csc = malloc(100 + strlen(username_escaped)) )
267     sprintf(filter_csc, "(&(uid=%s)(|(&(objectClass=member)(|(term=%s)(term=%s)))(!(objectClass=member))))", username_escaped, cur_term, prev_term);
268
269     /* issue CSC request */
270     WARN_NEG1( msg_csc = ldap_search(ld_csc, PAM_CSC_CSC_BASE_DN, 
271         LDAP_SCOPE_SUBTREE, filter_csc, attrs_csc, 0) )
272
273     if(cscf)
274     {
275         /* create CSCF request string */
276         WARN_ZERO( filter_cscf = malloc(100 + strlen(username_escaped)) )
277         sprintf(filter_csc, "TODO %s", username_escaped);
278
279         /* issue CSCF request */
280         WARN_NEG1( msg_cscf = ldap_search(ld_cscf, PAM_CSC_CSCF_BASE_DN, 
281             LDAP_SCOPE_SUBTREE, filter_cscf, attrs_cscf, 1) )
282     }
283
284     /* wait for CSC response */
285     WARN_NEG1( ldap_result(ld_csc, msg_csc, 1, &timeout, &res_csc) )
286
287     /* check if we received an entry from CSC */
288     if(ldap_count_entries(ld_csc, res_csc) == 0)
289     {
290         /* show notice and disallow login */
291         pam_csc_print_message(pamh, PAM_CSC_EXPIRED_MSG, PAM_ERROR_MSG);
292         syslog(LOG_AUTHPRIV | LOG_NOTICE, PAM_CSC_SYSLOG_EXPIRED_WARNING, 
293             username);
294         retval = PAM_AUTH_ERR;
295         goto cleanup;
296     }
297
298     /* get CSC entry */
299     WARN_ZERO( entry = ldap_first_entry(ld_csc, res_csc) )
300     values = ldap_get_values(ld_csc, entry, "term");
301     if(!values)
302     {
303         syslog(LOG_AUTHPRIV | LOG_NOTICE, PAM_CSC_SYSLOG_NOT_A_MEMBER, 
304             username);
305         retval = PAM_SUCCESS;
306         goto cleanup;
307     }
308
309     /* iterate through term attributes */
310     expired = true;
311     values_iter = values;
312     while(*values_iter)
313     {
314         if(strcmp(*values_iter, cur_term) == 0)
315         {
316             /* user is registered in current term */
317             expired = false;
318             break;
319         }
320         values_iter++;
321     }
322
323     /* check if account is expired */
324     if(expired)
325     {
326         /* show notice and continue */
327         pam_csc_print_message(pamh, PAM_CSC_EXPIRED_MSG, PAM_TEXT_INFO);
328         syslog(LOG_AUTHPRIV | LOG_NOTICE, PAM_CSC_SYSLOG_EXPIRED_ERROR, 
329             username);
330     }
331
332     if(cscf)
333     {
334         /* wait for CSCF response */
335         WARN_NEG1( ldap_result(ld_cscf, msg_cscf, 1, &timeout, &res_cscf) )
336
337         /* check if we got an entry back from CSCF */
338         if(ldap_count_entries(ld_cscf, res_cscf) == 0)
339         {
340             /* output CSCF disallowed message */
341             pam_csc_print_message(pamh, PAM_CSC_CSCF_DISALLOWED_MSG, 
342                 PAM_ERROR_MSG);
343             syslog(LOG_AUTHPRIV | LOG_NOTICE, PAM_CSC_SYSLOG_CSCF_DISALLOWED, 
344                 username);
345             retval = PAM_AUTH_ERR;
346             goto cleanup;
347         }
348     }
349
350 cleanup:
351
352     if(values) ldap_value_free(values);
353     if(res_csc) ldap_msgfree(res_csc);
354     if(res_cscf) ldap_msgfree(res_cscf);
355     if(ld_csc) ldap_unbind(ld_csc);
356     if(ld_cscf) ldap_unbind(ld_cscf);
357     if(filter_csc) free(filter_csc);
358     if(filter_cscf) free(filter_cscf);
359     if(username_escaped) free(username_escaped);
360
361     return retval;
362 }