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