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