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