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