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