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