Ensure consistent use of pdb_get_nt_passwd instead of pdb_get_lanman_passwd.
[ira/wip.git] / source3 / pam_smbpass / support.c
1 /* Unix NT password database implementation, version 0.6.
2  *
3  * This program is free software; you can redistribute it and/or modify it under
4  * the terms of the GNU General Public License as published by the Free
5  * Software Foundation; either version 3 of the License, or (at your option)
6  * any later version.
7  *
8  * This program is distributed in the hope that it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
11  * more details.
12  *
13  * You should have received a copy of the GNU General Public License along with
14  * this program; if not, see <http://www.gnu.org/licenses/>.
15  */
16
17 #include "includes.h"
18 #include "general.h"
19
20 #include "support.h"
21
22
23 #define _pam_overwrite(x)        \
24 do {                             \
25      register char *__xx__;      \
26      if ((__xx__=(x)))           \
27           while (*__xx__)        \
28                *__xx__++ = '\0'; \
29 } while (0)
30
31 /*
32  * Don't just free it, forget it too.
33  */
34
35 #define _pam_drop(X) \
36 do {                 \
37     if (X) {         \
38         free(X);     \
39         X=NULL;      \
40     }                \
41 } while (0)
42
43 #define _pam_drop_reply(/* struct pam_response * */ reply, /* int */ replies) \
44 do {                                              \
45     int reply_i;                                  \
46                                                   \
47     for (reply_i=0; reply_i<replies; ++reply_i) { \
48         if (reply[reply_i].resp) {                \
49             _pam_overwrite(reply[reply_i].resp);  \
50             free(reply[reply_i].resp);            \
51         }                                         \
52     }                                             \
53     if (reply)                                    \
54         free(reply);                              \
55 } while (0)
56
57
58 int converse(pam_handle_t *, int, int, struct pam_message **,
59                          struct pam_response **);
60 int make_remark(pam_handle_t *, unsigned int, int, const char *);
61 void _cleanup(pam_handle_t *, void *, int);
62 char *_pam_delete(register char *);
63
64 /* syslogging function for errors and other information */
65
66 void _log_err( int err, const char *format, ... )
67 {
68     va_list args;
69
70     va_start( args, format );
71     openlog( "PAM_smbpass", LOG_CONS | LOG_PID, LOG_AUTH );
72     vsyslog( err, format, args );
73     va_end( args );
74     closelog();
75 }
76
77 /* this is a front-end for module-application conversations */
78
79 int converse( pam_handle_t * pamh, int ctrl, int nargs
80               , struct pam_message **message
81               , struct pam_response **response )
82 {
83         int retval;
84         struct pam_conv *conv;
85
86         retval = pam_get_item(pamh, PAM_CONV, (const void **) &conv);
87         if (retval == PAM_SUCCESS) {
88
89                 retval = conv->conv(nargs, (const struct pam_message **) message
90                                                         ,response, conv->appdata_ptr);
91
92                 if (retval != PAM_SUCCESS && on(SMB_DEBUG, ctrl)) {
93                         _log_err(LOG_DEBUG, "conversation failure [%s]"
94                                          ,pam_strerror(pamh, retval));
95                 }
96         } else {
97                 _log_err(LOG_ERR, "couldn't obtain coversation function [%s]"
98                                  ,pam_strerror(pamh, retval));
99         }
100
101         return retval;                          /* propagate error status */
102 }
103
104 int make_remark( pam_handle_t * pamh, unsigned int ctrl
105                  , int type, const char *text )
106 {
107         if (off(SMB__QUIET, ctrl)) {
108                 struct pam_message *pmsg[1], msg[1];
109                 struct pam_response *resp;
110
111                 pmsg[0] = &msg[0];
112                 msg[0].msg = CONST_DISCARD(char *, text);
113                 msg[0].msg_style = type;
114                 resp = NULL;
115
116                 return converse(pamh, ctrl, 1, pmsg, &resp);
117         }
118         return PAM_SUCCESS;
119 }
120
121
122 /* set the control flags for the SMB module. */
123
124 int set_ctrl( int flags, int argc, const char **argv )
125 {
126     int i = 0;
127     const char *service_file = NULL;
128     unsigned int ctrl;
129
130     ctrl = SMB_DEFAULTS;        /* the default selection of options */
131
132     /* set some flags manually */
133
134     /* A good, sane default (matches Samba's behavior). */
135     set( SMB__NONULL, ctrl );
136
137     /* initialize service file location */
138     service_file=get_dyn_CONFIGFILE();
139
140     if (flags & PAM_SILENT) {
141         set( SMB__QUIET, ctrl );
142     }
143
144     /* Run through the arguments once, looking for an alternate smb config
145        file location */
146     while (i < argc) {
147         int j;
148
149         for (j = 0; j < SMB_CTRLS_; ++j) {
150             if (smb_args[j].token
151                 && !strncmp(argv[i], smb_args[j].token, strlen(smb_args[j].token)))
152             {
153                 break;
154             }
155         }
156
157         if (j == SMB_CONF_FILE) {
158             service_file = argv[i] + 8;
159         }
160         i++;
161     }
162
163     /* Read some options from the Samba config. Can be overridden by
164        the PAM config. */
165     if(lp_load(service_file,True,False,False,True) == False) {
166         _log_err( LOG_ERR, "Error loading service file %s", service_file );
167     }
168
169     secrets_init();
170
171     if (lp_null_passwords()) {
172         set( SMB__NULLOK, ctrl );
173     }
174
175     /* now parse the rest of the arguments to this module */
176
177     while (argc-- > 0) {
178         int j;
179
180         for (j = 0; j < SMB_CTRLS_; ++j) {
181             if (smb_args[j].token
182                 && !strncmp(*argv, smb_args[j].token, strlen(smb_args[j].token)))
183             {
184                 break;
185             }
186         }
187
188         if (j >= SMB_CTRLS_) {
189             _log_err( LOG_ERR, "unrecognized option [%s]", *argv );
190         } else {
191             ctrl &= smb_args[j].mask;   /* for turning things off */
192             ctrl |= smb_args[j].flag;   /* for turning things on  */
193         }
194
195         ++argv;                         /* step to next argument */
196     }
197
198     /* auditing is a more sensitive version of debug */
199
200     if (on( SMB_AUDIT, ctrl )) {
201         set( SMB_DEBUG, ctrl );
202     }
203     /* return the set of flags */
204
205     return ctrl;
206 }
207
208 /* use this to free strings. ESPECIALLY password strings */
209
210 char * _pam_delete( register char *xx )
211 {
212     _pam_overwrite( xx );
213     _pam_drop( xx );
214     return NULL;
215 }
216
217 void _cleanup( pam_handle_t * pamh, void *x, int error_status )
218 {
219     x = _pam_delete( (char *) x );
220 }
221
222 /* JHT
223  *
224  * Safe duplication of character strings. "Paranoid"; don't leave
225  * evidence of old token around for later stack analysis.
226  *
227  */
228 char * smbpXstrDup( const char *x )
229 {
230     register char *newstr = NULL;
231
232     if (x != NULL) {
233         register int i;
234
235         for (i = 0; x[i]; ++i); /* length of string */
236         if ((newstr = SMB_MALLOC_ARRAY(char, ++i)) == NULL) {
237             i = 0;
238             _log_err( LOG_CRIT, "out of memory in smbpXstrDup" );
239         } else {
240             while (i-- > 0) {
241                 newstr[i] = x[i];
242             }
243         }
244         x = NULL;
245     }
246     return newstr;                      /* return the duplicate or NULL on error */
247 }
248
249 /* ************************************************************** *
250  * Useful non-trivial functions                                   *
251  * ************************************************************** */
252
253 void _cleanup_failures( pam_handle_t * pamh, void *fl, int err )
254 {
255     int quiet;
256     const char *service = NULL;
257     struct _pam_failed_auth *failure;
258
259 #ifdef PAM_DATA_SILENT
260     quiet = err & PAM_DATA_SILENT;      /* should we log something? */
261 #else
262     quiet = 0;
263 #endif
264 #ifdef PAM_DATA_REPLACE
265     err &= PAM_DATA_REPLACE;    /* are we just replacing data? */
266 #endif
267     failure = (struct _pam_failed_auth *) fl;
268
269     if (failure != NULL) {
270
271 #ifdef PAM_DATA_SILENT
272         if (!quiet && !err) {   /* under advisement from Sun,may go away */
273 #else
274         if (!quiet) {   /* under advisement from Sun,may go away */
275 #endif
276
277             /* log the number of authentication failures */
278             if (failure->count != 0) {
279                 pam_get_item( pamh, PAM_SERVICE, (const void **) &service );
280                 _log_err( LOG_NOTICE
281                           , "%d authentication %s "
282                             "from %s for service %s as %s(%d)"
283                           , failure->count
284                           , failure->count == 1 ? "failure" : "failures"
285                           , failure->agent
286                           , service == NULL ? "**unknown**" : service 
287                           , failure->user, failure->id );
288                 if (failure->count > SMB_MAX_RETRIES) {
289                     _log_err( LOG_ALERT
290                               , "service(%s) ignoring max retries; %d > %d"
291                               , service == NULL ? "**unknown**" : service
292                               , failure->count
293                               , SMB_MAX_RETRIES );
294                 }
295             }
296         }
297         _pam_delete( failure->agent );  /* tidy up */
298         _pam_delete( failure->user );   /* tidy up */
299         SAFE_FREE( failure );
300     }
301 }
302
303 int _smb_verify_password( pam_handle_t * pamh, struct samu *sampass,
304                           const char *p, unsigned int ctrl )
305 {
306     uchar lm_pw[16];
307     uchar nt_pw[16];
308     int retval = PAM_AUTH_ERR;
309     char *data_name;
310     const char *name;
311
312     if (!sampass)
313         return PAM_ABORT;
314
315     name = pdb_get_username(sampass);
316
317 #ifdef HAVE_PAM_FAIL_DELAY
318     if (off( SMB_NODELAY, ctrl )) {
319         (void) pam_fail_delay( pamh, 1000000 ); /* 1 sec delay for on failure */
320     }
321 #endif
322
323     if (!pdb_get_nt_passwd(sampass))
324     {
325         _log_err( LOG_DEBUG, "user %s has null SMB password"
326                   , name );
327
328         if (off( SMB__NONULL, ctrl )
329             && (pdb_get_acct_ctrl(sampass) & ACB_PWNOTREQ))
330         { /* this means we've succeeded */
331             return PAM_SUCCESS;
332         } else {
333             const char *service;
334
335             pam_get_item( pamh, PAM_SERVICE, (const void **)&service );
336             _log_err( LOG_NOTICE, "failed auth request by %s for service %s as %s",
337                       uidtoname(getuid()), service ? service : "**unknown**", name);
338             return PAM_AUTH_ERR;
339         }
340     }
341
342     data_name = SMB_MALLOC_ARRAY(char, sizeof(FAIL_PREFIX) + strlen( name ));
343     if (data_name == NULL) {
344         _log_err( LOG_CRIT, "no memory for data-name" );
345         return PAM_AUTH_ERR;
346     }
347     strncpy( data_name, FAIL_PREFIX, sizeof(FAIL_PREFIX) );
348     strncpy( data_name + sizeof(FAIL_PREFIX) - 1, name, strlen( name ) + 1 );
349
350     /*
351      * The password we were given wasn't an encrypted password, or it
352      * didn't match the one we have.  We encrypt the password now and try
353      * again.
354      */
355
356     nt_lm_owf_gen(p, nt_pw, lm_pw);
357
358     /* the moment of truth -- do we agree with the password? */
359
360     if (!memcmp( nt_pw, pdb_get_nt_passwd(sampass), 16 )) {
361
362         retval = PAM_SUCCESS;
363         if (data_name) {                /* reset failures */
364             pam_set_data(pamh, data_name, NULL, _cleanup_failures);
365         }
366     } else {
367
368         const char *service;
369
370         pam_get_item( pamh, PAM_SERVICE, (const void **)&service );
371
372         if (data_name != NULL) {
373             struct _pam_failed_auth *newauth = NULL;
374             const struct _pam_failed_auth *old = NULL;
375
376             /* get a failure recorder */
377
378             newauth = SMB_MALLOC_P( struct _pam_failed_auth );
379
380             if (newauth != NULL) {
381
382                 /* any previous failures for this user ? */
383                 pam_get_data(pamh, data_name, (const void **) &old);
384
385                 if (old != NULL) {
386                     newauth->count = old->count + 1;
387                     if (newauth->count >= SMB_MAX_RETRIES) {
388                         retval = PAM_MAXTRIES;
389                     }
390                 } else {
391                     _log_err(LOG_NOTICE,
392                       "failed auth request by %s for service %s as %s",
393                       uidtoname(getuid()),
394                       service ? service : "**unknown**", name);
395                     newauth->count = 1;
396                 }
397                 if (!sid_to_uid(pdb_get_user_sid(sampass), &(newauth->id))) {
398                     _log_err(LOG_NOTICE,
399                       "failed auth request by %s for service %s as %s",
400                       uidtoname(getuid()),
401                       service ? service : "**unknown**", name);
402                 }               
403                 newauth->user = smbpXstrDup( name );
404                 newauth->agent = smbpXstrDup( uidtoname( getuid() ) );
405                 pam_set_data( pamh, data_name, newauth, _cleanup_failures );
406
407             } else {
408                 _log_err( LOG_CRIT, "no memory for failure recorder" );
409                 _log_err(LOG_NOTICE,
410                       "failed auth request by %s for service %s as %s(%d)",
411                       uidtoname(getuid()),
412                       service ? service : "**unknown**", name);
413             }
414         }
415         _log_err(LOG_NOTICE,
416                   "failed auth request by %s for service %s as %s(%d)",
417                   uidtoname(getuid()),
418                   service ? service : "**unknown**", name);
419         retval = PAM_AUTH_ERR;
420     }
421
422     _pam_delete( data_name );
423     
424     return retval;
425 }
426
427
428 /*
429  * _smb_blankpasswd() is a quick check for a blank password
430  *
431  * returns TRUE if user does not have a password
432  * - to avoid prompting for one in such cases (CG)
433  */
434
435 int _smb_blankpasswd( unsigned int ctrl, struct samu *sampass )
436 {
437         int retval;
438
439         /*
440          * This function does not have to be too smart if something goes
441          * wrong, return FALSE and let this case to be treated somewhere
442          * else (CG)
443          */
444
445         if (on( SMB__NONULL, ctrl ))
446                 return 0;               /* will fail but don't let on yet */
447
448         if (!(pdb_get_acct_ctrl(sampass) & ACB_PWNOTREQ))
449                 return 0;
450
451         if (pdb_get_nt_passwd(sampass) == NULL)
452                 retval = 1;
453         else
454                 retval = 0;
455
456         return retval;
457 }
458
459 /*
460  * obtain a password from the user
461  */
462
463 int _smb_read_password( pam_handle_t * pamh, unsigned int ctrl,
464                         const char *comment, const char *prompt1,
465                         const char *prompt2, const char *data_name, char **pass )
466 {
467     int authtok_flag;
468     int retval;
469     char *item = NULL;
470     char *token;
471
472     struct pam_message msg[3], *pmsg[3];
473     struct pam_response *resp;
474     int i, expect;
475
476
477     /* make sure nothing inappropriate gets returned */
478
479     *pass = token = NULL;
480
481     /* which authentication token are we getting? */
482
483     authtok_flag = on(SMB__OLD_PASSWD, ctrl) ? PAM_OLDAUTHTOK : PAM_AUTHTOK;
484
485     /* should we obtain the password from a PAM item ? */
486
487     if (on(SMB_TRY_FIRST_PASS, ctrl) || on(SMB_USE_FIRST_PASS, ctrl)) {
488         retval = pam_get_item( pamh, authtok_flag, (const void **) &item );
489         if (retval != PAM_SUCCESS) {
490             /* very strange. */
491             _log_err( LOG_ALERT
492                       , "pam_get_item returned error to smb_read_password" );
493             return retval;
494         } else if (item != NULL) {      /* we have a password! */
495             *pass = item;
496             item = NULL;
497             return PAM_SUCCESS;
498         } else if (on( SMB_USE_FIRST_PASS, ctrl )) {
499             return PAM_AUTHTOK_RECOVER_ERR;             /* didn't work */
500         } else if (on( SMB_USE_AUTHTOK, ctrl )
501                    && off( SMB__OLD_PASSWD, ctrl ))
502         {
503             return PAM_AUTHTOK_RECOVER_ERR;
504         }
505     }
506
507     /*
508      * getting here implies we will have to get the password from the
509      * user directly.
510      */
511
512     /* prepare to converse */
513     if (comment != NULL && off(SMB__QUIET, ctrl)) {
514         pmsg[0] = &msg[0];
515         msg[0].msg_style = PAM_TEXT_INFO;
516         msg[0].msg = CONST_DISCARD(char *, comment);
517         i = 1;
518     } else {
519         i = 0;
520     }
521
522     pmsg[i] = &msg[i];
523     msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
524     msg[i++].msg = CONST_DISCARD(char *, prompt1);
525
526     if (prompt2 != NULL) {
527         pmsg[i] = &msg[i];
528         msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
529         msg[i++].msg = CONST_DISCARD(char *, prompt2);
530         expect = 2;
531     } else
532         expect = 1;
533
534     resp = NULL;
535
536     retval = converse( pamh, ctrl, i, pmsg, &resp );
537
538     if (resp != NULL) {
539         int j = comment ? 1 : 0;
540         /* interpret the response */
541
542         if (retval == PAM_SUCCESS) {    /* a good conversation */
543
544             token = smbpXstrDup(resp[j++].resp);
545             if (token != NULL) {
546                 if (expect == 2) {
547                     /* verify that password entered correctly */
548                     if (!resp[j].resp || strcmp( token, resp[j].resp )) {
549                         _pam_delete( token );
550                         retval = PAM_AUTHTOK_RECOVER_ERR;
551                         make_remark( pamh, ctrl, PAM_ERROR_MSG
552                                      , MISTYPED_PASS );
553                     }
554                 }
555             } else {
556                 _log_err(LOG_NOTICE, "could not recover authentication token");
557             }
558         }
559
560         /* tidy up */
561         _pam_drop_reply( resp, expect );
562
563     } else {
564         retval = (retval == PAM_SUCCESS) ? PAM_AUTHTOK_RECOVER_ERR : retval;
565     }
566
567     if (retval != PAM_SUCCESS) {
568         if (on( SMB_DEBUG, ctrl ))
569             _log_err( LOG_DEBUG, "unable to obtain a password" );
570         return retval;
571     }
572     /* 'token' is the entered password */
573
574     if (off( SMB_NOT_SET_PASS, ctrl )) {
575
576         /* we store this password as an item */
577
578         retval = pam_set_item( pamh, authtok_flag, (const void *)token );
579         _pam_delete( token );           /* clean it up */
580         if (retval != PAM_SUCCESS
581             || (retval = pam_get_item( pamh, authtok_flag
582                             ,(const void **)&item )) != PAM_SUCCESS)
583         {
584             _log_err( LOG_CRIT, "error manipulating password" );
585             return retval;
586         }
587     } else {
588         /*
589          * then store it as data specific to this module. pam_end()
590          * will arrange to clean it up.
591          */
592
593         retval = pam_set_data( pamh, data_name, (void *) token, _cleanup );
594         if (retval != PAM_SUCCESS
595             || (retval = pam_get_data( pamh, data_name, (const void **)&item ))
596                              != PAM_SUCCESS)
597         {
598             _log_err( LOG_CRIT, "error manipulating password data [%s]"
599                       , pam_strerror( pamh, retval ));
600             _pam_delete( token );
601             item = NULL;
602             return retval;
603         }
604         token = NULL;                   /* break link to password */
605     }
606
607     *pass = item;
608     item = NULL;                        /* break link to password */
609
610     return PAM_SUCCESS;
611 }
612
613 int _pam_smb_approve_pass(pam_handle_t * pamh,
614                 unsigned int ctrl,
615                 const char *pass_old,
616                 const char *pass_new )
617 {
618
619     /* Further checks should be handled through module stacking. -SRL */
620     if (pass_new == NULL || (pass_old && !strcmp( pass_old, pass_new )))
621     {
622         if (on(SMB_DEBUG, ctrl)) {
623             _log_err( LOG_DEBUG,
624                       "passwd: bad authentication token (null or unchanged)" );
625         }
626         make_remark( pamh, ctrl, PAM_ERROR_MSG, pass_new == NULL ?
627                                 "No password supplied" : "Password unchanged" );
628         return PAM_AUTHTOK_ERR;
629     }
630
631     return PAM_SUCCESS;
632 }