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