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