various. debug levels changed. nmbd doesn't need libsmb/clienttrust.c.
[ira/wip.git] / source3 / smbd / password.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Password and authentication handling
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 extern int DEBUGLEVEL;
25 extern int Protocol;
26
27 /* users from session setup */
28 static pstring session_users="";
29
30 extern pstring scope;
31 extern pstring global_myname;
32 extern fstring global_myworkgroup;
33
34 /* Data to do lanman1/2 password challenge. */
35 static unsigned char saved_challenge[8];
36 static BOOL challenge_sent=False;
37
38 /*******************************************************************
39 Get the next challenge value - no repeats.
40 ********************************************************************/
41 void generate_next_challenge(char *challenge)
42 {
43 #if 0
44         /* 
45          * Leave this ifdef'd out while we test
46          * the new crypto random number generator.
47          * JRA.
48          */
49         unsigned char buf[16];
50         static int counter = 0;
51         struct timeval tval;
52         int v1,v2;
53
54         /* get a sort-of random number */
55         GetTimeOfDay(&tval);
56         v1 = (counter++) + getpid() + tval.tv_sec;
57         v2 = (counter++) * getpid() + tval.tv_usec;
58         SIVAL(challenge,0,v1);
59         SIVAL(challenge,4,v2);
60
61         /* mash it up with md4 */
62         mdfour(buf, (unsigned char *)challenge, 8);
63 #else
64         unsigned char buf[8];
65
66         generate_random_buffer(buf,8,False);
67 #endif 
68         memcpy(saved_challenge, buf, 8);
69         memcpy(challenge,buf,8);
70         challenge_sent = True;
71 }
72
73 /*******************************************************************
74 set the last challenge sent, usually from a password server
75 ********************************************************************/
76 BOOL set_challenge(unsigned char *challenge)
77 {
78   memcpy(saved_challenge,challenge,8);
79   challenge_sent = True;
80   return(True);
81 }
82
83 /*******************************************************************
84 get the last challenge sent
85 ********************************************************************/
86 static BOOL last_challenge(unsigned char *challenge)
87 {
88   if (!challenge_sent) return False;
89   memcpy(challenge,saved_challenge,8);
90   return(True);
91 }
92
93 /* this holds info on user ids that are already validated for this VC */
94 static user_struct *validated_users = NULL;
95 static int num_validated_users = 0;
96
97 /****************************************************************************
98 check if a uid has been validated, and return an pointer to the user_struct
99 if it has. NULL if not. vuid is biased by an offset. This allows us to
100 tell random client vuid's (normally zero) from valid vuids.
101 ****************************************************************************/
102 user_struct *get_valid_user_struct(uint16 vuid)
103 {
104   if (vuid == UID_FIELD_INVALID)
105     return NULL;
106   vuid -= VUID_OFFSET;
107   if ((vuid >= (uint16)num_validated_users) || 
108      (validated_users[vuid].uid == (uid_t)-1) || (validated_users[vuid].gid == (gid_t)-1))
109     return NULL;
110   return &validated_users[vuid];
111 }
112
113 /****************************************************************************
114 invalidate a uid
115 ****************************************************************************/
116 void invalidate_vuid(uint16 vuid)
117 {
118   user_struct *vuser = get_valid_user_struct(vuid);
119
120   if (vuser == NULL) return;
121
122   vuser->uid = (uid_t)-1;
123   vuser->gid = (gid_t)-1;
124
125   vuser->n_sids = 0;
126
127   /* same number of igroups as groups */
128   vuser->n_groups = 0;
129
130   if (vuser->groups)
131     free((char *)vuser->groups);
132
133   if (vuser->sids)
134     free((char *)vuser->sids);
135
136   vuser->sids    = NULL;
137   vuser->groups  = NULL;
138 }
139
140
141 /****************************************************************************
142 return a validated username
143 ****************************************************************************/
144 char *validated_username(uint16 vuid)
145 {
146   user_struct *vuser = get_valid_user_struct(vuid);
147   if (vuser == NULL)
148     return 0;
149   return(vuser->name);
150 }
151
152
153
154 /****************************************************************************
155 register a uid/name pair as being valid and that a valid password
156 has been given. vuid is biased by an offset. This allows us to
157 tell random client vuid's (normally zero) from valid vuids.
158 ****************************************************************************/
159 uint16 register_vuid(uid_t uid,gid_t gid, char *unix_name, char *requested_name, BOOL guest, uchar user_sess_key[16])
160 {
161   user_struct *vuser;
162   struct passwd *pwfile; /* for getting real name from passwd file */
163
164   /* Ensure no vuid gets registered in share level security. */
165   if(lp_security() == SEC_SHARE)
166     return UID_FIELD_INVALID;
167
168 #if 0
169   /*
170    * After observing MS-Exchange services writing to a Samba share
171    * I belive this code is incorrect. Each service does its own
172    * sessionsetup_and_X for the same user, and as each service shuts
173    * down, it does a user_logoff_and_X. As we are consolidating multiple
174    * sessionsetup_and_X's onto the same vuid here, when the first service
175    * shuts down, it invalidates all the open files for the other services.
176    * Hence I am removing this code and forcing each sessionsetup_and_X
177    * to get a new vuid.
178    * Jeremy Allison. (jallison@whistle.com).
179    */
180
181   int i;
182   for(i = 0; i < num_validated_users; i++) {
183     vuser = &validated_users[i];
184     if ( vuser->uid == uid )
185       return (uint16)(i + VUID_OFFSET); /* User already validated */
186   }
187 #endif
188
189   validated_users = (user_struct *)Realloc(validated_users,
190                            sizeof(user_struct)*
191                            (num_validated_users+1));
192   
193   if (!validated_users)
194     {
195       DEBUG(0,("Failed to realloc users struct!\n"));
196       num_validated_users = 0;
197       return UID_FIELD_INVALID;
198     }
199
200   vuser = &validated_users[num_validated_users];
201   num_validated_users++;
202
203   vuser->uid = uid;
204   vuser->gid = gid;
205   vuser->guest = guest;
206   fstrcpy(vuser->name,unix_name);
207   fstrcpy(vuser->requested_name,requested_name);
208   memcpy(vuser->dc.user_sess_key, user_sess_key, sizeof(vuser->dc.user_sess_key));
209
210   vuser->n_sids = 0;
211   vuser->sids   = NULL;
212
213   vuser->n_groups = 0;
214   vuser->groups  = NULL;
215
216   /* Find all the groups this uid is in and store them. 
217      Used by become_user() */
218   get_unixgroups(unix_name,uid,gid,
219                &vuser->n_groups,
220                &vuser->groups);
221
222   DEBUG(3,("uid %d registered to name %s\n",(int)uid,unix_name));
223
224   DEBUG(3, ("Clearing default real name\n"));
225   fstrcpy(vuser->real_name, "<Full Name>\0");
226   if (lp_unix_realname()) {
227     if ((pwfile=hashed_getpwnam(vuser->name))!= NULL)
228       {
229       DEBUG(3, ("User name: %s\tReal name: %s\n",vuser->name,pwfile->pw_gecos));
230       fstrcpy(vuser->real_name, pwfile->pw_gecos);
231       }
232   }
233
234   return (uint16)((num_validated_users - 1) + VUID_OFFSET);
235 }
236
237
238 /****************************************************************************
239 add a name to the session users list
240 ****************************************************************************/
241 void add_session_user(char *user)
242 {
243   fstring suser;
244   StrnCpy(suser,user,sizeof(suser)-1);
245
246   if (!Get_Pwnam(suser,True)) return;
247
248   if (suser && *suser && !in_list(suser,session_users,False))
249     {
250       if (strlen(suser) + strlen(session_users) + 2 >= sizeof(pstring))
251         DEBUG(1,("Too many session users??\n"));
252       else
253         {
254           pstrcat(session_users," ");
255           pstrcat(session_users,suser);
256         }
257     }
258 }
259
260
261 /****************************************************************************
262 update the encrypted smbpasswd file from the plaintext username and password
263 *****************************************************************************/
264 static BOOL update_smbpassword_file(char *user, char *password)
265 {
266         struct smb_passwd *smbpw;
267         BOOL ret;
268         
269         become_root(0);
270         smbpw = getsmbpwnam(user);
271         unbecome_root(0);
272         
273         if(smbpw == NULL) {
274                 DEBUG(0,("getsmbpwnam returned NULL\n"));
275                 return False;
276         }
277  
278         /* Here, the flag is one, because we want to ignore the
279            XXXXXXX'd out password */
280         ret = change_oem_password( smbpw, password, True);
281         if (ret == False) {
282                 DEBUG(3,("change_oem_password returned False\n"));
283         }
284
285         return ret;
286 }
287
288
289
290
291
292 /****************************************************************************
293 core of smb password checking routine.
294 ****************************************************************************/
295 static BOOL smb_pwd_check_ntlmv1(char *password, unsigned char *part_passwd,
296                                 unsigned char *c8)
297 {
298   /* Finish the encryption of part_passwd. */
299   unsigned char p24[24];
300
301   if (part_passwd == NULL)
302     DEBUG(10,("No password set - allowing access\n"));
303   /* No password set - always true ! */
304   if (part_passwd == NULL)
305     return True;
306
307   SMBOWFencrypt(part_passwd, c8, p24);
308 #if DEBUG_PASSWORD
309         DEBUG(100,("Part password (P16) was |"));
310         dump_data(100, part_passwd, 16);
311         DEBUG(100,("Password from client was |"));
312         dump_data(100, password, 24);
313         DEBUG(100,("Given challenge was |"));
314         dump_data(100, c8, 8);
315         DEBUG(100,("Value from encryption was |"));
316         dump_data(100, p24, 24);
317 #endif
318   return (memcmp(p24, password, 24) == 0);
319 }
320
321 /****************************************************************************
322 core of smb password checking routine.
323 ****************************************************************************/
324 static BOOL smb_pwd_check_ntlmv2(char *password, size_t pwd_len,
325                                 unsigned char *part_passwd,
326                                 unsigned char const *c8,
327                                 const char *user, const char *domain)
328 {
329         /* Finish the encryption of part_passwd. */
330         unsigned char kr[16];
331
332         if (part_passwd == NULL)
333         {
334                 DEBUG(10,("No password set - allowing access\n"));
335         }
336         /* No password set - always true ! */
337         if (part_passwd == NULL)
338         {
339                 return True;
340         }
341
342         ntv2_owf_gen(part_passwd, user, domain, kr);
343         SMBOWFencrypt_ntv2(kr, c8, 8, password+16, pwd_len-16, kr);
344
345 #if DEBUG_PASSWORD
346         DEBUG(100,("Part password (P16) was |"));
347         dump_data(100, part_passwd, 16);
348         DEBUG(100,("Password from client was |"));
349         dump_data(100, password, pwd_len);
350         DEBUG(100,("Given challenge was |"));
351         dump_data(100, c8, 8);
352         DEBUG(100,("Value from encryption was |"));
353         dump_data(100, kr, 16);
354 #endif
355
356         return (memcmp(kr, password, 16) == 0);
357 }
358
359 /****************************************************************************
360  Do a specific test for an smb password being correct, given a smb_password and
361  the lanman and NT responses.
362 ****************************************************************************/
363 BOOL smb_password_ok(struct smb_passwd *smb_pass, uchar chal[8],
364                                 const char *user, const char *domain,
365                                 uchar *lm_pass, size_t lm_pwd_len,
366                                 uchar *nt_pass, size_t nt_pwd_len)
367 {
368         uchar challenge[8];
369
370         if (smb_pass == NULL)
371         {
372                 return False;
373         }
374
375         DEBUG(4,("Checking SMB password for user %s\n", 
376                  smb_pass->unix_name));
377
378         if (smb_pass->acct_ctrl & ACB_DISABLED)
379         {
380                 DEBUG(3,("account for user %s was disabled.\n", 
381                          smb_pass->unix_name));
382                 return False;
383         }
384
385         if (chal == NULL)
386         {
387                 DEBUG(5,("use last SMBnegprot challenge\n"));
388                 if (!last_challenge(challenge))
389                 {
390                         DEBUG(1,("no challenge done - password failed\n"));
391                         return False;
392                 }
393         }
394         else
395         {
396                 DEBUG(5,("challenge received\n"));
397                 memcpy(challenge, chal, 8);
398         }
399
400         if ((Protocol >= PROTOCOL_NT1) && (smb_pass->smb_nt_passwd != NULL))
401         {
402                 /* We have the NT MD4 hash challenge available - see if we can
403                    use it (ie. does it exist in the smbpasswd file).
404                 */
405                 if (lp_server_ntlmv2() != False && nt_pwd_len > 24)
406                 {
407                         DEBUG(4,("smb_password_ok: Check NTLMv2 password\n"));
408                         if (smb_pwd_check_ntlmv2(nt_pass, nt_pwd_len,
409                                        (uchar *)smb_pass->smb_nt_passwd, 
410                                         challenge, user, domain))
411                         {
412                                 return True;
413                         }
414                 }
415                 if (lp_server_ntlmv2() != True && nt_pwd_len == 24)
416                 {
417                         DEBUG(4,("smb_password_ok: Check NT MD4 password\n"));
418                         if (smb_pwd_check_ntlmv1((char *)nt_pass, 
419                                        (uchar *)smb_pass->smb_nt_passwd, 
420                                        challenge))
421                         {
422                                 DEBUG(4,("NT MD4 password check succeeded\n"));
423                                 return True;
424                         }
425                 }
426                 DEBUG(4,("NT MD4 password check failed\n"));
427         }
428
429         if (lp_server_ntlmv2() == True)
430         {
431                 DEBUG(4,("Not checking LM MD4 password\n"));
432                 return False;
433         }
434
435         /* Try against the lanman password. smb_pass->smb_passwd == NULL means
436            no password, allow access. */
437
438         DEBUG(4,("Checking LM MD4 password\n"));
439
440         if ((smb_pass->smb_passwd == NULL) && 
441            (smb_pass->acct_ctrl & ACB_PWNOTREQ))
442         {
443                 DEBUG(4,("no password required for user %s\n",
444                          smb_pass->unix_name));
445                 return True;
446         }
447
448         if ((smb_pass->smb_passwd != NULL) && 
449            smb_pwd_check_ntlmv1((char *)lm_pass, 
450                               (uchar *)smb_pass->smb_passwd,
451                                 challenge))
452         {
453                 DEBUG(4,("LM MD4 password check succeeded\n"));
454                 return(True);
455         }
456
457         DEBUG(4,("LM MD4 password check failed\n"));
458
459         return False;
460 }
461
462
463 /****************************************************************************
464 check if a username/password is OK assuming the password is a 24 byte
465 SMB hash
466 return True if the password is correct, False otherwise
467 ****************************************************************************/
468
469 BOOL pass_check_smb(char *user, char *domain, uchar *chal,
470                 uchar *lm_pwd, size_t lm_pwd_len,
471                 uchar *nt_pwd, size_t nt_pwd_len,
472                 struct passwd *pwd, uchar user_sess_key[16])
473 {
474         const struct passwd *pass;
475         struct passwd pw;
476         struct smb_passwd *smb_pass;
477
478         if (!lm_pwd || !nt_pwd)
479         {
480                 return False;
481         }
482
483         if (pwd != NULL && user == NULL)
484         {
485                 pass = (struct passwd *) pwd;
486                 user = pass->pw_name;
487         }
488         else
489         {
490                 pass = Get_Pwnam(user,True);
491                 if (pass == NULL)
492                 {
493                         DEBUG(3,("Couldn't find user %s\n",user));
494                         return False;
495                 }
496                 memcpy(&pw, pass, sizeof(struct passwd));
497                 pass = &pw;
498         }
499
500         smb_pass = getsmbpwnam(user);
501
502         if (smb_pass == NULL)
503         {
504                 DEBUG(3,("Couldn't find user %s in smb_passwd file.\n", user));
505                 return False;
506         }
507
508         /* Quit if the account was disabled. */
509         if (smb_pass->acct_ctrl & ACB_DISABLED) {
510                 DEBUG(3,("account for user %s was disabled.\n", user));
511                 return False;
512         }
513
514         /* Ensure the uid's match */
515         if (smb_pass->unix_uid != pass->pw_uid)
516         {
517                 DEBUG(3,("Error : UNIX (%d) and SMB (%d) uids in password files do not match !\n", pass->pw_uid, smb_pass->unix_uid));
518                 return False;
519         }
520
521         if (lm_pwd[0] == '\0' && IS_BITS_SET_ALL(smb_pass->acct_ctrl, ACB_PWNOTREQ) && lp_null_passwords())
522         {
523                 DEBUG(3,("account for user %s has no password and null passwords are allowed.\n", smb_pass->unix_name));
524                 return(True);
525         }
526
527         if (smb_password_ok(smb_pass, chal, user, domain,
528                                             lm_pwd, lm_pwd_len,
529                                             nt_pwd, nt_pwd_len))
530         {
531                 if (user_sess_key != NULL)
532                 {
533                         mdfour(user_sess_key, smb_pass->smb_nt_passwd, 16);
534 #ifdef DEBUG_PASSWORD
535                 DEBUG(100,("user session key: "));
536                 dump_data(100, user_sess_key, 16);
537 #endif
538                 }
539                 return(True);
540         }
541         
542         DEBUG(3,("Error pass_check_smb failed\n"));
543         return False;
544 }
545
546 /****************************************************************************
547 check if a username/password pair is OK either via the system password
548 database or the encrypted SMB password database
549 return True if the password is correct, False otherwise
550 ****************************************************************************/
551 BOOL password_ok(char *user, char *password, int pwlen, struct passwd *pwd,
552                 uchar user_sess_key[16])
553 {
554         if (pwlen >= 24 || (lp_encrypted_passwords() && (pwlen == 0) && lp_null_passwords()))
555         {
556                 /* if 24 bytes or longer assume it is an encrypted password */
557                 uchar challenge[8];
558
559                 if (!last_challenge(challenge))
560                 {
561                         DEBUG(0,("Error: challenge not done for user=%s\n", user));
562                         return False;
563                 }
564
565                 return pass_check_smb(user, global_myworkgroup,
566                                       challenge, (uchar *)password,
567                                         pwlen, (uchar *)password, pwlen,
568                                         pwd, user_sess_key);
569         } 
570
571         return pass_check(user, password, pwlen, pwd, 
572                           lp_update_encrypted() ? 
573                           update_smbpassword_file : NULL);
574 }
575
576 /****************************************************************************
577 check if a username is valid
578 ****************************************************************************/
579 BOOL user_ok(char *user,int snum)
580 {
581         pstring valid, invalid;
582         BOOL ret;
583
584         StrnCpy(valid, lp_valid_users(snum), sizeof(pstring));
585         StrnCpy(invalid, lp_invalid_users(snum), sizeof(pstring));
586
587         string_sub(valid,"%S",lp_servicename(snum));
588         string_sub(invalid,"%S",lp_servicename(snum));
589         
590         ret = !user_in_list(user,invalid);
591         
592         if (ret && valid && *valid) {
593                 ret = user_in_list(user,valid);
594         }
595
596         if (ret && lp_onlyuser(snum)) {
597                 char *user_list = lp_username(snum);
598                 string_sub(user_list,"%S",lp_servicename(snum));
599                 ret = user_in_list(user,user_list);
600         }
601
602         return(ret);
603 }
604
605
606
607
608 /****************************************************************************
609 validate a group username entry. Return the username or NULL
610 ****************************************************************************/
611 static char *validate_group(char *group,char *password,int pwlen,int snum,
612                                 uchar user_sess_key[16])
613 {
614 #if defined(HAVE_NETGROUP) && defined(HAVE_GETNETGRENT) && defined(HAVE_SETNETGRENT) && defined(HAVE_ENDNETGRENT)
615   {
616     char *host, *user, *domain;
617     setnetgrent(group);
618     while (getnetgrent(&host, &user, &domain)) {
619       if (user) {
620         if (user_ok(user, snum) && 
621             password_ok(user,password,pwlen,NULL, user_sess_key)) {
622           endnetgrent();
623           return(user);
624         }
625       }
626     }
627     endnetgrent();
628   }
629 #endif
630   
631 #ifdef HAVE_GETGRNAM 
632   {
633     struct group *gptr = (struct group *)getgrnam(group);
634     char **member;
635     if (gptr)
636       {
637         member = gptr->gr_mem;
638         while (member && *member)
639           {
640             static fstring name;
641             fstrcpy(name,*member);
642             if (user_ok(name,snum) &&
643                 password_ok(name,password,pwlen,NULL, user_sess_key))
644               return(&name[0]);
645             member++;
646           }
647 #ifdef GROUP_CHECK_PWENT
648         {
649           struct passwd *pwd;
650           static fstring tm;
651           
652           setpwent ();
653           while (pwd = getpwent ()) {
654             if (*(pwd->pw_passwd) && pwd->pw_gid == gptr->gr_gid) {
655               /* This Entry have PASSWORD and same GID then check pwd */
656               if (password_ok(NULL, password, pwlen, pwd, user_sess_key)) {
657                 fstrcpy(tm, pwd->pw_name);
658                 endpwent ();
659                 return tm;
660               }
661             }
662           }
663           endpwent ();
664         }
665 #endif /* GROUP_CHECK_PWENT */
666       }
667   }      
668 #endif
669   return(NULL);
670 }
671
672
673
674 /****************************************************************************
675 check for authority to login to a service with a given username/password
676 ****************************************************************************/
677 BOOL authorise_login(int snum,char *user,char *password, int pwlen, 
678                      BOOL *guest,BOOL *force,uint16 vuid)
679 {
680   BOOL ok = False;
681   
682   *guest = False;
683   
684 #if DEBUG_PASSWORD
685   DEBUG(100,("checking authorisation on user=%s pass=%s\n",user,password));
686 #endif
687
688   /* there are several possibilities:
689      1) login as the given user with given password
690      2) login as a previously registered username with the given password
691      3) login as a session list username with the given password
692      4) login as a previously validated user/password pair
693      5) login as the "user =" user with given password
694      6) login as the "user =" user with no password (guest connection)
695      7) login as guest user with no password
696
697      if the service is guest_only then steps 1 to 5 are skipped
698   */
699
700   if (GUEST_ONLY(snum)) *force = True;
701
702   if (!(GUEST_ONLY(snum) && GUEST_OK(snum)))
703     {
704
705       user_struct *vuser = get_valid_user_struct(vuid);
706
707       /* check the given username and password */
708       if (!ok && (*user) && user_ok(user,snum)) {
709         ok = password_ok(user,password, pwlen, NULL, vuser->dc.user_sess_key);
710         if (ok) DEBUG(3,("ACCEPTED: given username password ok\n"));
711       }
712
713       /* check for a previously registered guest username */
714       if (!ok && (vuser != 0) && vuser->guest) {          
715         if (user_ok(vuser->name,snum) &&
716             password_ok(vuser->name, password, pwlen, NULL, vuser->dc.user_sess_key)) {
717           fstrcpy(user, vuser->name);
718           vuser->guest = False;
719           DEBUG(3,("ACCEPTED: given password with registered user %s\n", user));
720           ok = True;
721         }
722       }
723
724
725       /* now check the list of session users */
726     if (!ok)
727     {
728       char *auser;
729       char *user_list = strdup(session_users);
730       if (!user_list) return False;
731
732       for (auser=strtok(user_list,LIST_SEP); 
733            !ok && auser; 
734            auser = strtok(NULL,LIST_SEP))
735       {
736         fstring user2;
737         fstrcpy(user2,auser);
738         if (!user_ok(user2,snum)) continue;
739                   
740         if (password_ok(user2,password, pwlen, NULL, vuser->dc.user_sess_key)) {
741           ok = True;
742           fstrcpy(user,user2);
743           DEBUG(3,("ACCEPTED: session list username and given password ok\n"));
744         }
745       }
746       free(user_list);
747     }
748
749     /* check for a previously validated username/password pair */
750     if (!ok && (!lp_revalidate(snum) || lp_security() > SEC_SHARE) &&
751         (vuser != 0) && !vuser->guest &&
752         user_ok(vuser->name,snum)) {
753       fstrcpy(user,vuser->name);
754       *guest = False;
755       DEBUG(3,("ACCEPTED: validated uid ok as non-guest\n"));
756       ok = True;
757     }
758
759       /* check for a rhosts entry */
760       if (!ok && user_ok(user,snum) && check_hosts_equiv(user)) {
761         ok = True;
762         DEBUG(3,("ACCEPTED: hosts equiv or rhosts entry\n"));
763       }
764
765       /* check the user= fields and the given password */
766       if (!ok && lp_username(snum)) {
767         char *auser;
768         pstring user_list;
769         StrnCpy(user_list,lp_username(snum),sizeof(pstring));
770
771         string_sub(user_list,"%S",lp_servicename(snum));
772           
773         for (auser=strtok(user_list,LIST_SEP);
774              auser && !ok;
775              auser = strtok(NULL,LIST_SEP))
776           {
777             if (*auser == '@')
778               {
779                 auser = validate_group(auser+1,password,pwlen,snum, vuser->dc.user_sess_key);
780                 if (auser)
781                   {
782                     ok = True;
783                     fstrcpy(user,auser);
784                     DEBUG(3,("ACCEPTED: group username and given password ok\n"));
785                   }
786               }
787             else
788               {
789                 fstring user2;
790                 fstrcpy(user2,auser);
791                 if (user_ok(user2,snum) && 
792                     password_ok(user2,password,pwlen,NULL, vuser->dc.user_sess_key))
793                   {
794                     ok = True;
795                     fstrcpy(user,user2);
796                     DEBUG(3,("ACCEPTED: user list username and given password ok\n"));
797                   }
798               }
799           }
800       }      
801     } /* not guest only */
802
803   /* check for a normal guest connection */
804   if (!ok && GUEST_OK(snum))
805     {
806       fstring guestname;
807       StrnCpy(guestname,lp_guestaccount(snum),sizeof(guestname)-1);
808       if (Get_Pwnam(guestname,True))
809         {
810           fstrcpy(user,guestname);
811           ok = True;
812           DEBUG(3,("ACCEPTED: guest account and guest ok\n"));
813         }
814       else
815         DEBUG(0,("Invalid guest account %s??\n",guestname));
816       *guest = True;
817       *force = True;
818     }
819
820   if (ok && !user_ok(user,snum))
821     {
822       DEBUG(0,("rejected invalid user %s\n",user));
823       ok = False;
824     }
825
826   return(ok);
827 }
828
829
830 /****************************************************************************
831 read the a hosts.equiv or .rhosts file and check if it
832 allows this user from this machine
833 ****************************************************************************/
834 static BOOL check_user_equiv(char *user, char *remote, char *equiv_file)
835 {
836   pstring buf;
837   int plus_allowed = 1;
838   char *file_host;
839   char *file_user;
840   FILE *fp = sys_fopen(equiv_file, "r");
841   DEBUG(5, ("check_user_equiv %s %s %s\n", user, remote, equiv_file));
842   if (! fp) return False;
843   while(fgets(buf, sizeof(buf), fp)) 
844   {
845     trim_string(buf," "," ");
846
847     if (buf[0] != '#' && buf[0] != '\n') 
848     {
849       BOOL is_group = False;
850       int plus = 1;
851       char *bp = buf;
852       if (strcmp(buf, "NO_PLUS\n") == 0)
853       {
854         DEBUG(6, ("check_user_equiv NO_PLUS\n"));
855         plus_allowed = 0;
856       }
857       else {
858         if (buf[0] == '+') 
859         {
860           bp++;
861           if (*bp == '\n' && plus_allowed) 
862           {
863             /* a bare plus means everbody allowed */
864             DEBUG(6, ("check_user_equiv everybody allowed\n"));
865             fclose(fp);
866             return True;
867           }
868         }
869         else if (buf[0] == '-')
870         {
871           bp++;
872           plus = 0;
873         }
874         if (*bp == '@') 
875         {
876           is_group = True;
877           bp++;
878         }
879         file_host = strtok(bp, " \t\n");
880         file_user = strtok(NULL, " \t\n");
881         DEBUG(7, ("check_user_equiv %s %s\n", file_host ? file_host : "(null)", 
882                  file_user ? file_user : "(null)" ));
883         if (file_host && *file_host) 
884         {
885           BOOL host_ok = False;
886
887 #if defined(HAVE_NETGROUP) && defined(HAVE_YP_GET_DEFAULT_DOMAIN)
888           if (is_group)
889             {
890               static char *mydomain = NULL;
891               if (!mydomain)
892                 yp_get_default_domain(&mydomain);
893               if (mydomain && innetgr(file_host,remote,user,mydomain))
894                 host_ok = True;
895             }
896 #else
897           if (is_group)
898             {
899               DEBUG(1,("Netgroups not configured\n"));
900               continue;
901             }
902 #endif
903
904           /* is it this host */
905           /* the fact that remote has come from a call of gethostbyaddr
906            * means that it may have the fully qualified domain name
907            * so we could look up the file version to get it into
908            * a canonical form, but I would rather just type it
909            * in full in the equiv file
910            */
911           if (!host_ok && !is_group && strequal(remote, file_host))
912             host_ok = True;
913
914           if (!host_ok)
915             continue;
916
917           /* is it this user */
918           if (file_user == 0 || strequal(user, file_user)) 
919             {
920               fclose(fp);
921               DEBUG(5, ("check_user_equiv matched %s%s %s\n",
922                         (plus ? "+" : "-"), file_host,
923                         (file_user ? file_user : "")));
924               return (plus ? True : False);
925             }
926         }
927       }
928     }
929   }
930   fclose(fp);
931   return False;
932 }
933
934
935 /****************************************************************************
936 check for a possible hosts equiv or rhosts entry for the user
937 ****************************************************************************/
938 BOOL check_hosts_equiv(char *user)
939 {
940   char *fname = NULL;
941   pstring rhostsfile;
942   const struct passwd *pass = Get_Pwnam(user,True);
943
944   if (!pass) 
945     return False;
946
947   fname = lp_hosts_equiv();
948
949   /* note: don't allow hosts.equiv on root */
950   if (fname && *fname && (pass->pw_uid != 0)) {
951           extern int Client;
952           if (check_user_equiv(user,client_name(Client),fname))
953                   return(True);
954   }
955   
956   if (lp_use_rhosts())
957     {
958       char *home = get_home_dir(user);
959       if (home) {
960               extern int Client;
961               slprintf(rhostsfile, sizeof(rhostsfile)-1, "%s/.rhosts", home);
962               if (check_user_equiv(user,client_name(Client),rhostsfile))
963                       return(True);
964       }
965     }
966
967   return False;
968 }
969
970
971 /****************************************************************************
972 return the client state structure
973 ****************************************************************************/
974 struct cli_state *server_client(void)
975 {
976         static struct cli_state pw_cli;
977         return &pw_cli;
978 }
979
980 /****************************************************************************
981 support for server level security 
982 ****************************************************************************/
983 struct cli_state *server_cryptkey(void)
984 {
985         if (cli_connect_serverlist(server_client(), lp_passwordserver()))
986         {
987                 return server_client();
988         }
989         return NULL;
990 }
991
992 /****************************************************************************
993 validate a password with the password server
994 ****************************************************************************/
995 BOOL server_validate(char *user, char *domain, 
996                      char *pass, int passlen,
997                      char *ntpass, int ntpasslen)
998 {
999   struct cli_state *cli;
1000   static unsigned char badpass[24];
1001   static BOOL tested_password_server = False;
1002   static BOOL bad_password_server = False;
1003
1004   cli = server_client();
1005
1006   if (!cli->initialised) {
1007     DEBUG(1,("password server %s is not connected\n", cli->desthost));
1008     return False;
1009   }  
1010
1011   if(badpass[0] == 0)
1012     memset(badpass, 0x1f, sizeof(badpass));
1013
1014   if((passlen == sizeof(badpass)) && !memcmp(badpass, pass, passlen)) {
1015     /* 
1016      * Very unlikely, our random bad password is the same as the users
1017      * password. */
1018     memset(badpass, badpass[0]+1, sizeof(badpass));
1019   }
1020
1021   /*
1022    * Attempt a session setup with a totally incorrect password.
1023    * If this succeeds with the guest bit *NOT* set then the password
1024    * server is broken and is not correctly setting the guest bit. We
1025    * need to detect this as some versions of NT4.x are broken. JRA.
1026    */
1027
1028   if(!tested_password_server) {
1029     if (cli_session_setup(cli, user, (char *)badpass, sizeof(badpass), 
1030                               (char *)badpass, sizeof(badpass), domain)) {
1031
1032       /*
1033        * We connected to the password server so we
1034        * can say we've tested it.
1035        */
1036       tested_password_server = True;
1037
1038       if ((SVAL(cli->inbuf,smb_vwv2) & 1) == 0) {
1039         DEBUG(0,("server_validate: password server %s allows users as non-guest \
1040 with a bad password.\n", cli->desthost));
1041         DEBUG(0,("server_validate: This is broken (and insecure) behaviour. Please do not \
1042 use this machine as the password server.\n"));
1043         cli_ulogoff(cli);
1044
1045         /*
1046          * Password server has the bug.
1047          */
1048         bad_password_server = True;
1049         return False;
1050       }
1051       cli_ulogoff(cli);
1052     }
1053   } else {
1054
1055     /*
1056      * We have already tested the password server.
1057      * Fail immediately if it has the bug.
1058      */
1059
1060     if(bad_password_server) {
1061       DEBUG(0,("server_validate: [1] password server %s allows users as non-guest \
1062 with a bad password.\n", cli->desthost));
1063       DEBUG(0,("server_validate: [1] This is broken (and insecure) behaviour. Please do not \
1064 use this machine as the password server.\n"));
1065       return False;
1066     }
1067   }
1068
1069   /*
1070    * Now we know the password server will correctly set the guest bit, or is
1071    * not guest enabled, we can try with the real password.
1072    */
1073
1074   if (!cli_session_setup(cli, user, pass, passlen, ntpass, ntpasslen, domain)) {
1075     DEBUG(1,("password server %s rejected the password\n", cli->desthost));
1076     return False;
1077   }
1078
1079   /* if logged in as guest then reject */
1080   if ((SVAL(cli->inbuf,smb_vwv2) & 1) != 0) {
1081     DEBUG(1,("password server %s gave us guest only\n", cli->desthost));
1082     cli_ulogoff(cli);
1083     return False;
1084   }
1085
1086
1087   cli_ulogoff(cli);
1088
1089   return(True);
1090 }
1091
1092 /***********************************************************************
1093  Do the same as security=server, but using NT Domain calls and a session
1094  key from the workstation trust account password.
1095 ************************************************************************/
1096
1097 BOOL domain_client_validate( char *user, char *domain, 
1098                              char *smb_apasswd, int smb_apasslen, 
1099                              char *smb_ntpasswd, int smb_ntpasslen)
1100 {
1101         uint16 nt_pipe_fnum;
1102         unsigned char local_challenge[8];
1103         unsigned char local_lm_response[24];
1104         unsigned char local_nt_reponse[24];
1105         unsigned char trust_passwd[16];
1106         NET_ID_INFO_CTR ctr;
1107         NET_USER_INFO_3 info3;
1108         struct cli_state cli;
1109         uint32 smb_uid_low;
1110
1111         /* 
1112         * Check that the requested domain is not our own machine name.
1113         * If it is, we should never check the PDC here, we use our own local
1114         * password file.
1115         */
1116
1117         if(strequal( domain, global_myname))
1118         {
1119                 DEBUG(3,("domain_client_validate: Requested domain was for this machine.\n"));
1120                 return False;
1121         }
1122
1123         /*
1124         * Next, check that the passwords given were encrypted.
1125         */
1126
1127         if(((smb_apasslen  != 24) && (smb_apasslen  != 0)) || 
1128            ((smb_ntpasslen != 24) && (smb_ntpasslen != 0)))
1129         {
1130                 /*
1131                  * Not encrypted - do so.
1132                  */
1133
1134                 DEBUG(3,("domain_client_validate: User passwords not in encrypted format.\n"));
1135                 generate_random_buffer( local_challenge, 8, False);
1136                 SMBencrypt( (uchar *)smb_apasswd, local_challenge, local_lm_response);
1137                 SMBNTencrypt((uchar *)smb_ntpasswd, local_challenge, local_nt_reponse);
1138                 smb_apasslen = 24;
1139                 smb_ntpasslen = 24;
1140                 smb_apasswd = (char *)local_lm_response;
1141                 smb_ntpasswd = (char *)local_nt_reponse;
1142         }
1143         else
1144         {
1145                 /*
1146                  * Encrypted - get the challenge we sent for these
1147                  * responses.
1148                  */
1149
1150                 if (!last_challenge(local_challenge))
1151                 {
1152                         DEBUG(0,("domain_client_validate: no challenge done - password failed\n"));
1153                         return False;
1154                 }
1155         }
1156
1157         /*
1158          * Get the workstation trust account password.
1159          */
1160         if (!trust_get_passwd( trust_passwd, global_myworkgroup, global_myname))
1161         {
1162                 return False;
1163         }
1164
1165         /*
1166          * At this point, smb_apasswd points to the lanman response to
1167          * the challenge in local_challenge, and smb_ntpasswd points to
1168          * the NT response to the challenge in local_challenge. Ship
1169          * these over the secure channel to a domain controller and
1170          * see if they were valid.
1171          */
1172
1173         if (!cli_connect_serverlist(&cli, lp_passwordserver()))
1174         {
1175                 DEBUG(0,("domain_client_validate: Domain password server not available.\n"));
1176                 return False;
1177         }
1178
1179         /*
1180         * Ok - we have an anonymous connection to the IPC$ share.
1181         * Now start the NT Domain stuff :-).
1182         */
1183
1184         if(cli_nt_session_open(&cli, PIPE_NETLOGON, &nt_pipe_fnum) == False) {
1185         DEBUG(0,("domain_client_validate: unable to open the domain client session to \
1186         machine %s. Error was : %s.\n", cli.desthost, cli_errstr(&cli)));
1187         cli_nt_session_close(&cli, nt_pipe_fnum);
1188         cli_ulogoff(&cli);
1189         cli_shutdown(&cli);
1190         return False; 
1191         }
1192
1193         if(cli_nt_setup_creds(&cli, nt_pipe_fnum,
1194            cli.mach_acct, global_myname, trust_passwd, SEC_CHAN_WKSTA) == False)
1195         {
1196                 DEBUG(0,("domain_client_validate: unable to setup the PDC credentials to machine \
1197                 %s. Error was : %s.\n", cli.desthost, cli_errstr(&cli)));
1198                 cli_nt_session_close(&cli, nt_pipe_fnum);
1199                 cli_ulogoff(&cli);
1200                 cli_shutdown(&cli);
1201                 return False;
1202         }
1203
1204         /* We really don't care what LUID we give the user. */
1205         generate_random_buffer( (unsigned char *)&smb_uid_low, 4, False);
1206
1207         if (!cli_nt_login_network(&cli, nt_pipe_fnum, domain, user, smb_uid_low, (char *)local_challenge,
1208         ((smb_apasslen != 0) ? smb_apasswd : NULL),
1209         ((smb_ntpasslen != 0) ? smb_ntpasswd : NULL),
1210         &ctr, &info3))
1211         {
1212                 DEBUG(0,("domain_client_validate: unable to validate password for user %s in domain \
1213                 %s to Domain controller %s. Error was %s.\n", user, domain, cli.desthost, cli_errstr(&cli)));
1214                 cli_nt_session_close(&cli, nt_pipe_fnum);
1215                 cli_ulogoff(&cli);
1216                 cli_shutdown(&cli);
1217                 return False;
1218         }
1219
1220         /*
1221          * Here, if we really want it, we have lots of info about the user in info3.
1222          * LKCLXXXX - really important to check things like "is this user acct
1223          * locked out / disabled" etc!!!!
1224          */
1225
1226 #if 0
1227         /* 
1228         * We don't actually need to do this - plus it fails currently with
1229         * NT_STATUS_INVALID_INFO_CLASS - we need to know *exactly* what to
1230         * send here. JRA.
1231         */
1232
1233         if (!cli_nt_logoff(&cli, nt_pipe_fnum, &ctr))
1234         {
1235                 DEBUG(0,("domain_client_validate: unable to log off user %s in domain \
1236                 %s to Domain controller %s. Error was %s.\n", user, domain, cli.desthost, cli_errstr(&cli)));        
1237                 cli_nt_session_close(&cli, nt_pipe_fnum);
1238                 cli_ulogoff(&cli);
1239                 cli_shutdown(&cli);
1240                 return False;
1241         }
1242 #endif /* 0 */
1243
1244         cli_nt_session_close(&cli, nt_pipe_fnum);
1245         cli_ulogoff(&cli);
1246         cli_shutdown(&cli);
1247         return True;
1248 }