!pass -> pass != NULL is wrong: !pass -> pass == NULL is correct. oops.
[samba.git] / source / 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 Setup the groups a user belongs to.
155 ****************************************************************************/
156 int setup_groups(char *user, uid_t uid, gid_t gid, int *p_ngroups, gid_t **p_groups)
157 {
158         int i,ngroups;
159         gid_t grp = 0;
160         gid_t *groups = NULL;
161
162         if (-1 == initgroups(user,gid))
163         {
164                 if (getuid() == 0)
165                 {
166                         DEBUG(0,("Unable to initgroups!\n"));
167                         if (gid < 0 || gid > 16000 || uid < 0 || uid > 16000)
168                         {
169                                 DEBUG(0,("This is probably a problem with the account %s\n", user));
170                         }
171                 }
172                 return -1;
173         }
174
175         ngroups = sys_getgroups(0,&grp);
176         if (ngroups <= 0)
177         {
178                 ngroups = 32;
179         }
180
181         if((groups = (gid_t *)malloc(sizeof(gid_t)*ngroups)) == NULL)
182         {
183                 DEBUG(0,("setup_groups malloc fail !\n"));
184                 return -1;
185         }
186
187         ngroups = sys_getgroups(ngroups,groups);
188
189         (*p_ngroups) = ngroups;
190         (*p_groups) = groups;
191
192         DEBUG( 3, ( "%s is in %d groups: ", user, ngroups ) );
193         for (i = 0; i < ngroups; i++ )
194         {
195                 DEBUG( 3, ( "%s%d", (i ? ", " : ""), (int)groups[i] ) );
196         }
197         DEBUG( 3, ( "\n" ) );
198
199         return 0;
200 }
201
202
203 /****************************************************************************
204 register a uid/name pair as being valid and that a valid password
205 has been given. vuid is biased by an offset. This allows us to
206 tell random client vuid's (normally zero) from valid vuids.
207 ****************************************************************************/
208 uint16 register_vuid(uid_t uid,gid_t gid, char *unix_name, char *requested_name, BOOL guest)
209 {
210   user_struct *vuser;
211   struct passwd *pwfile; /* for getting real name from passwd file */
212
213   /* Ensure no vuid gets registered in share level security. */
214   if(lp_security() == SEC_SHARE)
215     return UID_FIELD_INVALID;
216
217 #if 0
218   /*
219    * After observing MS-Exchange services writing to a Samba share
220    * I belive this code is incorrect. Each service does its own
221    * sessionsetup_and_X for the same user, and as each service shuts
222    * down, it does a user_logoff_and_X. As we are consolidating multiple
223    * sessionsetup_and_X's onto the same vuid here, when the first service
224    * shuts down, it invalidates all the open files for the other services.
225    * Hence I am removing this code and forcing each sessionsetup_and_X
226    * to get a new vuid.
227    * Jeremy Allison. (jallison@whistle.com).
228    */
229
230   int i;
231   for(i = 0; i < num_validated_users; i++) {
232     vuser = &validated_users[i];
233     if ( vuser->uid == uid )
234       return (uint16)(i + VUID_OFFSET); /* User already validated */
235   }
236 #endif
237
238   validated_users = (user_struct *)Realloc(validated_users,
239                            sizeof(user_struct)*
240                            (num_validated_users+1));
241   
242   if (!validated_users)
243     {
244       DEBUG(0,("Failed to realloc users struct!\n"));
245       num_validated_users = 0;
246       return UID_FIELD_INVALID;
247     }
248
249   vuser = &validated_users[num_validated_users];
250   num_validated_users++;
251
252   vuser->uid = uid;
253   vuser->gid = gid;
254   vuser->guest = guest;
255   fstrcpy(vuser->name,unix_name);
256   fstrcpy(vuser->requested_name,requested_name);
257
258   vuser->n_sids = 0;
259   vuser->sids   = NULL;
260
261   vuser->n_groups = 0;
262   vuser->groups  = NULL;
263
264   /* Find all the groups this uid is in and store them. 
265      Used by become_user() */
266   setup_groups(unix_name,uid,gid,
267                &vuser->n_groups,
268                &vuser->groups);
269
270   DEBUG(3,("uid %d registered to name %s\n",(int)uid,unix_name));
271
272   DEBUG(3, ("Clearing default real name\n"));
273   fstrcpy(vuser->real_name, "<Full Name>\0");
274   if (lp_unix_realname()) {
275     if ((pwfile=getpwnam(vuser->name))!= NULL)
276       {
277       DEBUG(3, ("User name: %s\tReal name: %s\n",vuser->name,pwfile->pw_gecos));
278       fstrcpy(vuser->real_name, pwfile->pw_gecos);
279       }
280   }
281
282   return (uint16)((num_validated_users - 1) + VUID_OFFSET);
283 }
284
285
286 /****************************************************************************
287 add a name to the session users list
288 ****************************************************************************/
289 void add_session_user(char *user)
290 {
291   fstring suser;
292   StrnCpy(suser,user,sizeof(suser)-1);
293
294   if (!Get_Pwnam(suser,True)) return;
295
296   if (suser && *suser && !in_list(suser,session_users,False))
297     {
298       if (strlen(suser) + strlen(session_users) + 2 >= sizeof(pstring))
299         DEBUG(1,("Too many session users??\n"));
300       else
301         {
302           pstrcat(session_users," ");
303           pstrcat(session_users,suser);
304         }
305     }
306 }
307
308
309 /****************************************************************************
310 update the encrypted smbpasswd file from the plaintext username and password
311 *****************************************************************************/
312 static BOOL update_smbpassword_file(char *user, char *password)
313 {
314         struct smb_passwd *smbpw;
315         BOOL ret;
316         
317         become_root(0);
318         smbpw = getsmbpwnam(user);
319         unbecome_root(0);
320         
321         if(smbpw == NULL) {
322                 DEBUG(0,("getsmbpwnam returned NULL\n"));
323                 return False;
324         }
325  
326         /* Here, the flag is one, because we want to ignore the
327            XXXXXXX'd out password */
328         ret = change_oem_password( smbpw, password, True);
329         if (ret == False) {
330                 DEBUG(3,("change_oem_password returned False\n"));
331         }
332
333         return ret;
334 }
335
336
337
338
339
340 /****************************************************************************
341 core of smb password checking routine.
342 ****************************************************************************/
343 BOOL smb_password_check(char *password, unsigned char *part_passwd, unsigned char *c8)
344 {
345   /* Finish the encryption of part_passwd. */
346   unsigned char p21[21];
347   unsigned char p24[24];
348
349   if (part_passwd == NULL)
350     DEBUG(10,("No password set - allowing access\n"));
351   /* No password set - always true ! */
352   if (part_passwd == NULL)
353     return 1;
354
355   memset(p21,'\0',21);
356   memcpy(p21,part_passwd,16);
357   E_P24(p21, c8, p24);
358 #if DEBUG_PASSWORD
359   {
360     int i;
361     DEBUG(100,("Part password (P16) was |"));
362     for(i = 0; i < 16; i++)
363       DEBUG(100,("%X ", (unsigned char)part_passwd[i]));
364     DEBUG(100,("|\n"));
365     DEBUG(100,("Password from client was |"));
366     for(i = 0; i < 24; i++)
367       DEBUG(100,("%X ", (unsigned char)password[i]));
368     DEBUG(100,("|\n"));
369     DEBUG(100,("Given challenge was |"));
370     for(i = 0; i < 8; i++)
371       DEBUG(100,("%X ", (unsigned char)c8[i]));
372     DEBUG(100,("|\n"));
373     DEBUG(100,("Value from encryption was |"));
374     for(i = 0; i < 24; i++)
375       DEBUG(100,("%X ", (unsigned char)p24[i]));
376     DEBUG(100,("|\n"));
377   }
378 #endif
379   return (memcmp(p24, password, 24) == 0);
380 }
381
382 /****************************************************************************
383  Do a specific test for an smb password being correct, given a smb_password and
384  the lanman and NT responses.
385 ****************************************************************************/
386
387 BOOL smb_password_ok(struct smb_passwd *smb_pass,
388                      uchar lm_pass[24], uchar nt_pass[24])
389 {
390         uchar challenge[8];
391
392         if (!lm_pass || !smb_pass) return(False);
393
394         DEBUG(4,("Checking SMB password for user %s\n", 
395                  smb_pass->smb_name));
396
397         if(smb_pass->acct_ctrl & ACB_DISABLED) {
398                 DEBUG(3,("account for user %s was disabled.\n", 
399                          smb_pass->smb_name));
400                 return(False);
401         }
402
403         if (!last_challenge(challenge)) {
404                 DEBUG(1,("no challenge done - password failed\n"));
405                 return False;
406         }
407
408         if ((Protocol >= PROTOCOL_NT1) && (smb_pass->smb_nt_passwd != NULL)) {
409                 /* We have the NT MD4 hash challenge available - see if we can
410                    use it (ie. does it exist in the smbpasswd file).
411                 */
412                 DEBUG(4,("smb_password_ok: Checking NT MD4 password\n"));
413                 if (smb_password_check((char *)nt_pass, 
414                                        (uchar *)smb_pass->smb_nt_passwd, 
415                                        challenge)) {
416                         DEBUG(4,("NT MD4 password check succeeded\n"));
417                         return(True);
418                 }
419                 DEBUG(4,("NT MD4 password check failed\n"));
420         }
421
422         /* Try against the lanman password. smb_pass->smb_passwd == NULL means
423            no password, allow access. */
424
425         DEBUG(4,("Checking LM MD4 password\n"));
426
427         if((smb_pass->smb_passwd == NULL) && 
428            (smb_pass->acct_ctrl & ACB_PWNOTREQ)) {
429                 DEBUG(4,("no password required for user %s\n",
430                          smb_pass->smb_name));
431                 return True;
432         }
433
434         if((smb_pass->smb_passwd != NULL) && 
435            smb_password_check((char *)lm_pass, 
436                               (uchar *)smb_pass->smb_passwd, challenge)) {
437                 DEBUG(4,("LM MD4 password check succeeded\n"));
438                 return(True);
439         }
440
441         DEBUG(4,("LM MD4 password check failed\n"));
442
443         return False;
444 }
445
446
447 /****************************************************************************
448 check if a username/password is OK assuming the password is a 24 byte
449 SMB hash
450 return True if the password is correct, False otherwise
451 ****************************************************************************/
452 BOOL pass_check_smb(char *user, char *domain,
453                 char *challenge, char *lm_pwd, char *nt_pwd,
454                 struct passwd *pwd)
455 {
456         struct passwd *pass;
457         struct smb_passwd *smb_pass;
458
459         if (!lm_pwd || !nt_pwd)
460         {
461                 return(False);
462         }
463
464         if (pwd != NULL && user == NULL)
465         {
466                 pass = (struct passwd *) pwd;
467                 user = pass->pw_name;
468         }
469         else
470         {
471                 pass = Get_Pwnam(user,True);
472         }
473
474         if (pass == NULL)
475         {
476                 DEBUG(3,("Couldn't find user %s\n",user));
477                 return(False);
478         }
479
480         smb_pass = getsmbpwnam(user);
481
482         if (smb_pass == NULL)
483         {
484                 DEBUG(3,("Couldn't find user %s in smb_passwd file.\n", user));
485                 return(False);
486         }
487
488         /* Quit if the account was disabled. */
489         if(smb_pass->acct_ctrl & ACB_DISABLED) {
490                 DEBUG(3,("account for user %s was disabled.\n", user));
491                 return(False);
492         }
493
494         /* Ensure the uid's match */
495         if (smb_pass->smb_userid != pass->pw_uid)
496         {
497                 DEBUG(3,("Error : UNIX and SMB uids in password files do not match !\n"));
498                 return(False);
499         }
500
501         if (lm_pwd[0] == '\0' && IS_BITS_SET_ALL(smb_pass->acct_ctrl, ACB_PWNOTREQ) && lp_null_passwords())
502         {
503                 DEBUG(3,("account for user %s has no password and null passwords are allowed.\n", smb_pass->smb_name));
504                 return(True);
505         }
506
507         if (smb_password_ok(smb_pass, (uchar *)lm_pwd, (uchar *)nt_pwd))
508         {
509                 return(True);
510         }
511         
512         DEBUG(3,("Error smb_password_check failed\n"));
513         return False;
514 }
515
516 /****************************************************************************
517 check if a username/password pair is OK either via the system password
518 database or the encrypted SMB password database
519 return True if the password is correct, False otherwise
520 ****************************************************************************/
521 BOOL password_ok(char *user, char *password, int pwlen, struct passwd *pwd)
522 {
523         if (pwlen == 24 || (lp_encrypted_passwords() && (pwlen == 0) && lp_null_passwords()))
524         {
525                 /* if 24 bytes long assume it is an encrypted password */
526                 uchar challenge[8];
527
528                 if (!last_challenge(challenge))
529                 {
530                         DEBUG(0,("Error: challenge not done for user=%s\n", user));
531                         return False;
532                 }
533
534                 return pass_check_smb(user, global_myworkgroup,
535                                       challenge, password, password, pwd);
536         } 
537
538         return pass_check(user, password, pwlen, pwd, 
539                           lp_update_encrypted() ? 
540                           update_smbpassword_file : NULL);
541 }
542
543 /****************************************************************************
544 check if a username is valid
545 ****************************************************************************/
546 BOOL user_ok(char *user,int snum)
547 {
548         pstring valid, invalid;
549         BOOL ret;
550
551         StrnCpy(valid, lp_valid_users(snum), sizeof(pstring));
552         StrnCpy(invalid, lp_invalid_users(snum), sizeof(pstring));
553
554         string_sub(valid,"%S",lp_servicename(snum));
555         string_sub(invalid,"%S",lp_servicename(snum));
556         
557         ret = !user_in_list(user,invalid);
558         
559         if (ret && valid && *valid) {
560                 ret = user_in_list(user,valid);
561         }
562
563         if (ret && lp_onlyuser(snum)) {
564                 char *user_list = lp_username(snum);
565                 string_sub(user_list,"%S",lp_servicename(snum));
566                 ret = user_in_list(user,user_list);
567         }
568
569         return(ret);
570 }
571
572
573
574
575 /****************************************************************************
576 validate a group username entry. Return the username or NULL
577 ****************************************************************************/
578 static char *validate_group(char *group,char *password,int pwlen,int snum)
579 {
580 #ifdef HAVE_NETGROUP
581   {
582     char *host, *user, *domain;
583     setnetgrent(group);
584     while (getnetgrent(&host, &user, &domain)) {
585       if (user) {
586         if (user_ok(user, snum) && 
587             password_ok(user,password,pwlen,NULL)) {
588           endnetgrent();
589           return(user);
590         }
591       }
592     }
593     endnetgrent();
594   }
595 #endif
596   
597 #ifdef HAVE_GETGRNAM 
598   {
599     struct group *gptr = (struct group *)getgrnam(group);
600     char **member;
601     if (gptr)
602       {
603         member = gptr->gr_mem;
604         while (member && *member)
605           {
606             static fstring name;
607             fstrcpy(name,*member);
608             if (user_ok(name,snum) &&
609                 password_ok(name,password,pwlen,NULL))
610               return(&name[0]);
611             member++;
612           }
613 #ifdef GROUP_CHECK_PWENT
614         {
615           struct passwd *pwd;
616           static fstring tm;
617           
618           setpwent ();
619           while (pwd = getpwent ()) {
620             if (*(pwd->pw_passwd) && pwd->pw_gid == gptr->gr_gid) {
621               /* This Entry have PASSWORD and same GID then check pwd */
622               if (password_ok(NULL, password, pwlen, pwd)) {
623                 fstrcpy(tm, pwd->pw_name);
624                 endpwent ();
625                 return tm;
626               }
627             }
628           }
629           endpwent ();
630         }
631 #endif /* GROUP_CHECK_PWENT */
632       }
633   }      
634 #endif
635   return(NULL);
636 }
637
638
639
640 /****************************************************************************
641 check for authority to login to a service with a given username/password
642 ****************************************************************************/
643 BOOL authorise_login(int snum,char *user,char *password, int pwlen, 
644                      BOOL *guest,BOOL *force,uint16 vuid)
645 {
646   BOOL ok = False;
647   
648   *guest = False;
649   
650 #if DEBUG_PASSWORD
651   DEBUG(100,("checking authorisation on user=%s pass=%s\n",user,password));
652 #endif
653
654   /* there are several possibilities:
655      1) login as the given user with given password
656      2) login as a previously registered username with the given password
657      3) login as a session list username with the given password
658      4) login as a previously validated user/password pair
659      5) login as the "user =" user with given password
660      6) login as the "user =" user with no password (guest connection)
661      7) login as guest user with no password
662
663      if the service is guest_only then steps 1 to 5 are skipped
664   */
665
666   if (GUEST_ONLY(snum)) *force = True;
667
668   if (!(GUEST_ONLY(snum) && GUEST_OK(snum)))
669     {
670
671       user_struct *vuser = get_valid_user_struct(vuid);
672
673       /* check the given username and password */
674       if (!ok && (*user) && user_ok(user,snum)) {
675         ok = password_ok(user,password, pwlen, NULL);
676         if (ok) DEBUG(3,("ACCEPTED: given username password ok\n"));
677       }
678
679       /* check for a previously registered guest username */
680       if (!ok && (vuser != 0) && vuser->guest) {          
681         if (user_ok(vuser->name,snum) &&
682             password_ok(vuser->name, password, pwlen, NULL)) {
683           fstrcpy(user, vuser->name);
684           vuser->guest = False;
685           DEBUG(3,("ACCEPTED: given password with registered user %s\n", user));
686           ok = True;
687         }
688       }
689
690
691       /* now check the list of session users */
692     if (!ok)
693     {
694       char *auser;
695       char *user_list = strdup(session_users);
696       if (!user_list) return(False);
697
698       for (auser=strtok(user_list,LIST_SEP); 
699            !ok && auser; 
700            auser = strtok(NULL,LIST_SEP))
701       {
702         fstring user2;
703         fstrcpy(user2,auser);
704         if (!user_ok(user2,snum)) continue;
705                   
706         if (password_ok(user2,password, pwlen, NULL)) {
707           ok = True;
708           fstrcpy(user,user2);
709           DEBUG(3,("ACCEPTED: session list username and given password ok\n"));
710         }
711       }
712       free(user_list);
713     }
714
715     /* check for a previously validated username/password pair */
716     if (!ok && (!lp_revalidate(snum) || lp_security() > SEC_SHARE) &&
717         (vuser != 0) && !vuser->guest &&
718         user_ok(vuser->name,snum)) {
719       fstrcpy(user,vuser->name);
720       *guest = False;
721       DEBUG(3,("ACCEPTED: validated uid ok as non-guest\n"));
722       ok = True;
723     }
724
725       /* check for a rhosts entry */
726       if (!ok && user_ok(user,snum) && check_hosts_equiv(user)) {
727         ok = True;
728         DEBUG(3,("ACCEPTED: hosts equiv or rhosts entry\n"));
729       }
730
731       /* check the user= fields and the given password */
732       if (!ok && lp_username(snum)) {
733         char *auser;
734         pstring user_list;
735         StrnCpy(user_list,lp_username(snum),sizeof(pstring));
736
737         string_sub(user_list,"%S",lp_servicename(snum));
738           
739         for (auser=strtok(user_list,LIST_SEP);
740              auser && !ok;
741              auser = strtok(NULL,LIST_SEP))
742           {
743             if (*auser == '@')
744               {
745                 auser = validate_group(auser+1,password,pwlen,snum);
746                 if (auser)
747                   {
748                     ok = True;
749                     fstrcpy(user,auser);
750                     DEBUG(3,("ACCEPTED: group username and given password ok\n"));
751                   }
752               }
753             else
754               {
755                 fstring user2;
756                 fstrcpy(user2,auser);
757                 if (user_ok(user2,snum) && 
758                     password_ok(user2,password,pwlen,NULL))
759                   {
760                     ok = True;
761                     fstrcpy(user,user2);
762                     DEBUG(3,("ACCEPTED: user list username and given password ok\n"));
763                   }
764               }
765           }
766       }      
767     } /* not guest only */
768
769   /* check for a normal guest connection */
770   if (!ok && GUEST_OK(snum))
771     {
772       fstring guestname;
773       StrnCpy(guestname,lp_guestaccount(snum),sizeof(guestname)-1);
774       if (Get_Pwnam(guestname,True))
775         {
776           fstrcpy(user,guestname);
777           ok = True;
778           DEBUG(3,("ACCEPTED: guest account and guest ok\n"));
779         }
780       else
781         DEBUG(0,("Invalid guest account %s??\n",guestname));
782       *guest = True;
783       *force = True;
784     }
785
786   if (ok && !user_ok(user,snum))
787     {
788       DEBUG(0,("rejected invalid user %s\n",user));
789       ok = False;
790     }
791
792   return(ok);
793 }
794
795
796 /****************************************************************************
797 read the a hosts.equiv or .rhosts file and check if it
798 allows this user from this machine
799 ****************************************************************************/
800 static BOOL check_user_equiv(char *user, char *remote, char *equiv_file)
801 {
802   pstring buf;
803   int plus_allowed = 1;
804   char *file_host;
805   char *file_user;
806   FILE *fp = fopen(equiv_file, "r");
807   DEBUG(5, ("check_user_equiv %s %s %s\n", user, remote, equiv_file));
808   if (! fp) return False;
809   while(fgets(buf, sizeof(buf), fp)) 
810   {
811     trim_string(buf," "," ");
812
813     if (buf[0] != '#' && buf[0] != '\n') 
814     {
815       BOOL is_group = False;
816       int plus = 1;
817       char *bp = buf;
818       if (strcmp(buf, "NO_PLUS\n") == 0)
819       {
820         DEBUG(6, ("check_user_equiv NO_PLUS\n"));
821         plus_allowed = 0;
822       }
823       else {
824         if (buf[0] == '+') 
825         {
826           bp++;
827           if (*bp == '\n' && plus_allowed) 
828           {
829             /* a bare plus means everbody allowed */
830             DEBUG(6, ("check_user_equiv everybody allowed\n"));
831             fclose(fp);
832             return True;
833           }
834         }
835         else if (buf[0] == '-')
836         {
837           bp++;
838           plus = 0;
839         }
840         if (*bp == '@') 
841         {
842           is_group = True;
843           bp++;
844         }
845         file_host = strtok(bp, " \t\n");
846         file_user = strtok(NULL, " \t\n");
847         DEBUG(7, ("check_user_equiv %s %s\n", file_host ? file_host : "(null)", 
848                  file_user ? file_user : "(null)" ));
849         if (file_host && *file_host) 
850         {
851           BOOL host_ok = False;
852
853 #if defined(HAVE_NETGROUP) && defined(HAVE_YP_GET_DEFAULT_DOMAIN)
854           if (is_group)
855             {
856               static char *mydomain = NULL;
857               if (!mydomain)
858                 yp_get_default_domain(&mydomain);
859               if (mydomain && innetgr(file_host,remote,user,mydomain))
860                 host_ok = True;
861             }
862 #else
863           if (is_group)
864             {
865               DEBUG(1,("Netgroups not configured\n"));
866               continue;
867             }
868 #endif
869
870           /* is it this host */
871           /* the fact that remote has come from a call of gethostbyaddr
872            * means that it may have the fully qualified domain name
873            * so we could look up the file version to get it into
874            * a canonical form, but I would rather just type it
875            * in full in the equiv file
876            */
877           if (!host_ok && !is_group && strequal(remote, file_host))
878             host_ok = True;
879
880           if (!host_ok)
881             continue;
882
883           /* is it this user */
884           if (file_user == 0 || strequal(user, file_user)) 
885             {
886               fclose(fp);
887               DEBUG(5, ("check_user_equiv matched %s%s %s\n",
888                         (plus ? "+" : "-"), file_host,
889                         (file_user ? file_user : "")));
890               return (plus ? True : False);
891             }
892         }
893       }
894     }
895   }
896   fclose(fp);
897   return False;
898 }
899
900
901 /****************************************************************************
902 check for a possible hosts equiv or rhosts entry for the user
903 ****************************************************************************/
904 BOOL check_hosts_equiv(char *user)
905 {
906   char *fname = NULL;
907   pstring rhostsfile;
908   struct passwd *pass = Get_Pwnam(user,True);
909
910   if (!pass) 
911     return(False);
912
913   fname = lp_hosts_equiv();
914
915   /* note: don't allow hosts.equiv on root */
916   if (fname && *fname && (pass->pw_uid != 0)) {
917           extern int Client;
918           if (check_user_equiv(user,client_name(Client),fname))
919                   return(True);
920   }
921   
922   if (lp_use_rhosts())
923     {
924       char *home = get_home_dir(user);
925       if (home) {
926               extern int Client;
927               slprintf(rhostsfile, sizeof(rhostsfile)-1, "%s/.rhosts", home);
928               if (check_user_equiv(user,client_name(Client),rhostsfile))
929                       return(True);
930       }
931     }
932
933   return(False);
934 }
935
936
937 /****************************************************************************
938 return the client state structure
939 ****************************************************************************/
940 struct cli_state *server_client(void)
941 {
942         static struct cli_state pw_cli;
943         return &pw_cli;
944 }
945
946 /****************************************************************************
947 support for server level security 
948 ****************************************************************************/
949 struct cli_state *server_cryptkey(void)
950 {
951         struct cli_state *cli;
952         fstring desthost;
953         struct in_addr dest_ip;
954         extern fstring local_machine;
955         char *p;
956         BOOL connected_ok = False;
957         struct nmb_name calling, called;
958
959         cli = server_client();
960
961         if (!cli_initialise(cli))
962                 return NULL;
963
964         p = lp_passwordserver();
965         while(p && next_token( &p, desthost, LIST_SEP, sizeof(desthost))) {
966                 standard_sub_basic(desthost);
967                 strupper(desthost);
968
969                 if(!resolve_name( desthost, &dest_ip, 0x20)) {
970                         DEBUG(1,("server_cryptkey: Can't resolve address for %s\n",desthost));
971                         continue;
972                 }
973
974                 if (ismyip(dest_ip)) {
975                         DEBUG(1,("Password server loop - disabling password server %s\n",desthost));
976                         continue;
977                 }
978
979                 if (cli_connect(cli, desthost, &dest_ip)) {
980                         DEBUG(3,("connected to password server %s\n",desthost));
981                         connected_ok = True;
982                         break;
983                 }
984         }
985
986         if (!connected_ok) {
987                 DEBUG(0,("password server not available\n"));
988                 cli_shutdown(cli);
989                 return NULL;
990         }
991
992         make_nmb_name(&calling, local_machine, 0x0 , scope);
993         make_nmb_name(&called , desthost     , 0x20, scope);
994
995         if (!cli_session_request(cli, &calling, &called))
996         {
997                 DEBUG(1,("%s rejected the session\n",desthost));
998                 cli_shutdown(cli);
999                 return NULL;
1000         }
1001
1002         DEBUG(3,("got session\n"));
1003
1004         if (!cli_negprot(cli)) {
1005                 DEBUG(1,("%s rejected the negprot\n",desthost));
1006                 cli_shutdown(cli);
1007                 return NULL;
1008         }
1009
1010         if (cli->protocol < PROTOCOL_LANMAN2 ||
1011             !(cli->sec_mode & 1)) {
1012                 DEBUG(1,("%s isn't in user level security mode\n",desthost));
1013                 cli_shutdown(cli);
1014                 return NULL;
1015         }
1016
1017         DEBUG(3,("password server OK\n"));
1018
1019         return cli;
1020 }
1021
1022 /****************************************************************************
1023 validate a password with the password server
1024 ****************************************************************************/
1025 BOOL server_validate(char *user, char *domain, 
1026                      char *pass, int passlen,
1027                      char *ntpass, int ntpasslen)
1028 {
1029         struct cli_state *cli;
1030         extern fstring local_machine;
1031         static unsigned char badpass[24];
1032         cli = server_client();
1033
1034         if (!cli->initialised) {
1035                 DEBUG(1,("password server %s is not connected\n", cli->desthost));
1036                 return(False);
1037         }  
1038
1039         if(badpass[0] == 0) {
1040           memset(badpass, 0x1f, sizeof(badpass));
1041         }
1042
1043         if((passlen == sizeof(badpass)) && !memcmp(badpass, pass, passlen)) {
1044           /* Very unlikely, our random bad password is the same as the users
1045              password. */
1046           memset(badpass, badpass[0]+1, sizeof(badpass));
1047         }
1048
1049         /*
1050          * Attempt a session setup with a totally incorrect password.
1051          * If this succeeds with the guest bit *NOT* set then the password
1052          * server is broken and is not correctly setting the guest bit. We
1053          * need to detect this as some versions of NT4.x are broken. JRA.
1054          */
1055
1056         if (cli_session_setup(cli, user, (char *)badpass, sizeof(badpass), 
1057                               (char *)badpass, sizeof(badpass), domain)) {
1058           if ((SVAL(cli->inbuf,smb_vwv2) & 1) == 0) {
1059             DEBUG(0,("server_validate: password server %s allows users as non-guest \
1060 with a bad password.\n", cli->desthost));
1061             DEBUG(0,("server_validate: This is broken (and insecure) behaviour. Please do not \
1062 use this machine as the password server.\n"));
1063             cli_ulogoff(cli);
1064             return False;
1065           }
1066           cli_ulogoff(cli);
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          * This patch from Rob Nielsen <ran@adc.com> makes doing
1088          * the NetWksaUserLogon a dynamic, rather than compile-time
1089          * parameter, defaulting to on. This is somewhat dangerous
1090          * as it allows people to turn off this neccessary check,
1091          * but so many people have had problems with this that I
1092          * think it is a neccessary change. JRA.
1093          */
1094
1095         if (lp_net_wksta_user_logon()) {
1096                 DEBUG(3,("trying NetWkstaUserLogon with password server %s\n", cli->desthost));
1097
1098                 if (!cli_send_tconX(cli, "IPC$", "IPC", "", 1)) {
1099                         DEBUG(0,("password server %s refused IPC$ connect\n", cli->desthost));
1100                         cli_ulogoff(cli);
1101                         return False;
1102                 }
1103
1104                 if (!cli_NetWkstaUserLogon(cli,user,local_machine)) {
1105                         DEBUG(0,("password server %s failed NetWkstaUserLogon\n", cli->desthost));
1106                         cli_tdis(cli);
1107                         cli_ulogoff(cli);
1108                         return False;
1109                 }
1110
1111                 if (cli->privilages == 0) {
1112                         DEBUG(0,("password server %s gave guest privilages\n", cli->desthost));
1113                         cli_tdis(cli);
1114                         cli_ulogoff(cli);
1115                         return False;
1116                 }
1117
1118                 if (!strequal(cli->eff_name, user)) {
1119                         DEBUG(0,("password server %s gave different username %s\n", 
1120                                 cli->desthost,
1121                                 cli->eff_name));
1122                         cli_tdis(cli);
1123                         cli_ulogoff(cli);
1124                         return False;
1125                 }
1126                 cli_tdis(cli);
1127         }
1128         else {
1129                 DEBUG(3,("skipping NetWkstaUserLogon with password server %s\n", cli->desthost));
1130         }
1131
1132         DEBUG(3,("password server %s accepted the password\n", cli->desthost));
1133
1134         cli_ulogoff(cli);
1135
1136         return(True);
1137 }
1138
1139 /***********************************************************************
1140  Do the same as security=server, but using NT Domain calls and a session
1141  key from the machine password.
1142 ************************************************************************/
1143
1144 BOOL domain_client_validate( char *user, char *domain, 
1145                              char *smb_apasswd, int smb_apasslen, 
1146                              char *smb_ntpasswd, int smb_ntpasslen)
1147 {
1148   unsigned char local_challenge[8];
1149   unsigned char local_lm_response[24];
1150   unsigned char local_nt_reponse[24];
1151   unsigned char trust_passwd[16];
1152   fstring remote_machine;
1153   char *p;
1154   struct in_addr dest_ip;
1155   NET_ID_INFO_CTR ctr;
1156   NET_USER_INFO_3 info3;
1157   struct cli_state cli;
1158   uint32 smb_uid_low;
1159   BOOL connected_ok = False;
1160   struct nmb_name calling, called;
1161
1162   /* 
1163    * Check that the requested domain is not our own machine name.
1164    * If it is, we should never check the PDC here, we use our own local
1165    * password file.
1166    */
1167
1168   if(strequal( domain, global_myname)) {
1169     DEBUG(3,("domain_client_validate: Requested domain was for this machine.\n"));
1170     return False;
1171   }
1172
1173   /*
1174    * Next, check that the passwords given were encrypted.
1175    */
1176
1177   if(((smb_apasslen != 24) && (smb_apasslen != 0)) || 
1178      ((smb_ntpasslen != 24) && (smb_ntpasslen != 0))) {
1179
1180     /*
1181      * Not encrypted - do so.
1182      */
1183
1184     DEBUG(3,("domain_client_validate: User passwords not in encrypted format.\n"));
1185     generate_random_buffer( local_challenge, 8, False);
1186     SMBencrypt( (uchar *)smb_apasswd, local_challenge, local_lm_response);
1187     SMBNTencrypt((uchar *)smb_ntpasswd, local_challenge, local_nt_reponse);
1188     smb_apasslen = 24;
1189     smb_ntpasslen = 24;
1190     smb_apasswd = (char *)local_lm_response;
1191     smb_ntpasswd = (char *)local_nt_reponse;
1192   } else {
1193
1194     /*
1195      * Encrypted - get the challenge we sent for these
1196      * responses.
1197      */
1198
1199     if (!last_challenge(local_challenge)) {
1200       DEBUG(0,("domain_client_validate: no challenge done - password failed\n"));
1201       return False;
1202     }
1203   }
1204
1205   /*
1206    * Get the machine account password.
1207    */
1208   if (!trust_get_passwd( trust_passwd, global_myworkgroup, global_myname))
1209   {
1210     return False;
1211   }
1212
1213   /*
1214    * At this point, smb_apasswd points to the lanman response to
1215    * the challenge in local_challenge, and smb_ntpasswd points to
1216    * the NT response to the challenge in local_challenge. Ship
1217    * these over the secure channel to a domain controller and
1218    * see if they were valid.
1219    */
1220
1221   ZERO_STRUCT(cli);
1222
1223   if(cli_initialise(&cli) == False) {
1224     DEBUG(0,("domain_client_validate: unable to initialize client connection.\n"));
1225     return False;
1226   }
1227
1228   /*
1229    * Treat each name in the 'password server =' line as a potential
1230    * PDC/BDC. Contact each in turn and try and authenticate.
1231    */
1232
1233   p = lp_passwordserver();
1234   while(p && next_token(&p,remote_machine,LIST_SEP,sizeof(remote_machine))) {
1235
1236     standard_sub_basic(remote_machine);
1237     strupper(remote_machine);
1238  
1239     if(!resolve_name( remote_machine, &dest_ip, 0x20)) {
1240       DEBUG(1,("domain_client_validate: Can't resolve address for %s\n", remote_machine));
1241       continue;
1242     }   
1243     
1244     if (ismyip(dest_ip)) {
1245       DEBUG(1,("domain_client_validate: Password server loop - not using password server %s\n",remote_machine));
1246       continue;
1247     }
1248       
1249     if (!cli_connect(&cli, remote_machine, &dest_ip)) {
1250       DEBUG(0,("domain_client_validate: unable to connect to SMB server on \
1251 machine %s. Error was : %s.\n", remote_machine, cli_errstr(&cli) ));
1252       continue;
1253     }
1254     
1255         make_nmb_name(&calling, global_myname , 0x0 , scope);
1256         make_nmb_name(&called , remote_machine, 0x20, scope);
1257
1258         if (!cli_session_request(&cli, &calling, &called))
1259         {
1260       DEBUG(0,("domain_client_validate: machine %s rejected the session setup. \
1261 Error was : %s.\n", remote_machine, cli_errstr(&cli) ));
1262       cli_shutdown(&cli);
1263       continue;
1264     }
1265     
1266     cli.protocol = PROTOCOL_NT1;
1267
1268     if (!cli_negprot(&cli)) {
1269       DEBUG(0,("domain_client_validate: machine %s rejected the negotiate protocol. \
1270 Error was : %s.\n", remote_machine, cli_errstr(&cli) ));
1271       cli_shutdown(&cli);
1272       continue;
1273     }
1274     
1275     if (cli.protocol != PROTOCOL_NT1) {
1276       DEBUG(0,("domain_client_validate: machine %s didn't negotiate NT protocol.\n",
1277                      remote_machine));
1278       cli_shutdown(&cli);
1279       continue;
1280     }
1281
1282     /* 
1283      * Do an anonymous session setup.
1284      */
1285
1286     if (!cli_session_setup(&cli, "", "", 0, "", 0, "")) {
1287       DEBUG(0,("domain_client_validate: machine %s rejected the session setup. \
1288 Error was : %s.\n", remote_machine, cli_errstr(&cli) ));
1289       cli_shutdown(&cli);
1290       continue;
1291     }      
1292
1293     if (!(cli.sec_mode & 1)) {
1294       DEBUG(1,("domain_client_validate: machine %s isn't in user level security mode\n",
1295                  remote_machine));
1296       cli_shutdown(&cli);
1297       continue;
1298     }
1299
1300     if (!cli_send_tconX(&cli, "IPC$", "IPC", "", 1)) {
1301       DEBUG(0,("domain_client_validate: machine %s rejected the tconX on the IPC$ share. \
1302 Error was : %s.\n", remote_machine, cli_errstr(&cli) ));
1303       cli_shutdown(&cli);
1304       continue;
1305     }
1306
1307     /*
1308      * We have an anonymous connection to IPC$.
1309      */
1310     connected_ok = True;
1311     break;
1312   }
1313
1314   if (!connected_ok) {
1315     DEBUG(0,("domain_client_validate: Domain password server not available.\n"));
1316     cli_shutdown(&cli);
1317     return False;
1318   }
1319
1320   /*
1321    * Ok - we have an anonymous connection to the IPC$ share.
1322    * Now start the NT Domain stuff :-).
1323    */
1324
1325   if(cli_nt_session_open(&cli, PIPE_NETLOGON) == False) {
1326     DEBUG(0,("domain_client_validate: unable to open the domain client session to \
1327 machine %s. Error was : %s.\n", remote_machine, cli_errstr(&cli)));
1328     cli_nt_session_close(&cli);
1329     cli_ulogoff(&cli);
1330     cli_shutdown(&cli);
1331     return False; 
1332   }
1333
1334   if(cli_nt_setup_creds(&cli, trust_passwd) == False) {
1335     DEBUG(0,("domain_client_validate: unable to setup the PDC credentials to machine \
1336 %s. Error was : %s.\n", remote_machine, cli_errstr(&cli)));
1337     cli_nt_session_close(&cli);
1338     cli_ulogoff(&cli);
1339     cli_shutdown(&cli);
1340     return False;
1341   }
1342
1343   /* We really don't care what LUID we give the user. */
1344   generate_random_buffer( (unsigned char *)&smb_uid_low, 4, False);
1345
1346   if(cli_nt_login_network(&cli, domain, user, smb_uid_low, (char *)local_challenge,
1347                           ((smb_apasslen != 0) ? smb_apasswd : NULL),
1348                           ((smb_ntpasslen != 0) ? smb_ntpasswd : NULL),
1349                           &ctr, &info3) == False) {
1350     DEBUG(0,("domain_client_validate: unable to validate password for user %s in domain \
1351 %s to Domain controller %s. Error was %s.\n", user, domain, remote_machine, cli_errstr(&cli)));
1352     cli_nt_session_close(&cli);
1353     cli_ulogoff(&cli);
1354     cli_shutdown(&cli);
1355     return False;
1356   }
1357
1358   /*
1359    * Here, if we really want it, we have lots of info about the user in info3.
1360    */
1361
1362 #if 0
1363   /* 
1364    * We don't actually need to do this - plus it fails currently with
1365    * NT_STATUS_INVALID_INFO_CLASS - we need to know *exactly* what to
1366    * send here. JRA.
1367    */
1368
1369   if(cli_nt_logoff(&cli, &ctr) == False) {
1370     DEBUG(0,("domain_client_validate: unable to log off user %s in domain \
1371 %s to Domain controller %s. Error was %s.\n", user, domain, remote_machine, cli_errstr(&cli)));        
1372     cli_nt_session_close(&cli);
1373     cli_ulogoff(&cli);
1374     cli_shutdown(&cli);
1375     return False;
1376   }
1377 #endif /* 0 */
1378
1379   cli_nt_session_close(&cli);
1380   cli_ulogoff(&cli);
1381   cli_shutdown(&cli);
1382   return True;
1383 }