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