r21563: Fix a memleak: We only need dispinfo structs for "our" and for the builtin
[samba.git] / source3 / rpc_server / srv_samr_nt.c
1 /*
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Copyright (C) Andrew Tridgell                   1992-1997,
5  *  Copyright (C) Luke Kenneth Casson Leighton      1996-1997,
6  *  Copyright (C) Paul Ashton                       1997,
7  *  Copyright (C) Marc Jacobsen                     1999,
8  *  Copyright (C) Jeremy Allison                    2001-2005,
9  *  Copyright (C) Jean François Micouleau           1998-2001,
10  *  Copyright (C) Jim McDonough <jmcd@us.ibm.com>   2002,
11  *  Copyright (C) Gerald (Jerry) Carter             2003-2004,
12  *  Copyright (C) Simo Sorce                        2003.
13  *  Copyright (C) Volker Lendecke                   2005.
14  *
15  *  This program is free software; you can redistribute it and/or modify
16  *  it under the terms of the GNU General Public License as published by
17  *  the Free Software Foundation; either version 2 of the License, or
18  *  (at your option) any later version.
19  *
20  *  This program is distributed in the hope that it will be useful,
21  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  *  GNU General Public License for more details.
24  *
25  *  You should have received a copy of the GNU General Public License
26  *  along with this program; if not, write to the Free Software
27  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28  */
29
30 /*
31  * This is the implementation of the SAMR code.
32  */
33
34 #include "includes.h"
35
36 #undef DBGC_CLASS
37 #define DBGC_CLASS DBGC_RPC_SRV
38
39 #define SAMR_USR_RIGHTS_WRITE_PW \
40                 ( READ_CONTROL_ACCESS           | \
41                   SA_RIGHT_USER_CHANGE_PASSWORD | \
42                   SA_RIGHT_USER_SET_LOC_COM )
43 #define SAMR_USR_RIGHTS_CANT_WRITE_PW \
44                 ( READ_CONTROL_ACCESS | SA_RIGHT_USER_SET_LOC_COM )
45
46 #define DISP_INFO_CACHE_TIMEOUT 10
47
48 typedef struct disp_info {
49         DOM_SID sid; /* identify which domain this is. */
50         BOOL builtin_domain; /* Quick flag to check if this is the builtin domain. */
51         struct pdb_search *users; /* querydispinfo 1 and 4 */
52         struct pdb_search *machines; /* querydispinfo 2 */
53         struct pdb_search *groups; /* querydispinfo 3 and 5, enumgroups */
54         struct pdb_search *aliases; /* enumaliases */
55
56         uint16 enum_acb_mask;
57         struct pdb_search *enum_users; /* enumusers with a mask */
58
59
60         smb_event_id_t di_cache_timeout_event; /* cache idle timeout handler. */
61 } DISP_INFO;
62
63 /* We keep a static list of these by SID as modern clients close down
64    all resources between each request in a complete enumeration. */
65
66 struct samr_info {
67         /* for use by the \PIPE\samr policy */
68         DOM_SID sid;
69         BOOL builtin_domain; /* Quick flag to check if this is the builtin domain. */
70         uint32 status; /* some sort of flag.  best to record it.  comes from opnum 0x39 */
71         uint32 acc_granted;
72         DISP_INFO *disp_info;
73         TALLOC_CTX *mem_ctx;
74 };
75
76 static struct generic_mapping sam_generic_mapping = {
77         GENERIC_RIGHTS_SAM_READ,
78         GENERIC_RIGHTS_SAM_WRITE,
79         GENERIC_RIGHTS_SAM_EXECUTE,
80         GENERIC_RIGHTS_SAM_ALL_ACCESS};
81 static struct generic_mapping dom_generic_mapping = {
82         GENERIC_RIGHTS_DOMAIN_READ,
83         GENERIC_RIGHTS_DOMAIN_WRITE,
84         GENERIC_RIGHTS_DOMAIN_EXECUTE,
85         GENERIC_RIGHTS_DOMAIN_ALL_ACCESS};
86 static struct generic_mapping usr_generic_mapping = {
87         GENERIC_RIGHTS_USER_READ,
88         GENERIC_RIGHTS_USER_WRITE,
89         GENERIC_RIGHTS_USER_EXECUTE,
90         GENERIC_RIGHTS_USER_ALL_ACCESS};
91 static struct generic_mapping usr_nopwchange_generic_mapping = {
92         GENERIC_RIGHTS_USER_READ,
93         GENERIC_RIGHTS_USER_WRITE,
94         GENERIC_RIGHTS_USER_EXECUTE & ~SA_RIGHT_USER_CHANGE_PASSWORD,
95         GENERIC_RIGHTS_USER_ALL_ACCESS};
96 static struct generic_mapping grp_generic_mapping = {
97         GENERIC_RIGHTS_GROUP_READ,
98         GENERIC_RIGHTS_GROUP_WRITE,
99         GENERIC_RIGHTS_GROUP_EXECUTE,
100         GENERIC_RIGHTS_GROUP_ALL_ACCESS};
101 static struct generic_mapping ali_generic_mapping = {
102         GENERIC_RIGHTS_ALIAS_READ,
103         GENERIC_RIGHTS_ALIAS_WRITE,
104         GENERIC_RIGHTS_ALIAS_EXECUTE,
105         GENERIC_RIGHTS_ALIAS_ALL_ACCESS};
106
107 /*******************************************************************
108 *******************************************************************/
109
110 static NTSTATUS make_samr_object_sd( TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd_size,
111                                      struct generic_mapping *map,
112                                      DOM_SID *sid, uint32 sid_access )
113 {
114         DOM_SID domadmin_sid;
115         SEC_ACE ace[5];         /* at most 5 entries */
116         SEC_ACCESS mask;
117         size_t i = 0;
118
119         SEC_ACL *psa = NULL;
120
121         /* basic access for Everyone */
122
123         init_sec_access(&mask, map->generic_execute | map->generic_read );
124         init_sec_ace(&ace[i++], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
125
126         /* add Full Access 'BUILTIN\Administrators' and 'BUILTIN\Account Operators */
127
128         init_sec_access(&mask, map->generic_all);
129         
130         init_sec_ace(&ace[i++], &global_sid_Builtin_Administrators, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
131         init_sec_ace(&ace[i++], &global_sid_Builtin_Account_Operators, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
132
133         /* Add Full Access for Domain Admins if we are a DC */
134         
135         if ( IS_DC ) {
136                 sid_copy( &domadmin_sid, get_global_sam_sid() );
137                 sid_append_rid( &domadmin_sid, DOMAIN_GROUP_RID_ADMINS );
138                 init_sec_ace(&ace[i++], &domadmin_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
139         }
140
141         /* if we have a sid, give it some special access */
142
143         if ( sid ) {
144                 init_sec_access( &mask, sid_access );
145                 init_sec_ace(&ace[i++], sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
146         }
147
148         /* create the security descriptor */
149
150         if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, i, ace)) == NULL)
151                 return NT_STATUS_NO_MEMORY;
152
153         if ((*psd = make_sec_desc(ctx, SEC_DESC_REVISION, SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL, psa, sd_size)) == NULL)
154                 return NT_STATUS_NO_MEMORY;
155
156         return NT_STATUS_OK;
157 }
158
159 /*******************************************************************
160  Checks if access to an object should be granted, and returns that
161  level of access for further checks.
162 ********************************************************************/
163
164 static NTSTATUS access_check_samr_object( SEC_DESC *psd, NT_USER_TOKEN *token, 
165                                           SE_PRIV *rights, uint32 rights_mask,
166                                           uint32 des_access, uint32 *acc_granted, 
167                                           const char *debug )
168 {
169         NTSTATUS status = NT_STATUS_ACCESS_DENIED;
170         uint32 saved_mask = 0;
171
172         /* check privileges; certain SAM access bits should be overridden 
173            by privileges (mostly having to do with creating/modifying/deleting 
174            users and groups) */
175         
176         if ( rights && user_has_any_privilege( token, rights ) ) {
177         
178                 saved_mask = (des_access & rights_mask);
179                 des_access &= ~saved_mask;
180                 
181                 DEBUG(4,("access_check_samr_object: user rights access mask [0x%x]\n",
182                         rights_mask));
183         }
184                 
185         
186         /* check the security descriptor first */
187         
188         if ( se_access_check(psd, token, des_access, acc_granted, &status) )
189                 goto done;
190         
191         /* give root a free pass */
192         
193         if ( geteuid() == sec_initial_uid() ) {
194         
195                 DEBUG(4,("%s: ACCESS should be DENIED  (requested: %#010x)\n", debug, des_access));
196                 DEBUGADD(4,("but overritten by euid == sec_initial_uid()\n"));
197                 
198                 *acc_granted = des_access;
199                 
200                 status = NT_STATUS_OK;
201                 goto done;
202         }
203         
204         
205 done:
206         /* add in any bits saved during the privilege check (only 
207            matters is status is ok) */
208         
209         *acc_granted |= rights_mask;
210
211         DEBUG(4,("%s: access %s (requested: 0x%08x, granted: 0x%08x)\n", 
212                 debug, NT_STATUS_IS_OK(status) ? "GRANTED" : "DENIED", 
213                 des_access, *acc_granted));
214         
215         return status;
216 }
217
218 /*******************************************************************
219  Checks if access to a function can be granted
220 ********************************************************************/
221
222 static NTSTATUS access_check_samr_function(uint32 acc_granted, uint32 acc_required, const char *debug)
223 {
224         DEBUG(5,("%s: access check ((granted: %#010x;  required: %#010x)\n",  
225                 debug, acc_granted, acc_required));
226
227         /* check the security descriptor first */
228         
229         if ( (acc_granted&acc_required) == acc_required )
230                 return NT_STATUS_OK;
231                 
232         /* give root a free pass */
233
234         if (geteuid() == sec_initial_uid()) {
235         
236                 DEBUG(4,("%s: ACCESS should be DENIED (granted: %#010x;  required: %#010x)\n",
237                         debug, acc_granted, acc_required));
238                 DEBUGADD(4,("but overwritten by euid == 0\n"));
239                 
240                 return NT_STATUS_OK;
241         }
242         
243         DEBUG(2,("%s: ACCESS DENIED (granted: %#010x;  required: %#010x)\n", 
244                 debug, acc_granted, acc_required));
245                 
246         return NT_STATUS_ACCESS_DENIED;
247 }
248
249 /*******************************************************************
250  Fetch or create a dispinfo struct.
251 ********************************************************************/
252
253 static DISP_INFO *get_samr_dispinfo_by_sid(DOM_SID *psid)
254 {
255         /*
256          * We do a static cache for DISP_INFO's here. Explanation can be found
257          * in Jeremy's checkin message to r11793:
258          *
259          * Fix the SAMR cache so it works across completely insane
260          * client behaviour (ie.:
261          * open pipe/open SAMR handle/enumerate 0 - 1024
262          * close SAMR handle, close pipe.
263          * open pipe/open SAMR handle/enumerate 1024 - 2048...
264          * close SAMR handle, close pipe.
265          * And on ad-nausium. Amazing.... probably object-oriented
266          * client side programming in action yet again.
267          * This change should *massively* improve performance when
268          * enumerating users from an LDAP database.
269          * Jeremy.
270          *
271          * "Our" and the builtin domain are the only ones where we ever
272          * enumerate stuff, so just cache 2 entries.
273          */
274
275         static struct disp_info builtin_dispinfo;
276         static struct disp_info domain_dispinfo;
277
278         /* There are two cases to consider here:
279            1) The SID is a domain SID and we look for an equality match, or
280            2) This is an account SID and so we return the DISP_INFO* for our 
281               domain */
282
283         if (psid == NULL) {
284                 return NULL;
285         }
286
287         if (sid_check_is_builtin(psid) || sid_check_is_in_builtin(psid)) {
288                 /*
289                  * Necessary only once, but it does not really hurt.
290                  */
291                 sid_copy(&builtin_dispinfo.sid, &global_sid_Builtin);
292
293                 return &builtin_dispinfo;
294         }
295                 
296         if (sid_check_is_domain(psid) || sid_check_is_in_our_domain(psid)) {
297                 /*
298                  * Necessary only once, but it does not really hurt.
299                  */
300                 sid_copy(&domain_dispinfo.sid, get_global_sam_sid());
301
302                 return &domain_dispinfo;
303         }
304
305         return NULL;
306 }
307
308 /*******************************************************************
309  Create a samr_info struct.
310 ********************************************************************/
311
312 static struct samr_info *get_samr_info_by_sid(DOM_SID *psid)
313 {
314         struct samr_info *info;
315         fstring sid_str;
316         TALLOC_CTX *mem_ctx;
317         
318         if (psid) {
319                 sid_to_string(sid_str, psid);
320         } else {
321                 fstrcpy(sid_str,"(NULL)");
322         }
323
324         mem_ctx = talloc_init("samr_info for domain sid %s", sid_str);
325
326         if ((info = TALLOC_ZERO_P(mem_ctx, struct samr_info)) == NULL)
327                 return NULL;
328
329         DEBUG(10,("get_samr_info_by_sid: created new info for sid %s\n", sid_str));
330         if (psid) {
331                 sid_copy( &info->sid, psid);
332                 info->builtin_domain = sid_check_is_builtin(psid);
333         } else {
334                 DEBUG(10,("get_samr_info_by_sid: created new info for NULL sid.\n"));
335                 info->builtin_domain = False;
336         }
337         info->mem_ctx = mem_ctx;
338
339         info->disp_info = get_samr_dispinfo_by_sid(psid);
340
341         return info;
342 }
343
344 /*******************************************************************
345  Function to free the per SID data.
346  ********************************************************************/
347
348 static void free_samr_cache(DISP_INFO *disp_info, const char *sid_str)
349 {
350         DEBUG(10,("free_samr_cache: deleting cache for SID %s\n", sid_str));
351
352         /* We need to become root here because the paged search might have to
353          * tell the LDAP server we're not interested in the rest anymore. */
354
355         become_root();
356
357         if (disp_info->users) {
358                 DEBUG(10,("free_samr_cache: deleting users cache\n"));
359                 pdb_search_destroy(disp_info->users);
360                 disp_info->users = NULL;
361         }
362         if (disp_info->machines) {
363                 DEBUG(10,("free_samr_cache: deleting machines cache\n"));
364                 pdb_search_destroy(disp_info->machines);
365                 disp_info->machines = NULL;
366         }
367         if (disp_info->groups) {
368                 DEBUG(10,("free_samr_cache: deleting groups cache\n"));
369                 pdb_search_destroy(disp_info->groups);
370                 disp_info->groups = NULL;
371         }
372         if (disp_info->aliases) {
373                 DEBUG(10,("free_samr_cache: deleting aliases cache\n"));
374                 pdb_search_destroy(disp_info->aliases);
375                 disp_info->aliases = NULL;
376         }
377         if (disp_info->enum_users) {
378                 DEBUG(10,("free_samr_cache: deleting enum_users cache\n"));
379                 pdb_search_destroy(disp_info->enum_users);
380                 disp_info->enum_users = NULL;
381         }
382         disp_info->enum_acb_mask = 0;
383
384         unbecome_root();
385 }
386
387 /*******************************************************************
388  Function to free the per handle data.
389  ********************************************************************/
390
391 static void free_samr_info(void *ptr)
392 {
393         struct samr_info *info=(struct samr_info *) ptr;
394
395         /* Only free the dispinfo cache if no one bothered to set up
396            a timeout. */
397
398         if (info->disp_info && info->disp_info->di_cache_timeout_event == (smb_event_id_t)0) {
399                 fstring sid_str;
400                 sid_to_string(sid_str, &info->disp_info->sid);
401                 free_samr_cache(info->disp_info, sid_str);
402         }
403
404         talloc_destroy(info->mem_ctx);
405 }
406
407 /*******************************************************************
408  Idle event handler. Throw away the disp info cache.
409  ********************************************************************/
410
411 static void disp_info_cache_idle_timeout_handler(void **private_data,
412                                         time_t *ev_interval,
413                                         time_t ev_now)
414 {
415         fstring sid_str;
416         DISP_INFO *disp_info = (DISP_INFO *)(*private_data);
417
418         sid_to_string(sid_str, &disp_info->sid);
419
420         free_samr_cache(disp_info, sid_str);
421
422         /* Remove the event. */
423         smb_unregister_idle_event(disp_info->di_cache_timeout_event);
424         disp_info->di_cache_timeout_event = (smb_event_id_t)0;
425
426         DEBUG(10,("disp_info_cache_idle_timeout_handler: caching timed out for SID %s at %u\n",
427                 sid_str, (unsigned int)ev_now));
428 }
429
430 /*******************************************************************
431  Setup cache removal idle event handler.
432  ********************************************************************/
433
434 static void set_disp_info_cache_timeout(DISP_INFO *disp_info, time_t secs_fromnow)
435 {
436         fstring sid_str;
437
438         sid_to_string(sid_str, &disp_info->sid);
439
440         /* Remove any pending timeout and update. */
441
442         if (disp_info->di_cache_timeout_event) {
443                 smb_unregister_idle_event(disp_info->di_cache_timeout_event);
444                 disp_info->di_cache_timeout_event = (smb_event_id_t)0;
445         }
446
447         DEBUG(10,("set_disp_info_cache_timeout: caching enumeration for SID %s for %u seconds\n",
448                 sid_str, (unsigned int)secs_fromnow ));
449
450         disp_info->di_cache_timeout_event =
451                 smb_register_idle_event(disp_info_cache_idle_timeout_handler,
452                                         disp_info,
453                                         secs_fromnow);
454 }
455
456 /*******************************************************************
457  Force flush any cache. We do this on any samr_set_xxx call.
458  We must also remove the timeout handler.
459  ********************************************************************/
460
461 static void force_flush_samr_cache(DISP_INFO *disp_info)
462 {
463         if (disp_info) {
464                 fstring sid_str;
465
466                 sid_to_string(sid_str, &disp_info->sid);
467                 if (disp_info->di_cache_timeout_event) {
468                         smb_unregister_idle_event(disp_info->di_cache_timeout_event);
469                         disp_info->di_cache_timeout_event = (smb_event_id_t)0;
470                         DEBUG(10,("force_flush_samr_cache: clearing idle event for SID %s\n",
471                                 sid_str));
472                 }
473                 free_samr_cache(disp_info, sid_str);
474         }
475 }
476
477 /*******************************************************************
478  Ensure password info is never given out. Paranioa... JRA.
479  ********************************************************************/
480
481 static void samr_clear_sam_passwd(struct samu *sam_pass)
482 {
483         
484         if (!sam_pass)
485                 return;
486
487         /* These now zero out the old password */
488
489         pdb_set_lanman_passwd(sam_pass, NULL, PDB_DEFAULT);
490         pdb_set_nt_passwd(sam_pass, NULL, PDB_DEFAULT);
491 }
492
493 static uint32 count_sam_users(struct disp_info *info, uint32 acct_flags)
494 {
495         struct samr_displayentry *entry;
496
497         if (info->builtin_domain) {
498                 /* No users in builtin. */
499                 return 0;
500         }
501
502         if (info->users == NULL) {
503                 info->users = pdb_search_users(acct_flags);
504                 if (info->users == NULL) {
505                         return 0;
506                 }
507         }
508         /* Fetch the last possible entry, thus trigger an enumeration */
509         pdb_search_entries(info->users, 0xffffffff, 1, &entry);
510
511         /* Ensure we cache this enumeration. */
512         set_disp_info_cache_timeout(info, DISP_INFO_CACHE_TIMEOUT);
513
514         return info->users->num_entries;
515 }
516
517 static uint32 count_sam_groups(struct disp_info *info)
518 {
519         struct samr_displayentry *entry;
520
521         if (info->builtin_domain) {
522                 /* No groups in builtin. */
523                 return 0;
524         }
525
526         if (info->groups == NULL) {
527                 info->groups = pdb_search_groups();
528                 if (info->groups == NULL) {
529                         return 0;
530                 }
531         }
532         /* Fetch the last possible entry, thus trigger an enumeration */
533         pdb_search_entries(info->groups, 0xffffffff, 1, &entry);
534
535         /* Ensure we cache this enumeration. */
536         set_disp_info_cache_timeout(info, DISP_INFO_CACHE_TIMEOUT);
537
538         return info->groups->num_entries;
539 }
540
541 static uint32 count_sam_aliases(struct disp_info *info)
542 {
543         struct samr_displayentry *entry;
544
545         if (info->aliases == NULL) {
546                 info->aliases = pdb_search_aliases(&info->sid);
547                 if (info->aliases == NULL) {
548                         return 0;
549                 }
550         }
551         /* Fetch the last possible entry, thus trigger an enumeration */
552         pdb_search_entries(info->aliases, 0xffffffff, 1, &entry);
553
554         /* Ensure we cache this enumeration. */
555         set_disp_info_cache_timeout(info, DISP_INFO_CACHE_TIMEOUT);
556
557         return info->aliases->num_entries;
558 }
559
560 /*******************************************************************
561  _samr_close_hnd
562  ********************************************************************/
563
564 NTSTATUS _samr_close_hnd(pipes_struct *p, SAMR_Q_CLOSE_HND *q_u, SAMR_R_CLOSE_HND *r_u)
565 {
566         r_u->status = NT_STATUS_OK;
567
568         /* close the policy handle */
569         if (!close_policy_hnd(p, &q_u->pol))
570                 return NT_STATUS_OBJECT_NAME_INVALID;
571
572         DEBUG(5,("samr_reply_close_hnd: %d\n", __LINE__));
573
574         return r_u->status;
575 }
576
577 /*******************************************************************
578  samr_reply_open_domain
579  ********************************************************************/
580
581 NTSTATUS _samr_open_domain(pipes_struct *p, SAMR_Q_OPEN_DOMAIN *q_u, SAMR_R_OPEN_DOMAIN *r_u)
582 {
583         struct    samr_info *info;
584         SEC_DESC *psd = NULL;
585         uint32    acc_granted;
586         uint32    des_access = q_u->flags;
587         NTSTATUS  status;
588         size_t    sd_size;
589         SE_PRIV se_rights;
590
591         r_u->status = NT_STATUS_OK;
592
593         /* find the connection policy handle. */
594         
595         if ( !find_policy_by_hnd(p, &q_u->pol, (void**)(void *)&info) )
596                 return NT_STATUS_INVALID_HANDLE;
597
598         status = access_check_samr_function( info->acc_granted, 
599                 SA_RIGHT_SAM_OPEN_DOMAIN, "_samr_open_domain" );
600                 
601         if ( !NT_STATUS_IS_OK(status) )
602                 return status;
603
604         /*check if access can be granted as requested by client. */
605         
606         make_samr_object_sd( p->mem_ctx, &psd, &sd_size, &dom_generic_mapping, NULL, 0 );
607         se_map_generic( &des_access, &dom_generic_mapping );
608         
609         se_priv_copy( &se_rights, &se_machine_account );
610         se_priv_add( &se_rights, &se_add_users );
611
612         status = access_check_samr_object( psd, p->pipe_user.nt_user_token, 
613                 &se_rights, GENERIC_RIGHTS_DOMAIN_WRITE, des_access, 
614                 &acc_granted, "_samr_open_domain" );
615                 
616         if ( !NT_STATUS_IS_OK(status) )
617                 return status;
618
619         if (!sid_check_is_domain(&q_u->dom_sid.sid) &&
620             !sid_check_is_builtin(&q_u->dom_sid.sid)) {
621                 return NT_STATUS_NO_SUCH_DOMAIN;
622         }
623
624         /* associate the domain SID with the (unique) handle. */
625         if ((info = get_samr_info_by_sid(&q_u->dom_sid.sid))==NULL)
626                 return NT_STATUS_NO_MEMORY;
627         info->acc_granted = acc_granted;
628
629         /* get a (unique) handle.  open a policy on it. */
630         if (!create_policy_hnd(p, &r_u->domain_pol, free_samr_info, (void *)info))
631                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
632
633         DEBUG(5,("samr_open_domain: %d\n", __LINE__));
634
635         return r_u->status;
636 }
637
638 /*******************************************************************
639  _samr_get_usrdom_pwinfo
640  ********************************************************************/
641
642 NTSTATUS _samr_get_usrdom_pwinfo(pipes_struct *p, SAMR_Q_GET_USRDOM_PWINFO *q_u, SAMR_R_GET_USRDOM_PWINFO *r_u)
643 {
644         struct samr_info *info = NULL;
645
646         r_u->status = NT_STATUS_OK;
647
648         /* find the policy handle.  open a policy on it. */
649         if (!find_policy_by_hnd(p, &q_u->user_pol, (void **)(void *)&info))
650                 return NT_STATUS_INVALID_HANDLE;
651
652         if (!sid_check_is_in_our_domain(&info->sid))
653                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
654
655         init_samr_r_get_usrdom_pwinfo(r_u, NT_STATUS_OK);
656
657         DEBUG(5,("_samr_get_usrdom_pwinfo: %d\n", __LINE__));
658
659         /* 
660          * NT sometimes return NT_STATUS_ACCESS_DENIED
661          * I don't know yet why.
662          */
663
664         return r_u->status;
665 }
666
667 /*******************************************************************
668 ********************************************************************/
669
670 static BOOL get_lsa_policy_samr_sid( pipes_struct *p, POLICY_HND *pol, 
671                                         DOM_SID *sid, uint32 *acc_granted,
672                                         DISP_INFO **ppdisp_info)
673 {
674         struct samr_info *info = NULL;
675
676         /* find the policy handle.  open a policy on it. */
677         if (!find_policy_by_hnd(p, pol, (void **)(void *)&info))
678                 return False;
679
680         if (!info)
681                 return False;
682
683         *sid = info->sid;
684         *acc_granted = info->acc_granted;
685         if (ppdisp_info) {
686                 *ppdisp_info = info->disp_info;
687         }
688
689         return True;
690 }
691
692 /*******************************************************************
693  _samr_set_sec_obj
694  ********************************************************************/
695
696 NTSTATUS _samr_set_sec_obj(pipes_struct *p, SAMR_Q_SET_SEC_OBJ *q_u, SAMR_R_SET_SEC_OBJ *r_u)
697 {
698         DOM_SID pol_sid;
699         uint32 acc_granted, i;
700         SEC_ACL *dacl;
701         BOOL ret;
702         struct samu *sampass=NULL;
703         NTSTATUS status;
704
705         r_u->status = NT_STATUS_OK;
706
707         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &pol_sid, &acc_granted, NULL))
708                 return NT_STATUS_INVALID_HANDLE;
709
710         if (!(sampass = samu_new( p->mem_ctx))) {
711                 DEBUG(0,("No memory!\n"));
712                 return NT_STATUS_NO_MEMORY;
713         }
714
715         /* get the user record */
716         become_root();
717         ret = pdb_getsampwsid(sampass, &pol_sid);
718         unbecome_root();
719
720         if (!ret) {
721                 DEBUG(4, ("User %s not found\n", sid_string_static(&pol_sid)));
722                 TALLOC_FREE(sampass);
723                 return NT_STATUS_INVALID_HANDLE;
724         }
725
726         dacl = q_u->buf->sd->dacl;
727         for (i=0; i < dacl->num_aces; i++) {
728                 if (sid_equal(&pol_sid, &dacl->aces[i].trustee)) {
729                         ret = pdb_set_pass_can_change(sampass, 
730                                 (dacl->aces[i].access_mask & 
731                                  SA_RIGHT_USER_CHANGE_PASSWORD) ? 
732                                                       True: False);
733                         break;
734                 }
735         }
736
737         if (!ret) {
738                 TALLOC_FREE(sampass);
739                 return NT_STATUS_ACCESS_DENIED;
740         }
741
742         status = pdb_update_sam_account(sampass);
743
744         TALLOC_FREE(sampass);
745
746         return status;
747 }
748
749 /*******************************************************************
750   build correct perms based on policies and password times for _samr_query_sec_obj
751 *******************************************************************/
752 static BOOL check_change_pw_access(TALLOC_CTX *mem_ctx, DOM_SID *user_sid)
753 {
754         struct samu *sampass=NULL;
755         BOOL ret;
756
757         if ( !(sampass = samu_new( mem_ctx )) ) {
758                 DEBUG(0,("No memory!\n"));
759                 return False;
760         }
761
762         become_root();
763         ret = pdb_getsampwsid(sampass, user_sid);
764         unbecome_root();
765
766         if (ret == False) {
767                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
768                 TALLOC_FREE(sampass);
769                 return False;
770         }
771
772         DEBUG(3,("User:[%s]\n",  pdb_get_username(sampass) ));
773
774         if (pdb_get_pass_can_change(sampass)) {
775                 TALLOC_FREE(sampass);
776                 return True;
777         }
778         TALLOC_FREE(sampass);
779         return False;
780 }
781
782
783 /*******************************************************************
784  _samr_query_sec_obj
785  ********************************************************************/
786
787 NTSTATUS _samr_query_sec_obj(pipes_struct *p, SAMR_Q_QUERY_SEC_OBJ *q_u, SAMR_R_QUERY_SEC_OBJ *r_u)
788 {
789         DOM_SID pol_sid;
790         fstring str_sid;
791         SEC_DESC * psd = NULL;
792         uint32 acc_granted;
793         size_t sd_size;
794
795         r_u->status = NT_STATUS_OK;
796
797         /* Get the SID. */
798         if (!get_lsa_policy_samr_sid(p, &q_u->user_pol, &pol_sid, &acc_granted, NULL))
799                 return NT_STATUS_INVALID_HANDLE;
800
801         DEBUG(10,("_samr_query_sec_obj: querying security on SID: %s\n", sid_to_string(str_sid, &pol_sid)));
802
803         /* Check what typ of SID is beeing queried (e.g Domain SID, User SID, Group SID) */
804
805         /* To query the security of the SAM it self an invalid SID with S-0-0 is passed to this function */
806         if (pol_sid.sid_rev_num == 0) {
807                 DEBUG(5,("_samr_query_sec_obj: querying security on SAM\n"));
808                 r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &sam_generic_mapping, NULL, 0);
809         } else if (sid_equal(&pol_sid,get_global_sam_sid())) { 
810                 /* check if it is our domain SID */
811                 DEBUG(5,("_samr_query_sec_obj: querying security on Domain with SID: %s\n", sid_to_string(str_sid, &pol_sid)));
812                 r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &dom_generic_mapping, NULL, 0);
813         } else if (sid_equal(&pol_sid,&global_sid_Builtin)) {
814                 /* check if it is the Builtin  Domain */
815                 /* TODO: Builtin probably needs a different SD with restricted write access*/
816                 DEBUG(5,("_samr_query_sec_obj: querying security on Builtin Domain with SID: %s\n", sid_to_string(str_sid, &pol_sid)));
817                 r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &dom_generic_mapping, NULL, 0);
818         } else if (sid_check_is_in_our_domain(&pol_sid) ||
819                  sid_check_is_in_builtin(&pol_sid)) {
820                 /* TODO: different SDs have to be generated for aliases groups and users.
821                          Currently all three get a default user SD  */
822                 DEBUG(10,("_samr_query_sec_obj: querying security on Object with SID: %s\n", sid_to_string(str_sid, &pol_sid)));
823                 if (check_change_pw_access(p->mem_ctx, &pol_sid)) {
824                         r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &usr_generic_mapping, 
825                                                           &pol_sid, SAMR_USR_RIGHTS_WRITE_PW);
826                 } else {
827                         r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &usr_nopwchange_generic_mapping, 
828                                                           &pol_sid, SAMR_USR_RIGHTS_CANT_WRITE_PW);
829                 }
830         } else {
831                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
832         }
833
834         if ((r_u->buf = make_sec_desc_buf(p->mem_ctx, sd_size, psd)) == NULL)
835                 return NT_STATUS_NO_MEMORY;
836
837         if (NT_STATUS_IS_OK(r_u->status))
838                 r_u->ptr = 1;
839
840         return r_u->status;
841 }
842
843 /*******************************************************************
844 makes a SAM_ENTRY / UNISTR2* structure from a user list.
845 ********************************************************************/
846
847 static NTSTATUS make_user_sam_entry_list(TALLOC_CTX *ctx, SAM_ENTRY **sam_pp,
848                                          UNISTR2 **uni_name_pp,
849                                          uint32 num_entries, uint32 start_idx,
850                                          struct samr_displayentry *entries)
851 {
852         uint32 i;
853         SAM_ENTRY *sam;
854         UNISTR2 *uni_name;
855         
856         *sam_pp = NULL;
857         *uni_name_pp = NULL;
858
859         if (num_entries == 0)
860                 return NT_STATUS_OK;
861
862         sam = TALLOC_ZERO_ARRAY(ctx, SAM_ENTRY, num_entries);
863
864         uni_name = TALLOC_ZERO_ARRAY(ctx, UNISTR2, num_entries);
865
866         if (sam == NULL || uni_name == NULL) {
867                 DEBUG(0, ("make_user_sam_entry_list: talloc_zero failed!\n"));
868                 return NT_STATUS_NO_MEMORY;
869         }
870
871         for (i = 0; i < num_entries; i++) {
872                 UNISTR2 uni_temp_name;
873                 /*
874                  * usrmgr expects a non-NULL terminated string with
875                  * trust relationships
876                  */
877                 if (entries[i].acct_flags & ACB_DOMTRUST) {
878                         init_unistr2(&uni_temp_name, entries[i].account_name,
879                                      UNI_FLAGS_NONE);
880                 } else {
881                         init_unistr2(&uni_temp_name, entries[i].account_name,
882                                      UNI_STR_TERMINATE);
883                 }
884
885                 init_sam_entry(&sam[i], &uni_temp_name, entries[i].rid);
886                 copy_unistr2(&uni_name[i], &uni_temp_name);
887         }
888
889         *sam_pp = sam;
890         *uni_name_pp = uni_name;
891         return NT_STATUS_OK;
892 }
893
894 /*******************************************************************
895  samr_reply_enum_dom_users
896  ********************************************************************/
897
898 NTSTATUS _samr_enum_dom_users(pipes_struct *p, SAMR_Q_ENUM_DOM_USERS *q_u, 
899                               SAMR_R_ENUM_DOM_USERS *r_u)
900 {
901         struct samr_info *info = NULL;
902         int num_account;
903         uint32 enum_context=q_u->start_idx;
904         enum remote_arch_types ra_type = get_remote_arch();
905         int max_sam_entries = (ra_type == RA_WIN95) ? MAX_SAM_ENTRIES_W95 : MAX_SAM_ENTRIES_W2K;
906         uint32 max_entries = max_sam_entries;
907         struct samr_displayentry *entries = NULL;
908         
909         r_u->status = NT_STATUS_OK;
910
911         /* find the policy handle.  open a policy on it. */
912         if (!find_policy_by_hnd(p, &q_u->pol, (void **)(void *)&info))
913                 return NT_STATUS_INVALID_HANDLE;
914
915         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(info->acc_granted, 
916                                         SA_RIGHT_DOMAIN_ENUM_ACCOUNTS, 
917                                         "_samr_enum_dom_users"))) {
918                 return r_u->status;
919         }
920         
921         DEBUG(5,("_samr_enum_dom_users: %d\n", __LINE__));
922
923         if (info->builtin_domain) {
924                 /* No users in builtin. */
925                 init_samr_r_enum_dom_users(r_u, q_u->start_idx, 0);
926                 DEBUG(5,("_samr_enum_dom_users: No users in BUILTIN\n"));
927                 return r_u->status;
928         }
929
930         become_root();
931
932         /* AS ROOT !!!! */
933
934         if ((info->disp_info->enum_users != NULL) &&
935             (info->disp_info->enum_acb_mask != q_u->acb_mask)) {
936                 pdb_search_destroy(info->disp_info->enum_users);
937                 info->disp_info->enum_users = NULL;
938         }
939
940         if (info->disp_info->enum_users == NULL) {
941                 info->disp_info->enum_users = pdb_search_users(q_u->acb_mask);
942                 info->disp_info->enum_acb_mask = q_u->acb_mask;
943         }
944
945         if (info->disp_info->enum_users == NULL) {
946                 /* END AS ROOT !!!! */
947                 unbecome_root();
948                 return NT_STATUS_ACCESS_DENIED;
949         }
950
951         num_account = pdb_search_entries(info->disp_info->enum_users,
952                                          enum_context, max_entries,
953                                          &entries);
954
955         /* END AS ROOT !!!! */
956
957         unbecome_root();
958
959         if (num_account == 0) {
960                 DEBUG(5, ("_samr_enum_dom_users: enumeration handle over "
961                           "total entries\n"));
962                 return NT_STATUS_OK;
963         }
964
965         r_u->status = make_user_sam_entry_list(p->mem_ctx, &r_u->sam,
966                                                &r_u->uni_acct_name, 
967                                                num_account, enum_context,
968                                                entries);
969
970         if (!NT_STATUS_IS_OK(r_u->status))
971                 return r_u->status;
972
973         if (max_entries <= num_account) {
974                 r_u->status = STATUS_MORE_ENTRIES;
975         } else {
976                 r_u->status = NT_STATUS_OK;
977         }
978
979         /* Ensure we cache this enumeration. */
980         set_disp_info_cache_timeout(info->disp_info, DISP_INFO_CACHE_TIMEOUT);
981
982         DEBUG(5, ("_samr_enum_dom_users: %d\n", __LINE__));
983
984         init_samr_r_enum_dom_users(r_u, q_u->start_idx + num_account,
985                                    num_account);
986
987         DEBUG(5,("_samr_enum_dom_users: %d\n", __LINE__));
988
989         return r_u->status;
990 }
991
992 /*******************************************************************
993 makes a SAM_ENTRY / UNISTR2* structure from a group list.
994 ********************************************************************/
995
996 static void make_group_sam_entry_list(TALLOC_CTX *ctx, SAM_ENTRY **sam_pp,
997                                       UNISTR2 **uni_name_pp,
998                                       uint32 num_sam_entries,
999                                       struct samr_displayentry *entries)
1000 {
1001         uint32 i;
1002         SAM_ENTRY *sam;
1003         UNISTR2 *uni_name;
1004
1005         *sam_pp = NULL;
1006         *uni_name_pp = NULL;
1007
1008         if (num_sam_entries == 0)
1009                 return;
1010
1011         sam = TALLOC_ZERO_ARRAY(ctx, SAM_ENTRY, num_sam_entries);
1012         uni_name = TALLOC_ZERO_ARRAY(ctx, UNISTR2, num_sam_entries);
1013
1014         if (sam == NULL || uni_name == NULL) {
1015                 DEBUG(0, ("NULL pointers in SAMR_R_QUERY_DISPINFO\n"));
1016                 return;
1017         }
1018
1019         for (i = 0; i < num_sam_entries; i++) {
1020                 /*
1021                  * JRA. I think this should include the null. TNG does not.
1022                  */
1023                 init_unistr2(&uni_name[i], entries[i].account_name,
1024                              UNI_STR_TERMINATE);
1025                 init_sam_entry(&sam[i], &uni_name[i], entries[i].rid);
1026         }
1027
1028         *sam_pp = sam;
1029         *uni_name_pp = uni_name;
1030 }
1031
1032 /*******************************************************************
1033  samr_reply_enum_dom_groups
1034  ********************************************************************/
1035
1036 NTSTATUS _samr_enum_dom_groups(pipes_struct *p, SAMR_Q_ENUM_DOM_GROUPS *q_u, SAMR_R_ENUM_DOM_GROUPS *r_u)
1037 {
1038         struct samr_info *info = NULL;
1039         struct samr_displayentry *groups;
1040         uint32 num_groups;
1041
1042         r_u->status = NT_STATUS_OK;
1043
1044         /* find the policy handle.  open a policy on it. */
1045         if (!find_policy_by_hnd(p, &q_u->pol, (void **)(void *)&info))
1046                 return NT_STATUS_INVALID_HANDLE;
1047
1048         r_u->status = access_check_samr_function(info->acc_granted,
1049                                                  SA_RIGHT_DOMAIN_ENUM_ACCOUNTS,
1050                                                  "_samr_enum_dom_groups");
1051         if (!NT_STATUS_IS_OK(r_u->status))
1052                 return r_u->status;
1053
1054         DEBUG(5,("samr_reply_enum_dom_groups: %d\n", __LINE__));
1055
1056         if (info->builtin_domain) {
1057                 /* No groups in builtin. */
1058                 init_samr_r_enum_dom_groups(r_u, q_u->start_idx, 0);
1059                 DEBUG(5,("_samr_enum_dom_users: No groups in BUILTIN\n"));
1060                 return r_u->status;
1061         }
1062
1063         /* the domain group array is being allocated in the function below */
1064
1065         become_root();
1066
1067         if (info->disp_info->groups == NULL) {
1068                 info->disp_info->groups = pdb_search_groups();
1069
1070                 if (info->disp_info->groups == NULL) {
1071                         unbecome_root();
1072                         return NT_STATUS_ACCESS_DENIED;
1073                 }
1074         }
1075
1076         num_groups = pdb_search_entries(info->disp_info->groups, q_u->start_idx,
1077                                         MAX_SAM_ENTRIES, &groups);
1078         unbecome_root();
1079         
1080         /* Ensure we cache this enumeration. */
1081         set_disp_info_cache_timeout(info->disp_info, DISP_INFO_CACHE_TIMEOUT);
1082
1083         make_group_sam_entry_list(p->mem_ctx, &r_u->sam, &r_u->uni_grp_name,
1084                                   num_groups, groups);
1085
1086         init_samr_r_enum_dom_groups(r_u, q_u->start_idx, num_groups);
1087
1088         DEBUG(5,("samr_enum_dom_groups: %d\n", __LINE__));
1089
1090         return r_u->status;
1091 }
1092
1093 /*******************************************************************
1094  samr_reply_enum_dom_aliases
1095  ********************************************************************/
1096
1097 NTSTATUS _samr_enum_dom_aliases(pipes_struct *p, SAMR_Q_ENUM_DOM_ALIASES *q_u, SAMR_R_ENUM_DOM_ALIASES *r_u)
1098 {
1099         struct samr_info *info;
1100         struct samr_displayentry *aliases;
1101         uint32 num_aliases = 0;
1102
1103         /* find the policy handle.  open a policy on it. */
1104         if (!find_policy_by_hnd(p, &q_u->pol, (void **)(void *)&info))
1105                 return NT_STATUS_INVALID_HANDLE;
1106
1107         r_u->status = access_check_samr_function(info->acc_granted,
1108                                                  SA_RIGHT_DOMAIN_ENUM_ACCOUNTS,
1109                                                  "_samr_enum_dom_aliases");
1110         if (!NT_STATUS_IS_OK(r_u->status))
1111                 return r_u->status;
1112
1113         DEBUG(5,("samr_reply_enum_dom_aliases: sid %s\n",
1114                  sid_string_static(&info->sid)));
1115
1116         become_root();
1117
1118         if (info->disp_info->aliases == NULL) {
1119                 info->disp_info->aliases = pdb_search_aliases(&info->sid);
1120                 if (info->disp_info->aliases == NULL) {
1121                         unbecome_root();
1122                         return NT_STATUS_ACCESS_DENIED;
1123                 }
1124         }
1125
1126         num_aliases = pdb_search_entries(info->disp_info->aliases, q_u->start_idx,
1127                                          MAX_SAM_ENTRIES, &aliases);
1128         unbecome_root();
1129         
1130         /* Ensure we cache this enumeration. */
1131         set_disp_info_cache_timeout(info->disp_info, DISP_INFO_CACHE_TIMEOUT);
1132
1133         make_group_sam_entry_list(p->mem_ctx, &r_u->sam, &r_u->uni_grp_name,
1134                                   num_aliases, aliases);
1135
1136         init_samr_r_enum_dom_aliases(r_u, q_u->start_idx + num_aliases,
1137                                      num_aliases);
1138
1139         DEBUG(5,("samr_enum_dom_aliases: %d\n", __LINE__));
1140
1141         return r_u->status;
1142 }
1143
1144 /*******************************************************************
1145  samr_reply_query_dispinfo
1146  ********************************************************************/
1147
1148 NTSTATUS _samr_query_dispinfo(pipes_struct *p, SAMR_Q_QUERY_DISPINFO *q_u, 
1149                               SAMR_R_QUERY_DISPINFO *r_u)
1150 {
1151         struct samr_info *info = NULL;
1152         uint32 struct_size=0x20; /* W2K always reply that, client doesn't care */
1153         
1154         uint32 max_entries=q_u->max_entries;
1155         uint32 enum_context=q_u->start_idx;
1156         uint32 max_size=q_u->max_size;
1157
1158         SAM_DISPINFO_CTR *ctr;
1159         uint32 temp_size=0, total_data_size=0;
1160         NTSTATUS disp_ret = NT_STATUS_UNSUCCESSFUL;
1161         uint32 num_account = 0;
1162         enum remote_arch_types ra_type = get_remote_arch();
1163         int max_sam_entries = (ra_type == RA_WIN95) ? MAX_SAM_ENTRIES_W95 : MAX_SAM_ENTRIES_W2K;
1164         struct samr_displayentry *entries = NULL;
1165
1166         DEBUG(5, ("samr_reply_query_dispinfo: %d\n", __LINE__));
1167         r_u->status = NT_STATUS_UNSUCCESSFUL;
1168
1169         /* find the policy handle.  open a policy on it. */
1170         if (!find_policy_by_hnd(p, &q_u->domain_pol, (void **)(void *)&info))
1171                 return NT_STATUS_INVALID_HANDLE;
1172
1173         /*
1174          * calculate how many entries we will return.
1175          * based on 
1176          * - the number of entries the client asked
1177          * - our limit on that
1178          * - the starting point (enumeration context)
1179          * - the buffer size the client will accept
1180          */
1181
1182         /*
1183          * We are a lot more like W2K. Instead of reading the SAM
1184          * each time to find the records we need to send back,
1185          * we read it once and link that copy to the sam handle.
1186          * For large user list (over the MAX_SAM_ENTRIES)
1187          * it's a definitive win.
1188          * second point to notice: between enumerations
1189          * our sam is now the same as it's a snapshoot.
1190          * third point: got rid of the static SAM_USER_21 struct
1191          * no more intermediate.
1192          * con: it uses much more memory, as a full copy is stored
1193          * in memory.
1194          *
1195          * If you want to change it, think twice and think
1196          * of the second point , that's really important.
1197          *
1198          * JFM, 12/20/2001
1199          */
1200
1201         if ((q_u->switch_level < 1) || (q_u->switch_level > 5)) {
1202                 DEBUG(0,("_samr_query_dispinfo: Unknown info level (%u)\n",
1203                          (unsigned int)q_u->switch_level ));
1204                 return NT_STATUS_INVALID_INFO_CLASS;
1205         }
1206
1207         /* first limit the number of entries we will return */
1208         if(max_entries > max_sam_entries) {
1209                 DEBUG(5, ("samr_reply_query_dispinfo: client requested %d "
1210                           "entries, limiting to %d\n", max_entries,
1211                           max_sam_entries));
1212                 max_entries = max_sam_entries;
1213         }
1214
1215         /* calculate the size and limit on the number of entries we will
1216          * return */
1217
1218         temp_size=max_entries*struct_size;
1219         
1220         if (temp_size>max_size) {
1221                 max_entries=MIN((max_size/struct_size),max_entries);;
1222                 DEBUG(5, ("samr_reply_query_dispinfo: buffer size limits to "
1223                           "only %d entries\n", max_entries));
1224         }
1225
1226         if (!(ctr = TALLOC_ZERO_P(p->mem_ctx,SAM_DISPINFO_CTR)))
1227                 return NT_STATUS_NO_MEMORY;
1228
1229         ZERO_STRUCTP(ctr);
1230
1231         become_root();
1232
1233         /* THe following done as ROOT. Don't return without unbecome_root(). */
1234
1235         switch (q_u->switch_level) {
1236         case 0x1:
1237         case 0x4:
1238                 if (info->disp_info->users == NULL) {
1239                         info->disp_info->users = pdb_search_users(ACB_NORMAL);
1240                         if (info->disp_info->users == NULL) {
1241                                 unbecome_root();
1242                                 return NT_STATUS_ACCESS_DENIED;
1243                         }
1244                         DEBUG(10,("samr_reply_query_dispinfo: starting user enumeration at index %u\n",
1245                                 (unsigned  int)enum_context ));
1246                 } else {
1247                         DEBUG(10,("samr_reply_query_dispinfo: using cached user enumeration at index %u\n",
1248                                 (unsigned  int)enum_context ));
1249                 }
1250
1251                 num_account = pdb_search_entries(info->disp_info->users,
1252                                                  enum_context, max_entries,
1253                                                  &entries);
1254                 break;
1255         case 0x2:
1256                 if (info->disp_info->machines == NULL) {
1257                         info->disp_info->machines =
1258                                 pdb_search_users(ACB_WSTRUST|ACB_SVRTRUST);
1259                         if (info->disp_info->machines == NULL) {
1260                                 unbecome_root();
1261                                 return NT_STATUS_ACCESS_DENIED;
1262                         }
1263                         DEBUG(10,("samr_reply_query_dispinfo: starting machine enumeration at index %u\n",
1264                                 (unsigned  int)enum_context ));
1265                 } else {
1266                         DEBUG(10,("samr_reply_query_dispinfo: using cached machine enumeration at index %u\n",
1267                                 (unsigned  int)enum_context ));
1268                 }
1269
1270                 num_account = pdb_search_entries(info->disp_info->machines,
1271                                                  enum_context, max_entries,
1272                                                  &entries);
1273                 break;
1274         case 0x3:
1275         case 0x5:
1276                 if (info->disp_info->groups == NULL) {
1277                         info->disp_info->groups = pdb_search_groups();
1278                         if (info->disp_info->groups == NULL) {
1279                                 unbecome_root();
1280                                 return NT_STATUS_ACCESS_DENIED;
1281                         }
1282                         DEBUG(10,("samr_reply_query_dispinfo: starting group enumeration at index %u\n",
1283                                 (unsigned  int)enum_context ));
1284                 } else {
1285                         DEBUG(10,("samr_reply_query_dispinfo: using cached group enumeration at index %u\n",
1286                                 (unsigned  int)enum_context ));
1287                 }
1288
1289                 num_account = pdb_search_entries(info->disp_info->groups,
1290                                                  enum_context, max_entries,
1291                                                  &entries);
1292                 break;
1293         default:
1294                 unbecome_root();
1295                 smb_panic("info class changed");
1296                 break;
1297         }
1298         unbecome_root();
1299
1300         /* Now create reply structure */
1301         switch (q_u->switch_level) {
1302         case 0x1:
1303                 disp_ret = init_sam_dispinfo_1(p->mem_ctx, &ctr->sam.info1,
1304                                                num_account, enum_context,
1305                                                entries);
1306                 break;
1307         case 0x2:
1308                 disp_ret = init_sam_dispinfo_2(p->mem_ctx, &ctr->sam.info2,
1309                                                num_account, enum_context,
1310                                                entries);
1311                 break;
1312         case 0x3:
1313                 disp_ret = init_sam_dispinfo_3(p->mem_ctx, &ctr->sam.info3,
1314                                                num_account, enum_context,
1315                                                entries);
1316                 break;
1317         case 0x4:
1318                 disp_ret = init_sam_dispinfo_4(p->mem_ctx, &ctr->sam.info4,
1319                                                num_account, enum_context,
1320                                                entries);
1321                 break;
1322         case 0x5:
1323                 disp_ret = init_sam_dispinfo_5(p->mem_ctx, &ctr->sam.info5,
1324                                                num_account, enum_context,
1325                                                entries);
1326                 break;
1327         default:
1328                 smb_panic("info class changed");
1329                 break;
1330         }
1331
1332         if (!NT_STATUS_IS_OK(disp_ret))
1333                 return disp_ret;
1334
1335         /* calculate the total size */
1336         total_data_size=num_account*struct_size;
1337
1338         if (num_account) {
1339                 r_u->status = STATUS_MORE_ENTRIES;
1340         } else {
1341                 r_u->status = NT_STATUS_OK;
1342         }
1343
1344         /* Ensure we cache this enumeration. */
1345         set_disp_info_cache_timeout(info->disp_info, DISP_INFO_CACHE_TIMEOUT);
1346
1347         DEBUG(5, ("_samr_query_dispinfo: %d\n", __LINE__));
1348
1349         init_samr_r_query_dispinfo(r_u, num_account, total_data_size,
1350                                    temp_size, q_u->switch_level, ctr,
1351                                    r_u->status);
1352
1353         return r_u->status;
1354
1355 }
1356
1357 /*******************************************************************
1358  samr_reply_query_aliasinfo
1359  ********************************************************************/
1360
1361 NTSTATUS _samr_query_aliasinfo(pipes_struct *p, SAMR_Q_QUERY_ALIASINFO *q_u, SAMR_R_QUERY_ALIASINFO *r_u)
1362 {
1363         DOM_SID   sid;
1364         struct acct_info info;
1365         uint32    acc_granted;
1366         BOOL ret;
1367
1368         r_u->status = NT_STATUS_OK;
1369
1370         DEBUG(5,("_samr_query_aliasinfo: %d\n", __LINE__));
1371
1372         /* find the policy handle.  open a policy on it. */
1373         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &sid, &acc_granted, NULL))
1374                 return NT_STATUS_INVALID_HANDLE;
1375         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_ALIAS_LOOKUP_INFO, "_samr_query_aliasinfo"))) {
1376                 return r_u->status;
1377         }
1378
1379         become_root();
1380         ret = pdb_get_aliasinfo(&sid, &info);
1381         unbecome_root();
1382         
1383         if ( !ret )
1384                 return NT_STATUS_NO_SUCH_ALIAS;
1385
1386         if ( !(r_u->ctr = TALLOC_ZERO_P( p->mem_ctx, ALIAS_INFO_CTR )) ) 
1387                 return NT_STATUS_NO_MEMORY;
1388
1389
1390         switch (q_u->level ) {
1391         case 1:
1392                 r_u->ctr->level = 1;
1393                 init_samr_alias_info1(&r_u->ctr->alias.info1, info.acct_name, 1, info.acct_desc);
1394                 break;
1395         case 3:
1396                 r_u->ctr->level = 3;
1397                 init_samr_alias_info3(&r_u->ctr->alias.info3, info.acct_desc);
1398                 break;
1399         default:
1400                 return NT_STATUS_INVALID_INFO_CLASS;
1401         }
1402
1403         DEBUG(5,("_samr_query_aliasinfo: %d\n", __LINE__));
1404
1405         return r_u->status;
1406 }
1407
1408 #if 0
1409 /*******************************************************************
1410  samr_reply_lookup_ids
1411  ********************************************************************/
1412
1413  uint32 _samr_lookup_ids(pipes_struct *p, SAMR_Q_LOOKUP_IDS *q_u, SAMR_R_LOOKUP_IDS *r_u)
1414 {
1415     uint32 rid[MAX_SAM_ENTRIES];
1416     int num_rids = q_u->num_sids1;
1417
1418     r_u->status = NT_STATUS_OK;
1419
1420     DEBUG(5,("_samr_lookup_ids: %d\n", __LINE__));
1421
1422     if (num_rids > MAX_SAM_ENTRIES) {
1423         num_rids = MAX_SAM_ENTRIES;
1424         DEBUG(5,("_samr_lookup_ids: truncating entries to %d\n", num_rids));
1425     }
1426
1427 #if 0
1428     int i;
1429     SMB_ASSERT_ARRAY(q_u->uni_user_name, num_rids);
1430
1431     for (i = 0; i < num_rids && status == 0; i++)
1432     {
1433         struct sam_passwd *sam_pass;
1434         fstring user_name;
1435
1436
1437         fstrcpy(user_name, unistrn2(q_u->uni_user_name[i].buffer,
1438                                     q_u->uni_user_name[i].uni_str_len));
1439
1440         /* find the user account */
1441         become_root();
1442         sam_pass = get_smb21pwd_entry(user_name, 0);
1443         unbecome_root();
1444
1445         if (sam_pass == NULL)
1446         {
1447             status = 0xC0000000 | NT_STATUS_NO_SUCH_USER;
1448             rid[i] = 0;
1449         }
1450         else
1451         {
1452             rid[i] = sam_pass->user_rid;
1453         }
1454     }
1455 #endif
1456
1457     num_rids = 1;
1458     rid[0] = BUILTIN_ALIAS_RID_USERS;
1459
1460     init_samr_r_lookup_ids(&r_u, num_rids, rid, NT_STATUS_OK);
1461
1462     DEBUG(5,("_samr_lookup_ids: %d\n", __LINE__));
1463
1464     return r_u->status;
1465 }
1466 #endif
1467
1468 /*******************************************************************
1469  _samr_lookup_names
1470  ********************************************************************/
1471
1472 NTSTATUS _samr_lookup_names(pipes_struct *p, SAMR_Q_LOOKUP_NAMES *q_u, SAMR_R_LOOKUP_NAMES *r_u)
1473 {
1474         uint32 rid[MAX_SAM_ENTRIES];
1475         enum lsa_SidType type[MAX_SAM_ENTRIES];
1476         int i;
1477         int num_rids = q_u->num_names2;
1478         DOM_SID pol_sid;
1479         fstring sid_str;
1480         uint32  acc_granted;
1481
1482         r_u->status = NT_STATUS_OK;
1483
1484         DEBUG(5,("_samr_lookup_names: %d\n", __LINE__));
1485
1486         ZERO_ARRAY(rid);
1487         ZERO_ARRAY(type);
1488
1489         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &pol_sid, &acc_granted, NULL)) {
1490                 init_samr_r_lookup_names(p->mem_ctx, r_u, 0, NULL, NULL, NT_STATUS_OBJECT_TYPE_MISMATCH);
1491                 return r_u->status;
1492         }
1493         
1494         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, 0, "_samr_lookup_names"))) { /* Don't know the acc_bits yet */
1495                 return r_u->status;
1496         }
1497
1498         if (num_rids > MAX_SAM_ENTRIES) {
1499                 num_rids = MAX_SAM_ENTRIES;
1500                 DEBUG(5,("_samr_lookup_names: truncating entries to %d\n", num_rids));
1501         }
1502
1503         DEBUG(5,("_samr_lookup_names: looking name on SID %s\n", sid_to_string(sid_str, &pol_sid)));
1504         
1505         for (i = 0; i < num_rids; i++) {
1506                 fstring name;
1507                 int ret;
1508
1509                 r_u->status = NT_STATUS_NONE_MAPPED;
1510                 type[i] = SID_NAME_UNKNOWN;
1511
1512                 rid [i] = 0xffffffff;
1513
1514                 ret = rpcstr_pull(name, q_u->uni_name[i].buffer, sizeof(name), q_u->uni_name[i].uni_str_len*2, 0);
1515
1516                 if (ret <= 0) {
1517                         continue;
1518                 }
1519
1520                 if (sid_check_is_builtin(&pol_sid)) {
1521                         if (lookup_builtin_name(name, &rid[i])) {
1522                                 type[i] = SID_NAME_ALIAS;
1523                         }
1524                 } else {
1525                         lookup_global_sam_name(name, 0, &rid[i], &type[i]);
1526                 }
1527
1528                 if (type[i] != SID_NAME_UNKNOWN) {
1529                         r_u->status = NT_STATUS_OK;
1530                 }
1531         }
1532
1533         init_samr_r_lookup_names(p->mem_ctx, r_u, num_rids, rid, type, r_u->status);
1534
1535         DEBUG(5,("_samr_lookup_names: %d\n", __LINE__));
1536
1537         return r_u->status;
1538 }
1539
1540 /*******************************************************************
1541  _samr_chgpasswd_user
1542  ********************************************************************/
1543
1544 NTSTATUS _samr_chgpasswd_user(pipes_struct *p, SAMR_Q_CHGPASSWD_USER *q_u, SAMR_R_CHGPASSWD_USER *r_u)
1545 {
1546         fstring user_name;
1547         fstring wks;
1548
1549         DEBUG(5,("_samr_chgpasswd_user: %d\n", __LINE__));
1550
1551         r_u->status = NT_STATUS_OK;
1552
1553         rpcstr_pull(user_name, q_u->uni_user_name.buffer, sizeof(user_name), q_u->uni_user_name.uni_str_len*2, 0);
1554         rpcstr_pull(wks, q_u->uni_dest_host.buffer, sizeof(wks), q_u->uni_dest_host.uni_str_len*2,0);
1555
1556         DEBUG(5,("samr_chgpasswd_user: user: %s wks: %s\n", user_name, wks));
1557
1558         /*
1559          * Pass the user through the NT -> unix user mapping
1560          * function.
1561          */
1562  
1563         (void)map_username(user_name);
1564  
1565         /*
1566          * UNIX username case mangling not required, pass_oem_change 
1567          * is case insensitive.
1568          */
1569
1570         r_u->status = pass_oem_change(user_name, q_u->lm_newpass.pass, q_u->lm_oldhash.hash,
1571                                 q_u->nt_newpass.pass, q_u->nt_oldhash.hash, NULL);
1572
1573         init_samr_r_chgpasswd_user(r_u, r_u->status);
1574
1575         DEBUG(5,("_samr_chgpasswd_user: %d\n", __LINE__));
1576
1577         return r_u->status;
1578 }
1579
1580 /*******************************************************************
1581  _samr_chgpasswd_user3
1582  ********************************************************************/
1583
1584 NTSTATUS _samr_chgpasswd_user3(pipes_struct *p, SAMR_Q_CHGPASSWD_USER3 *q_u, SAMR_R_CHGPASSWD_USER3 *r_u)
1585 {
1586         fstring user_name;
1587         fstring wks;
1588         uint32 reject_reason;
1589         SAM_UNK_INFO_1 *info = NULL;
1590         SAMR_CHANGE_REJECT *reject = NULL;
1591
1592         DEBUG(5,("_samr_chgpasswd_user3: %d\n", __LINE__));
1593
1594         rpcstr_pull(user_name, q_u->uni_user_name.buffer, sizeof(user_name), q_u->uni_user_name.uni_str_len*2, 0);
1595         rpcstr_pull(wks, q_u->uni_dest_host.buffer, sizeof(wks), q_u->uni_dest_host.uni_str_len*2,0);
1596
1597         DEBUG(5,("_samr_chgpasswd_user3: user: %s wks: %s\n", user_name, wks));
1598
1599         /*
1600          * Pass the user through the NT -> unix user mapping
1601          * function.
1602          */
1603  
1604         (void)map_username(user_name);
1605  
1606         /*
1607          * UNIX username case mangling not required, pass_oem_change 
1608          * is case insensitive.
1609          */
1610
1611         r_u->status = pass_oem_change(user_name, q_u->lm_newpass.pass, q_u->lm_oldhash.hash,
1612                                       q_u->nt_newpass.pass, q_u->nt_oldhash.hash, &reject_reason);
1613
1614         if (NT_STATUS_EQUAL(r_u->status, NT_STATUS_PASSWORD_RESTRICTION) || 
1615             NT_STATUS_EQUAL(r_u->status, NT_STATUS_ACCOUNT_RESTRICTION)) {
1616
1617                 uint32 min_pass_len,pass_hist,password_properties;
1618                 time_t u_expire, u_min_age;
1619                 NTTIME nt_expire, nt_min_age;
1620                 uint32 account_policy_temp;
1621
1622                 if ((info = TALLOC_ZERO_P(p->mem_ctx, SAM_UNK_INFO_1)) == NULL) {
1623                         return NT_STATUS_NO_MEMORY;
1624                 }
1625
1626                 if ((reject = TALLOC_ZERO_P(p->mem_ctx, SAMR_CHANGE_REJECT)) == NULL) {
1627                         return NT_STATUS_NO_MEMORY;
1628                 }
1629
1630                 ZERO_STRUCTP(info);
1631                 ZERO_STRUCTP(reject);
1632
1633                 become_root();
1634
1635                 /* AS ROOT !!! */
1636
1637                 pdb_get_account_policy(AP_MIN_PASSWORD_LEN, &account_policy_temp);
1638                 min_pass_len = account_policy_temp;
1639
1640                 pdb_get_account_policy(AP_PASSWORD_HISTORY, &account_policy_temp);
1641                 pass_hist = account_policy_temp;
1642
1643                 pdb_get_account_policy(AP_USER_MUST_LOGON_TO_CHG_PASS, &account_policy_temp);
1644                 password_properties = account_policy_temp;
1645
1646                 pdb_get_account_policy(AP_MAX_PASSWORD_AGE, &account_policy_temp);
1647                 u_expire = account_policy_temp;
1648
1649                 pdb_get_account_policy(AP_MIN_PASSWORD_AGE, &account_policy_temp);
1650                 u_min_age = account_policy_temp;
1651
1652                 /* !AS ROOT */
1653                 
1654                 unbecome_root();
1655
1656                 unix_to_nt_time_abs(&nt_expire, u_expire);
1657                 unix_to_nt_time_abs(&nt_min_age, u_min_age);
1658
1659                 init_unk_info1(info, (uint16)min_pass_len, (uint16)pass_hist, 
1660                                password_properties, nt_expire, nt_min_age);
1661
1662                 reject->reject_reason = reject_reason;
1663         }
1664         
1665         init_samr_r_chgpasswd_user3(r_u, r_u->status, reject, info);
1666
1667         DEBUG(5,("_samr_chgpasswd_user3: %d\n", __LINE__));
1668
1669         return r_u->status;
1670 }
1671
1672 /*******************************************************************
1673 makes a SAMR_R_LOOKUP_RIDS structure.
1674 ********************************************************************/
1675
1676 static BOOL make_samr_lookup_rids(TALLOC_CTX *ctx, uint32 num_names,
1677                                   const char **names, UNIHDR **pp_hdr_name,
1678                                   UNISTR2 **pp_uni_name)
1679 {
1680         uint32 i;
1681         UNIHDR *hdr_name=NULL;
1682         UNISTR2 *uni_name=NULL;
1683
1684         *pp_uni_name = NULL;
1685         *pp_hdr_name = NULL;
1686
1687         if (num_names != 0) {
1688                 hdr_name = TALLOC_ZERO_ARRAY(ctx, UNIHDR, num_names);
1689                 if (hdr_name == NULL)
1690                         return False;
1691
1692                 uni_name = TALLOC_ZERO_ARRAY(ctx,UNISTR2, num_names);
1693                 if (uni_name == NULL)
1694                         return False;
1695         }
1696
1697         for (i = 0; i < num_names; i++) {
1698                 DEBUG(10, ("names[%d]:%s\n", i, names[i] && *names[i] ? names[i] : ""));
1699                 init_unistr2(&uni_name[i], names[i], UNI_FLAGS_NONE);
1700                 init_uni_hdr(&hdr_name[i], &uni_name[i]);
1701         }
1702
1703         *pp_uni_name = uni_name;
1704         *pp_hdr_name = hdr_name;
1705
1706         return True;
1707 }
1708
1709 /*******************************************************************
1710  _samr_lookup_rids
1711  ********************************************************************/
1712
1713 NTSTATUS _samr_lookup_rids(pipes_struct *p, SAMR_Q_LOOKUP_RIDS *q_u, SAMR_R_LOOKUP_RIDS *r_u)
1714 {
1715         const char **names;
1716         enum lsa_SidType *attrs = NULL;
1717         uint32 *wire_attrs = NULL;
1718         UNIHDR *hdr_name = NULL;
1719         UNISTR2 *uni_name = NULL;
1720         DOM_SID pol_sid;
1721         int num_rids = q_u->num_rids1;
1722         uint32 acc_granted;
1723         int i;
1724
1725         r_u->status = NT_STATUS_OK;
1726
1727         DEBUG(5,("_samr_lookup_rids: %d\n", __LINE__));
1728
1729         /* find the policy handle.  open a policy on it. */
1730         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &pol_sid, &acc_granted, NULL))
1731                 return NT_STATUS_INVALID_HANDLE;
1732
1733         if (num_rids > 1000) {
1734                 DEBUG(0, ("Got asked for %d rids (more than 1000) -- according "
1735                           "to samba4 idl this is not possible\n", num_rids));
1736                 return NT_STATUS_UNSUCCESSFUL;
1737         }
1738
1739         names = TALLOC_ZERO_ARRAY(p->mem_ctx, const char *, num_rids);
1740         attrs = TALLOC_ZERO_ARRAY(p->mem_ctx, enum lsa_SidType, num_rids);
1741         wire_attrs = TALLOC_ZERO_ARRAY(p->mem_ctx, uint32, num_rids);
1742
1743         if ((num_rids != 0) && ((names == NULL) || (attrs == NULL) || (wire_attrs==NULL)))
1744                 return NT_STATUS_NO_MEMORY;
1745
1746         become_root();  /* lookup_sid can require root privs */
1747         r_u->status = pdb_lookup_rids(&pol_sid, num_rids, q_u->rid,
1748                                       names, attrs);
1749         unbecome_root();
1750
1751         if ( NT_STATUS_EQUAL(r_u->status, NT_STATUS_NONE_MAPPED) && (num_rids == 0) ) {
1752                 r_u->status = NT_STATUS_OK;
1753         }
1754
1755         if(!make_samr_lookup_rids(p->mem_ctx, num_rids, names,
1756                                   &hdr_name, &uni_name))
1757                 return NT_STATUS_NO_MEMORY;
1758
1759         /* Convert from enum lsa_SidType to uint32 for wire format. */
1760         for (i = 0; i < num_rids; i++) {
1761                 wire_attrs[i] = (uint32)attrs[i];
1762         }
1763
1764         init_samr_r_lookup_rids(r_u, num_rids, hdr_name, uni_name, wire_attrs);
1765
1766         DEBUG(5,("_samr_lookup_rids: %d\n", __LINE__));
1767
1768         return r_u->status;
1769 }
1770
1771 /*******************************************************************
1772  _samr_open_user. Safe - gives out no passwd info.
1773  ********************************************************************/
1774
1775 NTSTATUS _samr_open_user(pipes_struct *p, SAMR_Q_OPEN_USER *q_u, SAMR_R_OPEN_USER *r_u)
1776 {
1777         struct samu *sampass=NULL;
1778         DOM_SID sid;
1779         POLICY_HND domain_pol = q_u->domain_pol;
1780         POLICY_HND *user_pol = &r_u->user_pol;
1781         struct samr_info *info = NULL;
1782         SEC_DESC *psd = NULL;
1783         uint32    acc_granted;
1784         uint32    des_access = q_u->access_mask;
1785         size_t    sd_size;
1786         BOOL ret;
1787         NTSTATUS nt_status;
1788         SE_PRIV se_rights;
1789
1790         r_u->status = NT_STATUS_OK;
1791
1792         /* find the domain policy handle and get domain SID / access bits in the domain policy. */
1793         
1794         if ( !get_lsa_policy_samr_sid(p, &domain_pol, &sid, &acc_granted, NULL) )
1795                 return NT_STATUS_INVALID_HANDLE;
1796         
1797         nt_status = access_check_samr_function( acc_granted, 
1798                 SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_open_user" );
1799                 
1800         if ( !NT_STATUS_IS_OK(nt_status) )
1801                 return nt_status;
1802
1803         if ( !(sampass = samu_new( p->mem_ctx )) ) {
1804                 return NT_STATUS_NO_MEMORY;
1805         }
1806
1807         /* append the user's RID to it */
1808         
1809         if (!sid_append_rid(&sid, q_u->user_rid))
1810                 return NT_STATUS_NO_SUCH_USER;
1811         
1812         /* check if access can be granted as requested by client. */
1813         
1814         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &usr_generic_mapping, &sid, SAMR_USR_RIGHTS_WRITE_PW);
1815         se_map_generic(&des_access, &usr_generic_mapping);
1816         
1817         se_priv_copy( &se_rights, &se_machine_account );
1818         se_priv_add( &se_rights, &se_add_users );
1819         
1820         nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
1821                 &se_rights, GENERIC_RIGHTS_USER_WRITE, des_access, 
1822                 &acc_granted, "_samr_open_user");
1823                 
1824         if ( !NT_STATUS_IS_OK(nt_status) )
1825                 return nt_status;
1826
1827         become_root();
1828         ret=pdb_getsampwsid(sampass, &sid);
1829         unbecome_root();
1830
1831         /* check that the SID exists in our domain. */
1832         if (ret == False) {
1833                 return NT_STATUS_NO_SUCH_USER;
1834         }
1835
1836         TALLOC_FREE(sampass);
1837
1838         /* associate the user's SID and access bits with the new handle. */
1839         if ((info = get_samr_info_by_sid(&sid)) == NULL)
1840                 return NT_STATUS_NO_MEMORY;
1841         info->acc_granted = acc_granted;
1842
1843         /* get a (unique) handle.  open a policy on it. */
1844         if (!create_policy_hnd(p, user_pol, free_samr_info, (void *)info))
1845                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1846
1847         return r_u->status;
1848 }
1849
1850 /*************************************************************************
1851  get_user_info_7. Safe. Only gives out account_name.
1852  *************************************************************************/
1853
1854 static NTSTATUS get_user_info_7(TALLOC_CTX *mem_ctx, SAM_USER_INFO_7 *id7, DOM_SID *user_sid)
1855 {
1856         struct samu *smbpass=NULL;
1857         BOOL ret;
1858
1859         if ( !(smbpass = samu_new( mem_ctx )) ) {
1860                 return NT_STATUS_NO_MEMORY;
1861         }
1862         
1863         become_root();
1864         ret = pdb_getsampwsid(smbpass, user_sid);
1865         unbecome_root();
1866
1867         if ( !ret ) {
1868                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
1869                 return NT_STATUS_NO_SUCH_USER;
1870         }
1871
1872         DEBUG(3,("User:[%s]\n", pdb_get_username(smbpass) ));
1873
1874         ZERO_STRUCTP(id7);
1875         init_sam_user_info7(id7, pdb_get_username(smbpass) );
1876
1877         TALLOC_FREE(smbpass);
1878
1879         return NT_STATUS_OK;
1880 }
1881
1882 /*************************************************************************
1883  get_user_info_9. Only gives out primary group SID.
1884  *************************************************************************/
1885 static NTSTATUS get_user_info_9(TALLOC_CTX *mem_ctx, SAM_USER_INFO_9 * id9, DOM_SID *user_sid)
1886 {
1887         struct samu *smbpass=NULL;
1888         BOOL ret;
1889
1890         if ( !(smbpass = samu_new( mem_ctx )) ) {
1891                 return NT_STATUS_NO_MEMORY;
1892         }
1893
1894         become_root();
1895         ret = pdb_getsampwsid(smbpass, user_sid);
1896         unbecome_root();
1897
1898         if (ret==False) {
1899                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
1900                 return NT_STATUS_NO_SUCH_USER;
1901         }
1902
1903         DEBUG(3,("User:[%s]\n", pdb_get_username(smbpass) ));
1904
1905         ZERO_STRUCTP(id9);
1906         init_sam_user_info9(id9, pdb_get_group_rid(smbpass) );
1907
1908         TALLOC_FREE(smbpass);
1909
1910         return NT_STATUS_OK;
1911 }
1912
1913 /*************************************************************************
1914  get_user_info_16. Safe. Only gives out acb bits.
1915  *************************************************************************/
1916
1917 static NTSTATUS get_user_info_16(TALLOC_CTX *mem_ctx, SAM_USER_INFO_16 *id16, DOM_SID *user_sid)
1918 {
1919         struct samu *smbpass=NULL;
1920         BOOL ret;
1921
1922         if ( !(smbpass = samu_new( mem_ctx )) ) {
1923                 return NT_STATUS_NO_MEMORY;
1924         }
1925
1926         become_root();
1927         ret = pdb_getsampwsid(smbpass, user_sid);
1928         unbecome_root();
1929
1930         if (ret==False) {
1931                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
1932                 return NT_STATUS_NO_SUCH_USER;
1933         }
1934
1935         DEBUG(3,("User:[%s]\n", pdb_get_username(smbpass) ));
1936
1937         ZERO_STRUCTP(id16);
1938         init_sam_user_info16(id16, pdb_get_acct_ctrl(smbpass) );
1939
1940         TALLOC_FREE(smbpass);
1941
1942         return NT_STATUS_OK;
1943 }
1944
1945 /*************************************************************************
1946  get_user_info_18. OK - this is the killer as it gives out password info.
1947  Ensure that this is only allowed on an encrypted connection with a root
1948  user. JRA. 
1949  *************************************************************************/
1950
1951 static NTSTATUS get_user_info_18(pipes_struct *p, TALLOC_CTX *mem_ctx, SAM_USER_INFO_18 * id18, DOM_SID *user_sid)
1952 {
1953         struct samu *smbpass=NULL;
1954         BOOL ret;
1955
1956         if (p->auth.auth_type != PIPE_AUTH_TYPE_NTLMSSP || p->auth.auth_type != PIPE_AUTH_TYPE_SPNEGO_NTLMSSP) {
1957                 return NT_STATUS_ACCESS_DENIED;
1958         }
1959
1960         if (p->auth.auth_level != PIPE_AUTH_LEVEL_PRIVACY) {
1961                 return NT_STATUS_ACCESS_DENIED;
1962         }
1963
1964         /*
1965          * Do *NOT* do become_root()/unbecome_root() here ! JRA.
1966          */
1967
1968         if ( !(smbpass = samu_new( mem_ctx )) ) {
1969                 return NT_STATUS_NO_MEMORY;
1970         }
1971
1972         ret = pdb_getsampwsid(smbpass, user_sid);
1973
1974         if (ret == False) {
1975                 DEBUG(4, ("User %s not found\n", sid_string_static(user_sid)));
1976                 TALLOC_FREE(smbpass);
1977                 return (geteuid() == (uid_t)0) ? NT_STATUS_NO_SUCH_USER : NT_STATUS_ACCESS_DENIED;
1978         }
1979
1980         DEBUG(3,("User:[%s] 0x%x\n", pdb_get_username(smbpass), pdb_get_acct_ctrl(smbpass) ));
1981
1982         if ( pdb_get_acct_ctrl(smbpass) & ACB_DISABLED) {
1983                 TALLOC_FREE(smbpass);
1984                 return NT_STATUS_ACCOUNT_DISABLED;
1985         }
1986
1987         ZERO_STRUCTP(id18);
1988         init_sam_user_info18(id18, pdb_get_lanman_passwd(smbpass), pdb_get_nt_passwd(smbpass));
1989         
1990         TALLOC_FREE(smbpass);
1991
1992         return NT_STATUS_OK;
1993 }
1994
1995 /*************************************************************************
1996  get_user_info_20
1997  *************************************************************************/
1998
1999 static NTSTATUS get_user_info_20(TALLOC_CTX *mem_ctx, SAM_USER_INFO_20 *id20, DOM_SID *user_sid)
2000 {
2001         struct samu *sampass=NULL;
2002         BOOL ret;
2003
2004         if ( !(sampass = samu_new( mem_ctx )) ) {
2005                 return NT_STATUS_NO_MEMORY;
2006         }
2007
2008         become_root();
2009         ret = pdb_getsampwsid(sampass, user_sid);
2010         unbecome_root();
2011
2012         if (ret == False) {
2013                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
2014                 return NT_STATUS_NO_SUCH_USER;
2015         }
2016
2017         samr_clear_sam_passwd(sampass);
2018
2019         DEBUG(3,("User:[%s]\n",  pdb_get_username(sampass) ));
2020
2021         ZERO_STRUCTP(id20);
2022         init_sam_user_info20A(id20, sampass);
2023         
2024         TALLOC_FREE(sampass);
2025
2026         return NT_STATUS_OK;
2027 }
2028
2029 /*************************************************************************
2030  get_user_info_21
2031  *************************************************************************/
2032
2033 static NTSTATUS get_user_info_21(TALLOC_CTX *mem_ctx, SAM_USER_INFO_21 *id21, 
2034                                  DOM_SID *user_sid, DOM_SID *domain_sid)
2035 {
2036         struct samu *sampass=NULL;
2037         BOOL ret;
2038         NTSTATUS nt_status;
2039
2040         if ( !(sampass = samu_new( mem_ctx )) ) {
2041                 return NT_STATUS_NO_MEMORY;
2042         }
2043
2044         become_root();
2045         ret = pdb_getsampwsid(sampass, user_sid);
2046         unbecome_root();
2047
2048         if (ret == False) {
2049                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
2050                 return NT_STATUS_NO_SUCH_USER;
2051         }
2052
2053         samr_clear_sam_passwd(sampass);
2054
2055         DEBUG(3,("User:[%s]\n",  pdb_get_username(sampass) ));
2056
2057         ZERO_STRUCTP(id21);
2058         nt_status = init_sam_user_info21A(id21, sampass, domain_sid);
2059         
2060         TALLOC_FREE(sampass);
2061
2062         return nt_status;
2063 }
2064
2065 /*******************************************************************
2066  _samr_query_userinfo
2067  ********************************************************************/
2068
2069 NTSTATUS _samr_query_userinfo(pipes_struct *p, SAMR_Q_QUERY_USERINFO *q_u, SAMR_R_QUERY_USERINFO *r_u)
2070 {
2071         SAM_USERINFO_CTR *ctr;
2072         struct samr_info *info = NULL;
2073         DOM_SID domain_sid;
2074         uint32 rid;
2075         
2076         r_u->status=NT_STATUS_OK;
2077
2078         /* search for the handle */
2079         if (!find_policy_by_hnd(p, &q_u->pol, (void **)(void *)&info))
2080                 return NT_STATUS_INVALID_HANDLE;
2081
2082         domain_sid = info->sid;
2083
2084         sid_split_rid(&domain_sid, &rid);
2085
2086         if (!sid_check_is_in_our_domain(&info->sid))
2087                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
2088
2089         DEBUG(5,("_samr_query_userinfo: sid:%s\n", sid_string_static(&info->sid)));
2090
2091         ctr = TALLOC_ZERO_P(p->mem_ctx, SAM_USERINFO_CTR);
2092         if (!ctr)
2093                 return NT_STATUS_NO_MEMORY;
2094
2095         ZERO_STRUCTP(ctr);
2096
2097         /* ok!  user info levels (lots: see MSDEV help), off we go... */
2098         ctr->switch_value = q_u->switch_value;
2099
2100         DEBUG(5,("_samr_query_userinfo: user info level: %d\n", q_u->switch_value));
2101
2102         switch (q_u->switch_value) {
2103         case 7:
2104                 ctr->info.id7 = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_7);
2105                 if (ctr->info.id7 == NULL)
2106                         return NT_STATUS_NO_MEMORY;
2107
2108                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_7(p->mem_ctx, ctr->info.id7, &info->sid)))
2109                         return r_u->status;
2110                 break;
2111         case 9:
2112                 ctr->info.id9 = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_9);
2113                 if (ctr->info.id9 == NULL)
2114                         return NT_STATUS_NO_MEMORY;
2115
2116                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_9(p->mem_ctx, ctr->info.id9, &info->sid)))
2117                         return r_u->status;
2118                 break;
2119         case 16:
2120                 ctr->info.id16 = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_16);
2121                 if (ctr->info.id16 == NULL)
2122                         return NT_STATUS_NO_MEMORY;
2123
2124                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_16(p->mem_ctx, ctr->info.id16, &info->sid)))
2125                         return r_u->status;
2126                 break;
2127
2128         case 18:
2129                 ctr->info.id18 = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_18);
2130                 if (ctr->info.id18 == NULL)
2131                         return NT_STATUS_NO_MEMORY;
2132
2133                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_18(p, p->mem_ctx, ctr->info.id18, &info->sid)))
2134                         return r_u->status;
2135                 break;
2136                 
2137         case 20:
2138                 ctr->info.id20 = TALLOC_ZERO_P(p->mem_ctx,SAM_USER_INFO_20);
2139                 if (ctr->info.id20 == NULL)
2140                         return NT_STATUS_NO_MEMORY;
2141                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_20(p->mem_ctx, ctr->info.id20, &info->sid)))
2142                         return r_u->status;
2143                 break;
2144
2145         case 21:
2146                 ctr->info.id21 = TALLOC_ZERO_P(p->mem_ctx,SAM_USER_INFO_21);
2147                 if (ctr->info.id21 == NULL)
2148                         return NT_STATUS_NO_MEMORY;
2149                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_21(p->mem_ctx, ctr->info.id21, 
2150                                                                     &info->sid, &domain_sid)))
2151                         return r_u->status;
2152                 break;
2153
2154         default:
2155                 return NT_STATUS_INVALID_INFO_CLASS;
2156         }
2157
2158         init_samr_r_query_userinfo(r_u, ctr, r_u->status);
2159
2160         DEBUG(5,("_samr_query_userinfo: %d\n", __LINE__));
2161         
2162         return r_u->status;
2163 }
2164
2165 /*******************************************************************
2166  samr_reply_query_usergroups
2167  ********************************************************************/
2168
2169 NTSTATUS _samr_query_usergroups(pipes_struct *p, SAMR_Q_QUERY_USERGROUPS *q_u, SAMR_R_QUERY_USERGROUPS *r_u)
2170 {
2171         struct samu *sam_pass=NULL;
2172         DOM_SID  sid;
2173         DOM_SID *sids;
2174         DOM_GID dom_gid;
2175         DOM_GID *gids = NULL;
2176         uint32 primary_group_rid;
2177         size_t num_groups = 0;
2178         gid_t *unix_gids;
2179         size_t i, num_gids;
2180         uint32 acc_granted;
2181         BOOL ret;
2182         NTSTATUS result;
2183         BOOL success = False;
2184
2185         /*
2186          * from the SID in the request:
2187          * we should send back the list of DOMAIN GROUPS
2188          * the user is a member of
2189          *
2190          * and only the DOMAIN GROUPS
2191          * no ALIASES !!! neither aliases of the domain
2192          * nor aliases of the builtin SID
2193          *
2194          * JFM, 12/2/2001
2195          */
2196
2197         r_u->status = NT_STATUS_OK;
2198
2199         DEBUG(5,("_samr_query_usergroups: %d\n", __LINE__));
2200
2201         /* find the policy handle.  open a policy on it. */
2202         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &sid, &acc_granted, NULL))
2203                 return NT_STATUS_INVALID_HANDLE;
2204         
2205         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_USER_GET_GROUPS, "_samr_query_usergroups"))) {
2206                 return r_u->status;
2207         }
2208
2209         if (!sid_check_is_in_our_domain(&sid))
2210                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
2211
2212         if ( !(sam_pass = samu_new( p->mem_ctx )) ) {
2213                 return NT_STATUS_NO_MEMORY;
2214         }
2215
2216         become_root();
2217         ret = pdb_getsampwsid(sam_pass, &sid);
2218         unbecome_root();
2219
2220         if (!ret) {
2221                 DEBUG(10, ("pdb_getsampwsid failed for %s\n",
2222                            sid_string_static(&sid)));
2223                 return NT_STATUS_NO_SUCH_USER;
2224         }
2225
2226         sids = NULL;
2227
2228         /* make both calls inside the root block */
2229         become_root();
2230         result = pdb_enum_group_memberships(p->mem_ctx, sam_pass,
2231                                             &sids, &unix_gids, &num_groups);
2232         if ( NT_STATUS_IS_OK(result) ) {
2233                 success = sid_peek_check_rid(get_global_sam_sid(), 
2234                                              pdb_get_group_sid(sam_pass),
2235                                              &primary_group_rid);
2236         }
2237         unbecome_root();
2238
2239         if (!NT_STATUS_IS_OK(result)) {
2240                 DEBUG(10, ("pdb_enum_group_memberships failed for %s\n",
2241                            sid_string_static(&sid)));
2242                 return result;
2243         }
2244
2245         if ( !success ) {
2246                 DEBUG(5, ("Group sid %s for user %s not in our domain\n",
2247                           sid_string_static(pdb_get_group_sid(sam_pass)),
2248                           pdb_get_username(sam_pass)));
2249                 TALLOC_FREE(sam_pass);
2250                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2251         }
2252
2253         gids = NULL;
2254         num_gids = 0;
2255
2256         dom_gid.attr = (SE_GROUP_MANDATORY|SE_GROUP_ENABLED_BY_DEFAULT|
2257                         SE_GROUP_ENABLED);
2258         dom_gid.g_rid = primary_group_rid;
2259         ADD_TO_ARRAY(p->mem_ctx, DOM_GID, dom_gid, &gids, &num_gids);
2260
2261         for (i=0; i<num_groups; i++) {
2262
2263                 if (!sid_peek_check_rid(get_global_sam_sid(),
2264                                         &(sids[i]), &dom_gid.g_rid)) {
2265                         DEBUG(10, ("Found sid %s not in our domain\n",
2266                                    sid_string_static(&sids[i])));
2267                         continue;
2268                 }
2269
2270                 if (dom_gid.g_rid == primary_group_rid) {
2271                         /* We added the primary group directly from the
2272                          * sam_account. The other SIDs are unique from
2273                          * enum_group_memberships */
2274                         continue;
2275                 }
2276
2277                 ADD_TO_ARRAY(p->mem_ctx, DOM_GID, dom_gid, &gids, &num_gids);
2278         }
2279         
2280         /* construct the response.  lkclXXXX: gids are not copied! */
2281         init_samr_r_query_usergroups(r_u, num_gids, gids, r_u->status);
2282         
2283         DEBUG(5,("_samr_query_usergroups: %d\n", __LINE__));
2284         
2285         return r_u->status;
2286 }
2287
2288 /*******************************************************************
2289  _samr_query_domain_info
2290  ********************************************************************/
2291
2292 NTSTATUS _samr_query_domain_info(pipes_struct *p, 
2293                                  SAMR_Q_QUERY_DOMAIN_INFO *q_u, 
2294                                  SAMR_R_QUERY_DOMAIN_INFO *r_u)
2295 {
2296         struct samr_info *info = NULL;
2297         SAM_UNK_CTR *ctr;
2298         uint32 min_pass_len,pass_hist,password_properties;
2299         time_t u_expire, u_min_age;
2300         NTTIME nt_expire, nt_min_age;
2301
2302         time_t u_lock_duration, u_reset_time;
2303         NTTIME nt_lock_duration, nt_reset_time;
2304         uint32 lockout;
2305         time_t u_logout;
2306         NTTIME nt_logout;
2307
2308         uint32 account_policy_temp;
2309
2310         time_t seq_num;
2311         uint32 server_role;
2312
2313         uint32 num_users=0, num_groups=0, num_aliases=0;
2314
2315         if ((ctr = TALLOC_ZERO_P(p->mem_ctx, SAM_UNK_CTR)) == NULL) {
2316                 return NT_STATUS_NO_MEMORY;
2317         }
2318
2319         ZERO_STRUCTP(ctr);
2320
2321         r_u->status = NT_STATUS_OK;
2322         
2323         DEBUG(5,("_samr_query_domain_info: %d\n", __LINE__));
2324         
2325         /* find the policy handle.  open a policy on it. */
2326         if (!find_policy_by_hnd(p, &q_u->domain_pol, (void **)(void *)&info)) {
2327                 return NT_STATUS_INVALID_HANDLE;
2328         }
2329         
2330         switch (q_u->switch_value) {
2331                 case 0x01:
2332                         
2333                         become_root();
2334
2335                         /* AS ROOT !!! */
2336
2337                         pdb_get_account_policy(AP_MIN_PASSWORD_LEN, &account_policy_temp);
2338                         min_pass_len = account_policy_temp;
2339
2340                         pdb_get_account_policy(AP_PASSWORD_HISTORY, &account_policy_temp);
2341                         pass_hist = account_policy_temp;
2342
2343                         pdb_get_account_policy(AP_USER_MUST_LOGON_TO_CHG_PASS, &account_policy_temp);
2344                         password_properties = account_policy_temp;
2345
2346                         pdb_get_account_policy(AP_MAX_PASSWORD_AGE, &account_policy_temp);
2347                         u_expire = account_policy_temp;
2348
2349                         pdb_get_account_policy(AP_MIN_PASSWORD_AGE, &account_policy_temp);
2350                         u_min_age = account_policy_temp;
2351
2352                         /* !AS ROOT */
2353                         
2354                         unbecome_root();
2355
2356                         unix_to_nt_time_abs(&nt_expire, u_expire);
2357                         unix_to_nt_time_abs(&nt_min_age, u_min_age);
2358
2359                         init_unk_info1(&ctr->info.inf1, (uint16)min_pass_len, (uint16)pass_hist, 
2360                                        password_properties, nt_expire, nt_min_age);
2361                         break;
2362                 case 0x02:
2363
2364                         become_root();
2365
2366                         /* AS ROOT !!! */
2367
2368                         num_users = count_sam_users(info->disp_info, ACB_NORMAL);
2369                         num_groups = count_sam_groups(info->disp_info);
2370                         num_aliases = count_sam_aliases(info->disp_info);
2371
2372                         pdb_get_account_policy(AP_TIME_TO_LOGOUT, &account_policy_temp);
2373                         u_logout = account_policy_temp;
2374
2375                         unix_to_nt_time_abs(&nt_logout, u_logout);
2376
2377                         if (!pdb_get_seq_num(&seq_num))
2378                                 seq_num = time(NULL);
2379
2380                         /* !AS ROOT */
2381                         
2382                         unbecome_root();
2383
2384                         server_role = ROLE_DOMAIN_PDC;
2385                         if (lp_server_role() == ROLE_DOMAIN_BDC)
2386                                 server_role = ROLE_DOMAIN_BDC;
2387
2388                         init_unk_info2(&ctr->info.inf2, lp_serverstring(), lp_workgroup(), global_myname(), seq_num, 
2389                                        num_users, num_groups, num_aliases, nt_logout, server_role);
2390                         break;
2391                 case 0x03:
2392
2393                         become_root();
2394
2395                         /* AS ROOT !!! */
2396
2397                         {
2398                                 uint32 ul;
2399                                 pdb_get_account_policy(AP_TIME_TO_LOGOUT, &ul);
2400                                 u_logout = (time_t)ul;
2401                         }
2402
2403                         /* !AS ROOT */
2404                         
2405                         unbecome_root();
2406
2407                         unix_to_nt_time_abs(&nt_logout, u_logout);
2408                         
2409                         init_unk_info3(&ctr->info.inf3, nt_logout);
2410                         break;
2411                 case 0x04:
2412                         init_unk_info4(&ctr->info.inf4, lp_serverstring());
2413                         break;
2414                 case 0x05:
2415                         init_unk_info5(&ctr->info.inf5, get_global_sam_name());
2416                         break;
2417                 case 0x06:
2418                         /* NT returns its own name when a PDC. win2k and later
2419                          * only the name of the PDC if itself is a BDC (samba4
2420                          * idl) */
2421                         init_unk_info6(&ctr->info.inf6, global_myname());
2422                         break;
2423                 case 0x07:
2424                         server_role = ROLE_DOMAIN_PDC;
2425                         if (lp_server_role() == ROLE_DOMAIN_BDC)
2426                                 server_role = ROLE_DOMAIN_BDC;
2427
2428                         init_unk_info7(&ctr->info.inf7, server_role);
2429                         break;
2430                 case 0x08:
2431
2432                         become_root();
2433
2434                         /* AS ROOT !!! */
2435
2436                         if (!pdb_get_seq_num(&seq_num)) {
2437                                 seq_num = time(NULL);
2438                         }
2439
2440                         /* !AS ROOT */
2441                         
2442                         unbecome_root();
2443
2444                         init_unk_info8(&ctr->info.inf8, (uint32) seq_num);
2445                         break;
2446                 case 0x0c:
2447
2448                         become_root();
2449
2450                         /* AS ROOT !!! */
2451
2452                         pdb_get_account_policy(AP_LOCK_ACCOUNT_DURATION, &account_policy_temp);
2453                         u_lock_duration = account_policy_temp;
2454                         if (u_lock_duration != -1) {
2455                                 u_lock_duration *= 60;
2456                         }
2457
2458                         pdb_get_account_policy(AP_RESET_COUNT_TIME, &account_policy_temp);
2459                         u_reset_time = account_policy_temp * 60;
2460
2461                         pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &account_policy_temp);
2462                         lockout = account_policy_temp;
2463
2464                         /* !AS ROOT */
2465                         
2466                         unbecome_root();
2467
2468                         unix_to_nt_time_abs(&nt_lock_duration, u_lock_duration);
2469                         unix_to_nt_time_abs(&nt_reset_time, u_reset_time);
2470         
2471                         init_unk_info12(&ctr->info.inf12, nt_lock_duration, nt_reset_time, (uint16)lockout);
2472                         break;
2473                 default:
2474                         return NT_STATUS_INVALID_INFO_CLASS;
2475                 }
2476         
2477
2478         init_samr_r_query_domain_info(r_u, q_u->switch_value, ctr, NT_STATUS_OK);
2479         
2480         DEBUG(5,("_samr_query_domain_info: %d\n", __LINE__));
2481         
2482         return r_u->status;
2483 }
2484
2485 /* W2k3 seems to use the same check for all 3 objects that can be created via
2486  * SAMR, if you try to create for example "Dialup" as an alias it says
2487  * "NT_STATUS_USER_EXISTS". This is racy, but we can't really lock the user
2488  * database. */
2489
2490 static NTSTATUS can_create(TALLOC_CTX *mem_ctx, const char *new_name)
2491 {
2492         enum lsa_SidType type;
2493         BOOL result;
2494
2495         DEBUG(10, ("Checking whether [%s] can be created\n", new_name));
2496
2497         become_root();
2498         /* Lookup in our local databases (only LOOKUP_NAME_ISOLATED set)
2499          * whether the name already exists */
2500         result = lookup_name(mem_ctx, new_name, LOOKUP_NAME_ISOLATED,
2501                              NULL, NULL, NULL, &type);
2502         unbecome_root();
2503
2504         if (!result) {
2505                 DEBUG(10, ("%s does not exist, can create it\n", new_name));
2506                 return NT_STATUS_OK;
2507         }
2508
2509         DEBUG(5, ("trying to create %s, exists as %s\n",
2510                   new_name, sid_type_lookup(type)));
2511
2512         if (type == SID_NAME_DOM_GRP) {
2513                 return NT_STATUS_GROUP_EXISTS;
2514         }
2515         if (type == SID_NAME_ALIAS) {
2516                 return NT_STATUS_ALIAS_EXISTS;
2517         }
2518
2519         /* Yes, the default is NT_STATUS_USER_EXISTS */
2520         return NT_STATUS_USER_EXISTS;
2521 }
2522
2523 /*******************************************************************
2524  _samr_create_user
2525  Create an account, can be either a normal user or a machine.
2526  This funcion will need to be updated for bdc/domain trusts.
2527  ********************************************************************/
2528
2529 NTSTATUS _samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u,
2530                            SAMR_R_CREATE_USER *r_u)
2531 {
2532         char *account;
2533         DOM_SID sid;
2534         POLICY_HND dom_pol = q_u->domain_pol;
2535         uint16 acb_info = q_u->acb_info;
2536         POLICY_HND *user_pol = &r_u->user_pol;
2537         struct samr_info *info = NULL;
2538         NTSTATUS nt_status;
2539         uint32 acc_granted;
2540         SEC_DESC *psd;
2541         size_t    sd_size;
2542         /* check this, when giving away 'add computer to domain' privs */
2543         uint32    des_access = GENERIC_RIGHTS_USER_ALL_ACCESS;
2544         BOOL can_add_account = False;
2545         SE_PRIV se_rights;
2546         DISP_INFO *disp_info = NULL;
2547
2548         /* Get the domain SID stored in the domain policy */
2549         if (!get_lsa_policy_samr_sid(p, &dom_pol, &sid, &acc_granted,
2550                                      &disp_info))
2551                 return NT_STATUS_INVALID_HANDLE;
2552
2553         nt_status = access_check_samr_function(acc_granted,
2554                                                SA_RIGHT_DOMAIN_CREATE_USER,
2555                                                "_samr_create_user");
2556         if (!NT_STATUS_IS_OK(nt_status)) {
2557                 return nt_status;
2558         }
2559
2560         if (!(acb_info == ACB_NORMAL || acb_info == ACB_DOMTRUST ||
2561               acb_info == ACB_WSTRUST || acb_info == ACB_SVRTRUST)) { 
2562                 /* Match Win2k, and return NT_STATUS_INVALID_PARAMETER if 
2563                    this parameter is not an account type */
2564                 return NT_STATUS_INVALID_PARAMETER;
2565         }
2566
2567         account = rpcstr_pull_unistr2_talloc(p->mem_ctx, &q_u->uni_name);
2568         if (account == NULL) {
2569                 return NT_STATUS_NO_MEMORY;
2570         }
2571
2572         nt_status = can_create(p->mem_ctx, account);
2573         if (!NT_STATUS_IS_OK(nt_status)) {
2574                 return nt_status;
2575         }
2576
2577         /* determine which user right we need to check based on the acb_info */
2578         
2579         if ( acb_info & ACB_WSTRUST )
2580         {
2581                 se_priv_copy( &se_rights, &se_machine_account );
2582                 can_add_account = user_has_privileges(
2583                         p->pipe_user.nt_user_token, &se_rights );
2584         } 
2585         /* usrmgr.exe (and net rpc trustdom grant) creates a normal user 
2586            account for domain trusts and changes the ACB flags later */
2587         else if ( acb_info & ACB_NORMAL &&
2588                   (account[strlen(account)-1] != '$') )
2589         {
2590                 se_priv_copy( &se_rights, &se_add_users );
2591                 can_add_account = user_has_privileges(
2592                         p->pipe_user.nt_user_token, &se_rights );
2593         } 
2594         else    /* implicit assumption of a BDC or domain trust account here
2595                  * (we already check the flags earlier) */
2596         {
2597                 if ( lp_enable_privileges() ) {
2598                         /* only Domain Admins can add a BDC or domain trust */
2599                         se_priv_copy( &se_rights, &se_priv_none );
2600                         can_add_account = nt_token_check_domain_rid(
2601                                 p->pipe_user.nt_user_token,
2602                                 DOMAIN_GROUP_RID_ADMINS );
2603                 }
2604         }
2605                 
2606         DEBUG(5, ("_samr_create_user: %s can add this account : %s\n",
2607                   uidtoname(p->pipe_user.ut.uid),
2608                   can_add_account ? "True":"False" ));
2609                 
2610         /********** BEGIN Admin BLOCK **********/
2611
2612         if ( can_add_account )
2613                 become_root();
2614
2615         nt_status = pdb_create_user(p->mem_ctx, account, acb_info,
2616                                     &r_u->user_rid);
2617
2618         if ( can_add_account )
2619                 unbecome_root();
2620
2621         /********** END Admin BLOCK **********/
2622         
2623         /* now check for failure */
2624         
2625         if ( !NT_STATUS_IS_OK(nt_status) )
2626                 return nt_status;
2627                         
2628         /* Get the user's SID */
2629
2630         sid_compose(&sid, get_global_sam_sid(), r_u->user_rid);
2631         
2632         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &usr_generic_mapping,
2633                             &sid, SAMR_USR_RIGHTS_WRITE_PW);
2634         se_map_generic(&des_access, &usr_generic_mapping);
2635         
2636         nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
2637                 &se_rights, GENERIC_RIGHTS_USER_WRITE, des_access, 
2638                 &acc_granted, "_samr_create_user");
2639                 
2640         if ( !NT_STATUS_IS_OK(nt_status) ) {
2641                 return nt_status;
2642         }
2643
2644         /* associate the user's SID with the new handle. */
2645         if ((info = get_samr_info_by_sid(&sid)) == NULL) {
2646                 return NT_STATUS_NO_MEMORY;
2647         }
2648
2649         ZERO_STRUCTP(info);
2650         info->sid = sid;
2651         info->acc_granted = acc_granted;
2652
2653         /* get a (unique) handle.  open a policy on it. */
2654         if (!create_policy_hnd(p, user_pol, free_samr_info, (void *)info)) {
2655                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2656         }
2657
2658         /* After a "set" ensure we have no cached display info. */
2659         force_flush_samr_cache(info->disp_info);
2660
2661         r_u->access_granted = acc_granted;
2662
2663         return NT_STATUS_OK;
2664 }
2665
2666 /*******************************************************************
2667  samr_reply_connect_anon
2668  ********************************************************************/
2669
2670 NTSTATUS _samr_connect_anon(pipes_struct *p, SAMR_Q_CONNECT_ANON *q_u, SAMR_R_CONNECT_ANON *r_u)
2671 {
2672         struct samr_info *info = NULL;
2673         uint32    des_access = q_u->access_mask;
2674
2675         /* Access check */
2676
2677         if (!pipe_access_check(p)) {
2678                 DEBUG(3, ("access denied to samr_connect_anon\n"));
2679                 r_u->status = NT_STATUS_ACCESS_DENIED;
2680                 return r_u->status;
2681         }
2682
2683         /* set up the SAMR connect_anon response */
2684
2685         r_u->status = NT_STATUS_OK;
2686
2687         /* associate the user's SID with the new handle. */
2688         if ((info = get_samr_info_by_sid(NULL)) == NULL)
2689                 return NT_STATUS_NO_MEMORY;
2690
2691         /* don't give away the farm but this is probably ok.  The SA_RIGHT_SAM_ENUM_DOMAINS
2692            was observed from a win98 client trying to enumerate users (when configured  
2693            user level access control on shares)   --jerry */
2694            
2695         if (des_access == MAXIMUM_ALLOWED_ACCESS) {
2696                 /* Map to max possible knowing we're filtered below. */
2697                 des_access = GENERIC_ALL_ACCESS;
2698         }
2699
2700         se_map_generic( &des_access, &sam_generic_mapping );
2701         info->acc_granted = des_access & (SA_RIGHT_SAM_ENUM_DOMAINS|SA_RIGHT_SAM_OPEN_DOMAIN);
2702         
2703         info->status = q_u->unknown_0;
2704
2705         /* get a (unique) handle.  open a policy on it. */
2706         if (!create_policy_hnd(p, &r_u->connect_pol, free_samr_info, (void *)info))
2707                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2708
2709         return r_u->status;
2710 }
2711
2712 /*******************************************************************
2713  samr_reply_connect
2714  ********************************************************************/
2715
2716 NTSTATUS _samr_connect(pipes_struct *p, SAMR_Q_CONNECT *q_u, SAMR_R_CONNECT *r_u)
2717 {
2718         struct samr_info *info = NULL;
2719         SEC_DESC *psd = NULL;
2720         uint32    acc_granted;
2721         uint32    des_access = q_u->access_mask;
2722         NTSTATUS  nt_status;
2723         size_t    sd_size;
2724
2725
2726         DEBUG(5,("_samr_connect: %d\n", __LINE__));
2727
2728         /* Access check */
2729
2730         if (!pipe_access_check(p)) {
2731                 DEBUG(3, ("access denied to samr_connect\n"));
2732                 r_u->status = NT_STATUS_ACCESS_DENIED;
2733                 return r_u->status;
2734         }
2735
2736         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &sam_generic_mapping, NULL, 0);
2737         se_map_generic(&des_access, &sam_generic_mapping);
2738         
2739         nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
2740                 NULL, 0, des_access, &acc_granted, "_samr_connect");
2741         
2742         if ( !NT_STATUS_IS_OK(nt_status) ) 
2743                 return nt_status;
2744
2745         r_u->status = NT_STATUS_OK;
2746
2747         /* associate the user's SID and access granted with the new handle. */
2748         if ((info = get_samr_info_by_sid(NULL)) == NULL)
2749                 return NT_STATUS_NO_MEMORY;
2750
2751         info->acc_granted = acc_granted;
2752         info->status = q_u->access_mask;
2753
2754         /* get a (unique) handle.  open a policy on it. */
2755         if (!create_policy_hnd(p, &r_u->connect_pol, free_samr_info, (void *)info))
2756                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2757
2758         DEBUG(5,("_samr_connect: %d\n", __LINE__));
2759
2760         return r_u->status;
2761 }
2762
2763 /*******************************************************************
2764  samr_connect4
2765  ********************************************************************/
2766
2767 NTSTATUS _samr_connect4(pipes_struct *p, SAMR_Q_CONNECT4 *q_u, SAMR_R_CONNECT4 *r_u)
2768 {
2769         struct samr_info *info = NULL;
2770         SEC_DESC *psd = NULL;
2771         uint32    acc_granted;
2772         uint32    des_access = q_u->access_mask;
2773         NTSTATUS  nt_status;
2774         size_t    sd_size;
2775
2776
2777         DEBUG(5,("_samr_connect4: %d\n", __LINE__));
2778
2779         /* Access check */
2780
2781         if (!pipe_access_check(p)) {
2782                 DEBUG(3, ("access denied to samr_connect4\n"));
2783                 r_u->status = NT_STATUS_ACCESS_DENIED;
2784                 return r_u->status;
2785         }
2786
2787         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &sam_generic_mapping, NULL, 0);
2788         se_map_generic(&des_access, &sam_generic_mapping);
2789         
2790         nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
2791                 NULL, 0, des_access, &acc_granted, "_samr_connect4");
2792         
2793         if ( !NT_STATUS_IS_OK(nt_status) ) 
2794                 return nt_status;
2795
2796         r_u->status = NT_STATUS_OK;
2797
2798         /* associate the user's SID and access granted with the new handle. */
2799         if ((info = get_samr_info_by_sid(NULL)) == NULL)
2800                 return NT_STATUS_NO_MEMORY;
2801
2802         info->acc_granted = acc_granted;
2803         info->status = q_u->access_mask;
2804
2805         /* get a (unique) handle.  open a policy on it. */
2806         if (!create_policy_hnd(p, &r_u->connect_pol, free_samr_info, (void *)info))
2807                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2808
2809         DEBUG(5,("_samr_connect: %d\n", __LINE__));
2810
2811         return r_u->status;
2812 }
2813
2814 /*******************************************************************
2815  samr_connect5
2816  ********************************************************************/
2817
2818 NTSTATUS _samr_connect5(pipes_struct *p, SAMR_Q_CONNECT5 *q_u, SAMR_R_CONNECT5 *r_u)
2819 {
2820         struct samr_info *info = NULL;
2821         SEC_DESC *psd = NULL;
2822         uint32    acc_granted;
2823         uint32    des_access = q_u->access_mask;
2824         NTSTATUS  nt_status;
2825         POLICY_HND pol;
2826         size_t    sd_size;
2827
2828
2829         DEBUG(5,("_samr_connect5: %d\n", __LINE__));
2830
2831         ZERO_STRUCTP(r_u);
2832
2833         /* Access check */
2834
2835         if (!pipe_access_check(p)) {
2836                 DEBUG(3, ("access denied to samr_connect5\n"));
2837                 r_u->status = NT_STATUS_ACCESS_DENIED;
2838                 return r_u->status;
2839         }
2840
2841         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &sam_generic_mapping, NULL, 0);
2842         se_map_generic(&des_access, &sam_generic_mapping);
2843         
2844         nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
2845                 NULL, 0, des_access, &acc_granted, "_samr_connect5");
2846         
2847         if ( !NT_STATUS_IS_OK(nt_status) ) 
2848                 return nt_status;
2849
2850         /* associate the user's SID and access granted with the new handle. */
2851         if ((info = get_samr_info_by_sid(NULL)) == NULL)
2852                 return NT_STATUS_NO_MEMORY;
2853
2854         info->acc_granted = acc_granted;
2855         info->status = q_u->access_mask;
2856
2857         /* get a (unique) handle.  open a policy on it. */
2858         if (!create_policy_hnd(p, &pol, free_samr_info, (void *)info))
2859                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2860
2861         DEBUG(5,("_samr_connect: %d\n", __LINE__));
2862
2863         init_samr_r_connect5(r_u, &pol, NT_STATUS_OK);
2864
2865         return r_u->status;
2866 }
2867
2868 /**********************************************************************
2869  api_samr_lookup_domain
2870  **********************************************************************/
2871
2872 NTSTATUS _samr_lookup_domain(pipes_struct *p, SAMR_Q_LOOKUP_DOMAIN *q_u, SAMR_R_LOOKUP_DOMAIN *r_u)
2873 {
2874         struct samr_info *info;
2875         fstring domain_name;
2876         DOM_SID sid;
2877
2878         r_u->status = NT_STATUS_OK;
2879
2880         if (!find_policy_by_hnd(p, &q_u->connect_pol, (void**)(void *)&info))
2881                 return NT_STATUS_INVALID_HANDLE;
2882
2883         /* win9x user manager likes to use SA_RIGHT_SAM_ENUM_DOMAINS here.  
2884            Reverted that change so we will work with RAS servers again */
2885
2886         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(info->acc_granted, 
2887                 SA_RIGHT_SAM_OPEN_DOMAIN, "_samr_lookup_domain"))) 
2888         {
2889                 return r_u->status;
2890         }
2891
2892         rpcstr_pull(domain_name, q_u->uni_domain.buffer, sizeof(domain_name), q_u->uni_domain.uni_str_len*2, 0);
2893
2894         ZERO_STRUCT(sid);
2895
2896         if (strequal(domain_name, builtin_domain_name())) {
2897                 sid_copy(&sid, &global_sid_Builtin);
2898         } else {
2899                 if (!secrets_fetch_domain_sid(domain_name, &sid)) {
2900                         r_u->status = NT_STATUS_NO_SUCH_DOMAIN;
2901                 }
2902         }
2903
2904         DEBUG(2,("Returning domain sid for domain %s -> %s\n", domain_name, sid_string_static(&sid)));
2905
2906         init_samr_r_lookup_domain(r_u, &sid, r_u->status);
2907
2908         return r_u->status;
2909 }
2910
2911 /******************************************************************
2912 makes a SAMR_R_ENUM_DOMAINS structure.
2913 ********************************************************************/
2914
2915 static BOOL make_enum_domains(TALLOC_CTX *ctx, SAM_ENTRY **pp_sam,
2916                         UNISTR2 **pp_uni_name, uint32 num_sam_entries, fstring doms[])
2917 {
2918         uint32 i;
2919         SAM_ENTRY *sam;
2920         UNISTR2 *uni_name;
2921
2922         DEBUG(5, ("make_enum_domains\n"));
2923
2924         *pp_sam = NULL;
2925         *pp_uni_name = NULL;
2926
2927         if (num_sam_entries == 0)
2928                 return True;
2929
2930         sam = TALLOC_ZERO_ARRAY(ctx, SAM_ENTRY, num_sam_entries);
2931         uni_name = TALLOC_ZERO_ARRAY(ctx, UNISTR2, num_sam_entries);
2932
2933         if (sam == NULL || uni_name == NULL)
2934                 return False;
2935
2936         for (i = 0; i < num_sam_entries; i++) {
2937                 init_unistr2(&uni_name[i], doms[i], UNI_FLAGS_NONE);
2938                 init_sam_entry(&sam[i], &uni_name[i], 0);
2939         }
2940
2941         *pp_sam = sam;
2942         *pp_uni_name = uni_name;
2943
2944         return True;
2945 }
2946
2947 /**********************************************************************
2948  api_samr_enum_domains
2949  **********************************************************************/
2950
2951 NTSTATUS _samr_enum_domains(pipes_struct *p, SAMR_Q_ENUM_DOMAINS *q_u, SAMR_R_ENUM_DOMAINS *r_u)
2952 {
2953         struct samr_info *info;
2954         uint32 num_entries = 2;
2955         fstring dom[2];
2956         const char *name;
2957
2958         r_u->status = NT_STATUS_OK;
2959         
2960         if (!find_policy_by_hnd(p, &q_u->pol, (void**)(void *)&info))
2961                 return NT_STATUS_INVALID_HANDLE;
2962         
2963         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(info->acc_granted, SA_RIGHT_SAM_ENUM_DOMAINS, "_samr_enum_domains"))) {
2964                 return r_u->status;
2965         }
2966
2967         name = get_global_sam_name();
2968
2969         fstrcpy(dom[0],name);
2970         strupper_m(dom[0]);
2971         fstrcpy(dom[1],"Builtin");
2972
2973         if (!make_enum_domains(p->mem_ctx, &r_u->sam, &r_u->uni_dom_name, num_entries, dom))
2974                 return NT_STATUS_NO_MEMORY;
2975
2976         init_samr_r_enum_domains(r_u, q_u->start_idx + num_entries, num_entries);
2977
2978         return r_u->status;
2979 }
2980
2981 /*******************************************************************
2982  api_samr_open_alias
2983  ********************************************************************/
2984
2985 NTSTATUS _samr_open_alias(pipes_struct *p, SAMR_Q_OPEN_ALIAS *q_u, SAMR_R_OPEN_ALIAS *r_u)
2986 {
2987         DOM_SID sid;
2988         POLICY_HND domain_pol = q_u->dom_pol;
2989         uint32 alias_rid = q_u->rid_alias;
2990         POLICY_HND *alias_pol = &r_u->pol;
2991         struct    samr_info *info = NULL;
2992         SEC_DESC *psd = NULL;
2993         uint32    acc_granted;
2994         uint32    des_access = q_u->access_mask;
2995         size_t    sd_size;
2996         NTSTATUS  status;
2997         SE_PRIV se_rights;
2998
2999         r_u->status = NT_STATUS_OK;
3000
3001         /* find the domain policy and get the SID / access bits stored in the domain policy */
3002         
3003         if ( !get_lsa_policy_samr_sid(p, &domain_pol, &sid, &acc_granted, NULL) )
3004                 return NT_STATUS_INVALID_HANDLE;
3005         
3006         status = access_check_samr_function(acc_granted, 
3007                 SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_open_alias");
3008                 
3009         if ( !NT_STATUS_IS_OK(status) ) 
3010                 return status;
3011
3012         /* append the alias' RID to it */
3013         
3014         if (!sid_append_rid(&sid, alias_rid))
3015                 return NT_STATUS_NO_SUCH_ALIAS;
3016                 
3017         /*check if access can be granted as requested by client. */
3018         
3019         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &ali_generic_mapping, NULL, 0);
3020         se_map_generic(&des_access,&ali_generic_mapping);
3021         
3022         se_priv_copy( &se_rights, &se_add_users );
3023         
3024         
3025         status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
3026                 &se_rights, GENERIC_RIGHTS_ALIAS_WRITE, des_access, 
3027                 &acc_granted, "_samr_open_alias");
3028                 
3029         if ( !NT_STATUS_IS_OK(status) )
3030                 return status;
3031
3032         {
3033                 /* Check we actually have the requested alias */
3034                 enum lsa_SidType type;
3035                 BOOL result;
3036                 gid_t gid;
3037
3038                 become_root();
3039                 result = lookup_sid(NULL, &sid, NULL, NULL, &type);
3040                 unbecome_root();
3041
3042                 if (!result || (type != SID_NAME_ALIAS)) {
3043                         return NT_STATUS_NO_SUCH_ALIAS;
3044                 }
3045
3046                 /* make sure there is a mapping */
3047                 
3048                 if ( !sid_to_gid( &sid, &gid ) ) {
3049                         return NT_STATUS_NO_SUCH_ALIAS;
3050                 }
3051
3052         }
3053
3054         /* associate the alias SID with the new handle. */
3055         if ((info = get_samr_info_by_sid(&sid)) == NULL)
3056                 return NT_STATUS_NO_MEMORY;
3057                 
3058         info->acc_granted = acc_granted;
3059
3060         /* get a (unique) handle.  open a policy on it. */
3061         if (!create_policy_hnd(p, alias_pol, free_samr_info, (void *)info))
3062                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3063
3064         return r_u->status;
3065 }
3066
3067 /*******************************************************************
3068  set_user_info_7
3069  ********************************************************************/
3070 static NTSTATUS set_user_info_7(TALLOC_CTX *mem_ctx,
3071                                 const SAM_USER_INFO_7 *id7, struct samu *pwd)
3072 {
3073         fstring new_name;
3074         NTSTATUS rc;
3075
3076         if (id7 == NULL) {
3077                 DEBUG(5, ("set_user_info_7: NULL id7\n"));
3078                 TALLOC_FREE(pwd);
3079                 return NT_STATUS_ACCESS_DENIED;
3080         }
3081
3082         if(!rpcstr_pull(new_name, id7->uni_name.buffer, sizeof(new_name), id7->uni_name.uni_str_len*2, 0)) {
3083                 DEBUG(5, ("set_user_info_7: failed to get new username\n"));
3084                 TALLOC_FREE(pwd);
3085                 return NT_STATUS_ACCESS_DENIED;
3086         }
3087
3088         /* check to see if the new username already exists.  Note: we can't
3089            reliably lock all backends, so there is potentially the 
3090            possibility that a user can be created in between this check and
3091            the rename.  The rename should fail, but may not get the
3092            exact same failure status code.  I think this is small enough
3093            of a window for this type of operation and the results are
3094            simply that the rename fails with a slightly different status
3095            code (like UNSUCCESSFUL instead of ALREADY_EXISTS). */
3096
3097         rc = can_create(mem_ctx, new_name);
3098         if (!NT_STATUS_IS_OK(rc)) {
3099                 return rc;
3100         }
3101
3102         rc = pdb_rename_sam_account(pwd, new_name);
3103
3104         TALLOC_FREE(pwd);
3105         return rc;
3106 }
3107
3108 /*******************************************************************
3109  set_user_info_16
3110  ********************************************************************/
3111
3112 static BOOL set_user_info_16(const SAM_USER_INFO_16 *id16, struct samu *pwd)
3113 {
3114         if (id16 == NULL) {
3115                 DEBUG(5, ("set_user_info_16: NULL id16\n"));
3116                 TALLOC_FREE(pwd);
3117                 return False;
3118         }
3119         
3120         /* FIX ME: check if the value is really changed --metze */
3121         if (!pdb_set_acct_ctrl(pwd, id16->acb_info, PDB_CHANGED)) {
3122                 TALLOC_FREE(pwd);
3123                 return False;
3124         }
3125
3126         if(!NT_STATUS_IS_OK(pdb_update_sam_account(pwd))) {
3127                 TALLOC_FREE(pwd);
3128                 return False;
3129         }
3130
3131         TALLOC_FREE(pwd);
3132
3133         return True;
3134 }
3135
3136 /*******************************************************************
3137  set_user_info_18
3138  ********************************************************************/
3139
3140 static BOOL set_user_info_18(SAM_USER_INFO_18 *id18, struct samu *pwd)
3141 {
3142
3143         if (id18 == NULL) {
3144                 DEBUG(2, ("set_user_info_18: id18 is NULL\n"));
3145                 TALLOC_FREE(pwd);
3146                 return False;
3147         }
3148  
3149         if (!pdb_set_lanman_passwd (pwd, id18->lm_pwd, PDB_CHANGED)) {
3150                 TALLOC_FREE(pwd);
3151                 return False;
3152         }
3153         if (!pdb_set_nt_passwd     (pwd, id18->nt_pwd, PDB_CHANGED)) {
3154                 TALLOC_FREE(pwd);
3155                 return False;
3156         }
3157         if (!pdb_set_pass_last_set_time (pwd, time(NULL), PDB_CHANGED)) {
3158                 TALLOC_FREE(pwd);
3159                 return False; 
3160         }
3161  
3162         if(!NT_STATUS_IS_OK(pdb_update_sam_account(pwd))) {
3163                 TALLOC_FREE(pwd);
3164                 return False;
3165         }
3166
3167         TALLOC_FREE(pwd);
3168         return True;
3169 }
3170
3171 /*******************************************************************
3172  set_user_info_20
3173  ********************************************************************/
3174
3175 static BOOL set_user_info_20(SAM_USER_INFO_20 *id20, struct samu *pwd)
3176 {
3177         if (id20 == NULL) {
3178                 DEBUG(5, ("set_user_info_20: NULL id20\n"));
3179                 return False;
3180         }
3181  
3182         copy_id20_to_sam_passwd(pwd, id20);
3183
3184         /* write the change out */
3185         if(!NT_STATUS_IS_OK(pdb_update_sam_account(pwd))) {
3186                 TALLOC_FREE(pwd);
3187                 return False;
3188         }
3189
3190         TALLOC_FREE(pwd);
3191
3192         return True;
3193 }
3194 /*******************************************************************
3195  set_user_info_21
3196  ********************************************************************/
3197
3198 static NTSTATUS set_user_info_21(TALLOC_CTX *mem_ctx, SAM_USER_INFO_21 *id21,
3199                                  struct samu *pwd)
3200 {
3201         fstring new_name;
3202         NTSTATUS status;
3203         
3204         if (id21 == NULL) {
3205                 DEBUG(5, ("set_user_info_21: NULL id21\n"));
3206                 return NT_STATUS_INVALID_PARAMETER;
3207         }
3208
3209         /* we need to separately check for an account rename first */
3210         
3211         if (rpcstr_pull(new_name, id21->uni_user_name.buffer, 
3212                 sizeof(new_name), id21->uni_user_name.uni_str_len*2, 0) 
3213                 && (!strequal(new_name, pdb_get_username(pwd)))) 
3214         {
3215
3216                 /* check to see if the new username already exists.  Note: we can't
3217                    reliably lock all backends, so there is potentially the 
3218                    possibility that a user can be created in between this check and
3219                    the rename.  The rename should fail, but may not get the
3220                    exact same failure status code.  I think this is small enough
3221                    of a window for this type of operation and the results are
3222                    simply that the rename fails with a slightly different status
3223                    code (like UNSUCCESSFUL instead of ALREADY_EXISTS). */
3224
3225                 status = can_create(mem_ctx, new_name);
3226                 if (!NT_STATUS_IS_OK(status)) {
3227                         return status;
3228                 }
3229
3230                 status = pdb_rename_sam_account(pwd, new_name);
3231
3232                 if (!NT_STATUS_IS_OK(status)) {
3233                         DEBUG(0,("set_user_info_21: failed to rename account: %s\n", 
3234                                 nt_errstr(status)));
3235                         TALLOC_FREE(pwd);
3236                         return status;
3237                 }
3238
3239                 /* set the new username so that later 
3240                    functions can work on the new account */
3241                 pdb_set_username(pwd, new_name, PDB_SET);
3242         }
3243
3244         copy_id21_to_sam_passwd(pwd, id21);
3245  
3246         /*
3247          * The funny part about the previous two calls is
3248          * that pwd still has the password hashes from the
3249          * passdb entry.  These have not been updated from
3250          * id21.  I don't know if they need to be set.    --jerry
3251          */
3252  
3253         if ( IS_SAM_CHANGED(pwd, PDB_GROUPSID) ) {
3254                 status = pdb_set_unix_primary_group(mem_ctx, pwd);
3255                 if ( !NT_STATUS_IS_OK(status) ) {
3256                         return status;
3257                 }
3258         }
3259         
3260         /* Don't worry about writing out the user account since the
3261            primary group SID is generated solely from the user's Unix 
3262            primary group. */
3263
3264         /* write the change out */
3265         if(!NT_STATUS_IS_OK(status = pdb_update_sam_account(pwd))) {
3266                 TALLOC_FREE(pwd);
3267                 return status;
3268         }
3269
3270         TALLOC_FREE(pwd);
3271
3272         return NT_STATUS_OK;
3273 }
3274
3275 /*******************************************************************
3276  set_user_info_23
3277  ********************************************************************/
3278
3279 static NTSTATUS set_user_info_23(TALLOC_CTX *mem_ctx, SAM_USER_INFO_23 *id23,
3280                                  struct samu *pwd)
3281 {
3282         pstring plaintext_buf;
3283         uint32 len;
3284         uint16 acct_ctrl;
3285         NTSTATUS status;
3286  
3287         if (id23 == NULL) {
3288                 DEBUG(5, ("set_user_info_23: NULL id23\n"));
3289                 return NT_STATUS_INVALID_PARAMETER;
3290         }
3291  
3292         DEBUG(5, ("Attempting administrator password change (level 23) for user %s\n",
3293                   pdb_get_username(pwd)));
3294
3295         acct_ctrl = pdb_get_acct_ctrl(pwd);
3296
3297         if (!decode_pw_buffer(id23->pass, plaintext_buf, 256, &len, STR_UNICODE)) {
3298                 TALLOC_FREE(pwd);
3299                 return NT_STATUS_INVALID_PARAMETER;
3300         }
3301   
3302         if (!pdb_set_plaintext_passwd (pwd, plaintext_buf)) {
3303                 TALLOC_FREE(pwd);
3304                 return NT_STATUS_ACCESS_DENIED;
3305         }
3306  
3307         copy_id23_to_sam_passwd(pwd, id23);
3308  
3309         /* if it's a trust account, don't update /etc/passwd */
3310         if (    ( (acct_ctrl &  ACB_DOMTRUST) == ACB_DOMTRUST ) ||
3311                 ( (acct_ctrl &  ACB_WSTRUST) ==  ACB_WSTRUST) ||
3312                 ( (acct_ctrl &  ACB_SVRTRUST) ==  ACB_SVRTRUST) ) {
3313                 DEBUG(5, ("Changing trust account.  Not updating /etc/passwd\n"));
3314         } else  {
3315                 /* update the UNIX password */
3316                 if (lp_unix_password_sync() ) {
3317                         struct passwd *passwd;
3318                         if (pdb_get_username(pwd) == NULL) {
3319                                 DEBUG(1, ("chgpasswd: User without name???\n"));
3320                                 TALLOC_FREE(pwd);
3321                                 return NT_STATUS_ACCESS_DENIED;
3322                         }
3323
3324                         if ((passwd = Get_Pwnam(pdb_get_username(pwd))) == NULL) {
3325                                 DEBUG(1, ("chgpasswd: Username does not exist in system !?!\n"));
3326                         }
3327                         
3328                         if(!chgpasswd(pdb_get_username(pwd), passwd, "", plaintext_buf, True)) {
3329                                 TALLOC_FREE(pwd);
3330                                 return NT_STATUS_ACCESS_DENIED;
3331                         }
3332                 }
3333         }
3334  
3335         ZERO_STRUCT(plaintext_buf);
3336  
3337         if (IS_SAM_CHANGED(pwd, PDB_GROUPSID) &&
3338             (!NT_STATUS_IS_OK(status =  pdb_set_unix_primary_group(mem_ctx,
3339                                                                    pwd)))) {
3340                 TALLOC_FREE(pwd);
3341                 return status;
3342         }
3343
3344         if(!NT_STATUS_IS_OK(status = pdb_update_sam_account(pwd))) {
3345                 TALLOC_FREE(pwd);
3346                 return status;
3347         }
3348  
3349         TALLOC_FREE(pwd);
3350
3351         return NT_STATUS_OK;
3352 }
3353
3354 /*******************************************************************
3355  set_user_info_pw
3356  ********************************************************************/
3357
3358 static BOOL set_user_info_pw(uint8 *pass, struct samu *pwd)
3359 {
3360         uint32 len;
3361         pstring plaintext_buf;
3362         uint32 acct_ctrl;
3363  
3364         DEBUG(5, ("Attempting administrator password change for user %s\n",
3365                   pdb_get_username(pwd)));
3366
3367         acct_ctrl = pdb_get_acct_ctrl(pwd);
3368
3369         ZERO_STRUCT(plaintext_buf);
3370  
3371         if (!decode_pw_buffer(pass, plaintext_buf, 256, &len, STR_UNICODE)) {
3372                 TALLOC_FREE(pwd);
3373                 return False;
3374         }
3375
3376         if (!pdb_set_plaintext_passwd (pwd, plaintext_buf)) {
3377                 TALLOC_FREE(pwd);
3378                 return False;
3379         }
3380  
3381         /* if it's a trust account, don't update /etc/passwd */
3382         if ( ( (acct_ctrl &  ACB_DOMTRUST) == ACB_DOMTRUST ) ||
3383                 ( (acct_ctrl &  ACB_WSTRUST) ==  ACB_WSTRUST) ||
3384                 ( (acct_ctrl &  ACB_SVRTRUST) ==  ACB_SVRTRUST) ) {
3385                 DEBUG(5, ("Changing trust account or non-unix-user password, not updating /etc/passwd\n"));
3386         } else {
3387                 /* update the UNIX password */
3388                 if (lp_unix_password_sync()) {
3389                         struct passwd *passwd;
3390
3391                         if (pdb_get_username(pwd) == NULL) {
3392                                 DEBUG(1, ("chgpasswd: User without name???\n"));
3393                                 TALLOC_FREE(pwd);
3394                                 return False;
3395                         }
3396
3397                         if ((passwd = Get_Pwnam(pdb_get_username(pwd))) == NULL) {
3398                                 DEBUG(1, ("chgpasswd: Username does not exist in system !?!\n"));
3399                         }
3400                         
3401                         if(!chgpasswd(pdb_get_username(pwd), passwd, "", plaintext_buf, True)) {
3402                                 TALLOC_FREE(pwd);
3403                                 return False;
3404                         }
3405                 }
3406         }
3407  
3408         ZERO_STRUCT(plaintext_buf);
3409  
3410         DEBUG(5,("set_user_info_pw: pdb_update_pwd()\n"));
3411  
3412         /* update the SAMBA password */
3413         if(!NT_STATUS_IS_OK(pdb_update_sam_account(pwd))) {
3414                 TALLOC_FREE(pwd);
3415                 return False;
3416         }
3417
3418         TALLOC_FREE(pwd);
3419
3420         return True;
3421 }
3422
3423 /*******************************************************************
3424  set_user_info_25
3425  ********************************************************************/
3426
3427 static NTSTATUS set_user_info_25(TALLOC_CTX *mem_ctx, SAM_USER_INFO_25 *id25,
3428                                  struct samu *pwd)
3429 {
3430         NTSTATUS status;
3431         
3432         if (id25 == NULL) {
3433                 DEBUG(5, ("set_user_info_25: NULL id25\n"));
3434                 return NT_STATUS_INVALID_PARAMETER;
3435         }
3436
3437         copy_id25_to_sam_passwd(pwd, id25);
3438  
3439         /* write the change out */
3440         if(!NT_STATUS_IS_OK(status = pdb_update_sam_account(pwd))) {
3441                 TALLOC_FREE(pwd);
3442                 return status;
3443         }
3444
3445         /*
3446          * We need to "pdb_update_sam_account" before the unix primary group
3447          * is set, because the idealx scripts would also change the
3448          * sambaPrimaryGroupSid using the ldap replace method. pdb_ldap uses
3449          * the delete explicit / add explicit, which would then fail to find
3450          * the previous primaryGroupSid value.
3451          */
3452
3453         if ( IS_SAM_CHANGED(pwd, PDB_GROUPSID) ) {
3454                 status = pdb_set_unix_primary_group(mem_ctx, pwd);
3455                 if ( !NT_STATUS_IS_OK(status) ) {
3456                         return status;
3457                 }
3458         }
3459         
3460         /* WARNING: No TALLOC_FREE(pwd), we are about to set the password
3461          * hereafter! */
3462
3463         return NT_STATUS_OK;
3464 }
3465
3466 /*******************************************************************
3467  samr_reply_set_userinfo
3468  ********************************************************************/
3469
3470 NTSTATUS _samr_set_userinfo(pipes_struct *p, SAMR_Q_SET_USERINFO *q_u, SAMR_R_SET_USERINFO *r_u)
3471 {
3472         struct samu *pwd = NULL;
3473         DOM_SID sid;
3474         POLICY_HND *pol = &q_u->pol;
3475         uint16 switch_value = q_u->switch_value;
3476         SAM_USERINFO_CTR *ctr = q_u->ctr;
3477         uint32 acc_granted;
3478         uint32 acc_required;
3479         BOOL ret;
3480         BOOL has_enough_rights = False;
3481         uint32 acb_info;
3482         DISP_INFO *disp_info = NULL;
3483
3484         DEBUG(5, ("_samr_set_userinfo: %d\n", __LINE__));
3485
3486         r_u->status = NT_STATUS_OK;
3487
3488         /* find the policy handle.  open a policy on it. */
3489         if (!get_lsa_policy_samr_sid(p, pol, &sid, &acc_granted, &disp_info))
3490                 return NT_STATUS_INVALID_HANDLE;
3491
3492         /* This is tricky.  A WinXP domain join sets 
3493           (SA_RIGHT_USER_SET_PASSWORD|SA_RIGHT_USER_SET_ATTRIBUTES|SA_RIGHT_USER_ACCT_FLAGS_EXPIRY)
3494           The MMC lusrmgr plugin includes these perms and more in the SamrOpenUser().  But the 
3495           standard Win32 API calls just ask for SA_RIGHT_USER_SET_PASSWORD in the SamrOpenUser().  
3496           This should be enough for levels 18, 24, 25,& 26.  Info level 23 can set more so 
3497           we'll use the set from the WinXP join as the basis. */
3498         
3499         switch (switch_value) {
3500         case 18:
3501         case 24:
3502         case 25:
3503         case 26:
3504                 acc_required = SA_RIGHT_USER_SET_PASSWORD;
3505                 break;
3506         default:
3507                 acc_required = SA_RIGHT_USER_SET_PASSWORD | SA_RIGHT_USER_SET_ATTRIBUTES | SA_RIGHT_USER_ACCT_FLAGS_EXPIRY;
3508                 break;
3509         }
3510         
3511         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, acc_required, "_samr_set_userinfo"))) {
3512                 return r_u->status;
3513         }
3514
3515         DEBUG(5, ("_samr_set_userinfo: sid:%s, level:%d\n", sid_string_static(&sid), switch_value));
3516
3517         if (ctr == NULL) {
3518                 DEBUG(5, ("_samr_set_userinfo: NULL info level\n"));
3519                 return NT_STATUS_INVALID_INFO_CLASS;
3520         }
3521         
3522         if ( !(pwd = samu_new( NULL )) ) {
3523                 return NT_STATUS_NO_MEMORY;
3524         }
3525         
3526         become_root();
3527         ret = pdb_getsampwsid(pwd, &sid);
3528         unbecome_root();
3529         
3530         if ( !ret ) {
3531                 TALLOC_FREE(pwd);
3532                 return NT_STATUS_NO_SUCH_USER;
3533         }
3534         
3535         /* deal with machine password changes differently from userinfo changes */
3536         /* check to see if we have the sufficient rights */
3537         
3538         acb_info = pdb_get_acct_ctrl(pwd);
3539         if ( acb_info & ACB_WSTRUST ) 
3540                 has_enough_rights = user_has_privileges( p->pipe_user.nt_user_token, &se_machine_account);
3541         else if ( acb_info & ACB_NORMAL )
3542                 has_enough_rights = user_has_privileges( p->pipe_user.nt_user_token, &se_add_users );
3543         else if ( acb_info & (ACB_SVRTRUST|ACB_DOMTRUST) ) {
3544                 if ( lp_enable_privileges() )
3545                         has_enough_rights = nt_token_check_domain_rid( p->pipe_user.nt_user_token, DOMAIN_GROUP_RID_ADMINS );
3546         }
3547         
3548         DEBUG(5, ("_samr_set_userinfo: %s does%s possess sufficient rights\n",
3549                   uidtoname(p->pipe_user.ut.uid),
3550                   has_enough_rights ? "" : " not"));
3551
3552         /* ================ BEGIN SeMachineAccountPrivilege BLOCK ================ */
3553         
3554         if ( has_enough_rights )                                
3555                 become_root(); 
3556         
3557         /* ok!  user info levels (lots: see MSDEV help), off we go... */
3558
3559         switch (switch_value) {
3560                 case 18:
3561                         if (!set_user_info_18(ctr->info.id18, pwd))
3562                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3563                         break;
3564
3565                 case 24:
3566                         if (!p->session_key.length) {
3567                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3568                         }
3569                         SamOEMhashBlob(ctr->info.id24->pass, 516, &p->session_key);
3570
3571                         dump_data(100, (char *)ctr->info.id24->pass, 516);
3572
3573                         if (!set_user_info_pw(ctr->info.id24->pass, pwd))
3574                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3575                         break;
3576
3577                 case 25:
3578                         if (!p->session_key.length) {
3579                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3580                         }
3581                         encode_or_decode_arc4_passwd_buffer(ctr->info.id25->pass, &p->session_key);
3582
3583                         dump_data(100, (char *)ctr->info.id25->pass, 532);
3584
3585                         r_u->status = set_user_info_25(p->mem_ctx,
3586                                                        ctr->info.id25, pwd);
3587                         if (!NT_STATUS_IS_OK(r_u->status)) {
3588                                 goto done;
3589                         }
3590                         if (!set_user_info_pw(ctr->info.id25->pass, pwd))
3591                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3592                         break;
3593
3594                 case 26:
3595                         if (!p->session_key.length) {
3596                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3597                         }
3598                         encode_or_decode_arc4_passwd_buffer(ctr->info.id26->pass, &p->session_key);
3599
3600                         dump_data(100, (char *)ctr->info.id26->pass, 516);
3601
3602                         if (!set_user_info_pw(ctr->info.id26->pass, pwd))
3603                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3604                         break;
3605
3606                 case 23:
3607                         if (!p->session_key.length) {
3608                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3609                         }
3610                         SamOEMhashBlob(ctr->info.id23->pass, 516, &p->session_key);
3611
3612                         dump_data(100, (char *)ctr->info.id23->pass, 516);
3613
3614                         r_u->status = set_user_info_23(p->mem_ctx,
3615                                                        ctr->info.id23, pwd);
3616                         break;
3617
3618                 default:
3619                         r_u->status = NT_STATUS_INVALID_INFO_CLASS;
3620         }
3621
3622  done:
3623         
3624         if ( has_enough_rights )                                
3625                 unbecome_root();
3626                 
3627         /* ================ END SeMachineAccountPrivilege BLOCK ================ */
3628
3629         if (NT_STATUS_IS_OK(r_u->status)) {
3630                 force_flush_samr_cache(disp_info);
3631         }
3632
3633         return r_u->status;
3634 }
3635
3636 /*******************************************************************
3637  samr_reply_set_userinfo2
3638  ********************************************************************/
3639
3640 NTSTATUS _samr_set_userinfo2(pipes_struct *p, SAMR_Q_SET_USERINFO2 *q_u, SAMR_R_SET_USERINFO2 *r_u)
3641 {
3642         struct samu *pwd = NULL;
3643         DOM_SID sid;
3644         SAM_USERINFO_CTR *ctr = q_u->ctr;
3645         POLICY_HND *pol = &q_u->pol;
3646         uint16 switch_value = q_u->switch_value;
3647         uint32 acc_granted;
3648         uint32 acc_required;
3649         BOOL ret;
3650         BOOL has_enough_rights = False;
3651         uint32 acb_info;
3652         DISP_INFO *disp_info = NULL;
3653
3654         DEBUG(5, ("samr_reply_set_userinfo2: %d\n", __LINE__));
3655
3656         r_u->status = NT_STATUS_OK;
3657
3658         /* find the policy handle.  open a policy on it. */
3659         if (!get_lsa_policy_samr_sid(p, pol, &sid, &acc_granted, &disp_info))
3660                 return NT_STATUS_INVALID_HANDLE;
3661
3662                 
3663 #if 0   /* this really should be applied on a per info level basis   --jerry */
3664
3665         /* observed when joining XP client to Samba domain */
3666         acc_required = SA_RIGHT_USER_SET_PASSWORD | SA_RIGHT_USER_SET_ATTRIBUTES | SA_RIGHT_USER_ACCT_FLAGS_EXPIRY;
3667 #else
3668         acc_required = SA_RIGHT_USER_SET_ATTRIBUTES;
3669 #endif
3670         
3671         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, acc_required, "_samr_set_userinfo2"))) {
3672                 return r_u->status;
3673         }
3674
3675         DEBUG(5, ("samr_reply_set_userinfo2: sid:%s\n", sid_string_static(&sid)));
3676
3677         if (ctr == NULL) {
3678                 DEBUG(5, ("samr_reply_set_userinfo2: NULL info level\n"));
3679                 return NT_STATUS_INVALID_INFO_CLASS;
3680         }
3681
3682         switch_value=ctr->switch_value;
3683
3684         if ( !(pwd = samu_new( NULL )) ) {
3685                 return NT_STATUS_NO_MEMORY;
3686         }
3687
3688         become_root();
3689         ret = pdb_getsampwsid(pwd, &sid);
3690         unbecome_root();
3691         
3692         if ( !ret ) {
3693                 TALLOC_FREE(pwd);
3694                 return NT_STATUS_NO_SUCH_USER;
3695         }
3696         
3697         acb_info = pdb_get_acct_ctrl(pwd);
3698         if ( acb_info & ACB_WSTRUST ) 
3699                 has_enough_rights = user_has_privileges( p->pipe_user.nt_user_token, &se_machine_account);
3700         else if ( acb_info & ACB_NORMAL )
3701                 has_enough_rights = user_has_privileges( p->pipe_user.nt_user_token, &se_add_users );
3702         else if ( acb_info & (ACB_SVRTRUST|ACB_DOMTRUST) ) {
3703                 if ( lp_enable_privileges() )
3704                         has_enough_rights = nt_token_check_domain_rid( p->pipe_user.nt_user_token, DOMAIN_GROUP_RID_ADMINS );
3705         }
3706         
3707         DEBUG(5, ("_samr_set_userinfo2: %s does%s possess sufficient rights\n",
3708                   uidtoname(p->pipe_user.ut.uid),
3709                   has_enough_rights ? "" : " not"));
3710
3711         /* ================ BEGIN SeMachineAccountPrivilege BLOCK ================ */
3712         
3713         if ( has_enough_rights )                                
3714                 become_root(); 
3715         
3716         /* ok!  user info levels (lots: see MSDEV help), off we go... */
3717         
3718         switch (switch_value) {
3719                 case 7:
3720                         r_u->status = set_user_info_7(p->mem_ctx,
3721                                                       ctr->info.id7, pwd);
3722                         break;
3723                 case 16:
3724                         if (!set_user_info_16(ctr->info.id16, pwd))
3725                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3726                         break;
3727                 case 18:
3728                         /* Used by AS/U JRA. */
3729                         if (!set_user_info_18(ctr->info.id18, pwd))
3730                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3731                         break;
3732                 case 20:
3733                         if (!set_user_info_20(ctr->info.id20, pwd))
3734                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3735                         break;
3736                 case 21:
3737                         r_u->status = set_user_info_21(p->mem_ctx,
3738                                                        ctr->info.id21, pwd);
3739                         break;
3740                 case 23:
3741                         if (!p->session_key.length) {
3742                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3743                         }
3744                         SamOEMhashBlob(ctr->info.id23->pass, 516, &p->session_key);
3745
3746                         dump_data(100, (char *)ctr->info.id23->pass, 516);
3747
3748                         r_u->status = set_user_info_23(p->mem_ctx,
3749                                                        ctr->info.id23, pwd);
3750                         break;
3751                 case 26:
3752                         if (!p->session_key.length) {
3753                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3754                         }
3755                         encode_or_decode_arc4_passwd_buffer(ctr->info.id26->pass, &p->session_key);
3756
3757                         dump_data(100, (char *)ctr->info.id26->pass, 516);
3758
3759                         if (!set_user_info_pw(ctr->info.id26->pass, pwd))
3760                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3761                         break;
3762                 default:
3763                         r_u->status = NT_STATUS_INVALID_INFO_CLASS;
3764         }
3765
3766         if ( has_enough_rights )                                
3767                 unbecome_root();
3768                 
3769         /* ================ END SeMachineAccountPrivilege BLOCK ================ */
3770
3771         if (NT_STATUS_IS_OK(r_u->status)) {
3772                 force_flush_samr_cache(disp_info);
3773         }
3774
3775         return r_u->status;
3776 }
3777
3778 /*********************************************************************
3779  _samr_query_aliasmem
3780 *********************************************************************/
3781
3782 NTSTATUS _samr_query_useraliases(pipes_struct *p, SAMR_Q_QUERY_USERALIASES *q_u, SAMR_R_QUERY_USERALIASES *r_u)
3783 {
3784         size_t num_alias_rids;
3785         uint32 *alias_rids;
3786         struct samr_info *info = NULL;
3787         size_t i;
3788                 
3789         NTSTATUS ntstatus1;
3790         NTSTATUS ntstatus2;
3791
3792         DOM_SID *members;
3793
3794         r_u->status = NT_STATUS_OK;
3795
3796         DEBUG(5,("_samr_query_useraliases: %d\n", __LINE__));
3797
3798         /* find the policy handle.  open a policy on it. */
3799         if (!find_policy_by_hnd(p, &q_u->pol, (void **)(void *)&info))
3800                 return NT_STATUS_INVALID_HANDLE;
3801                 
3802         ntstatus1 = access_check_samr_function(info->acc_granted, SA_RIGHT_DOMAIN_LOOKUP_ALIAS_BY_MEM, "_samr_query_useraliases");
3803         ntstatus2 = access_check_samr_function(info->acc_granted, SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_query_useraliases");
3804         
3805         if (!NT_STATUS_IS_OK(ntstatus1) || !NT_STATUS_IS_OK(ntstatus2)) {
3806                 if (!(NT_STATUS_EQUAL(ntstatus1,NT_STATUS_ACCESS_DENIED) && NT_STATUS_IS_OK(ntstatus2)) &&
3807                     !(NT_STATUS_EQUAL(ntstatus1,NT_STATUS_ACCESS_DENIED) && NT_STATUS_IS_OK(ntstatus1))) {
3808                         return (NT_STATUS_IS_OK(ntstatus1)) ? ntstatus2 : ntstatus1;
3809                 }
3810         }               
3811
3812         if (!sid_check_is_domain(&info->sid) &&
3813             !sid_check_is_builtin(&info->sid))
3814                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
3815
3816         members = TALLOC_ARRAY(p->mem_ctx, DOM_SID, q_u->num_sids1);
3817
3818         if (members == NULL)
3819                 return NT_STATUS_NO_MEMORY;
3820
3821         for (i=0; i<q_u->num_sids1; i++)
3822                 sid_copy(&members[i], &q_u->sid[i].sid);
3823
3824         alias_rids = NULL;
3825         num_alias_rids = 0;
3826
3827         become_root();
3828         ntstatus1 = pdb_enum_alias_memberships(p->mem_ctx, &info->sid, members,
3829                                                q_u->num_sids1,
3830                                                &alias_rids, &num_alias_rids);
3831         unbecome_root();
3832
3833         if (!NT_STATUS_IS_OK(ntstatus1)) {
3834                 return ntstatus1;
3835         }
3836
3837         init_samr_r_query_useraliases(r_u, num_alias_rids, alias_rids,
3838                                       NT_STATUS_OK);
3839         return NT_STATUS_OK;
3840 }
3841
3842 /*********************************************************************
3843  _samr_query_aliasmem
3844 *********************************************************************/
3845
3846 NTSTATUS _samr_query_aliasmem(pipes_struct *p, SAMR_Q_QUERY_ALIASMEM *q_u, SAMR_R_QUERY_ALIASMEM *r_u)
3847 {
3848         NTSTATUS status;
3849         size_t i;
3850         size_t num_sids = 0;
3851         DOM_SID2 *sid;
3852         DOM_SID *sids=NULL;
3853
3854         DOM_SID alias_sid;
3855
3856         uint32 acc_granted;
3857
3858         /* find the policy handle.  open a policy on it. */
3859         if (!get_lsa_policy_samr_sid(p, &q_u->alias_pol, &alias_sid, &acc_granted, NULL)) 
3860                 return NT_STATUS_INVALID_HANDLE;
3861         
3862         if (!NT_STATUS_IS_OK(r_u->status = 
3863                 access_check_samr_function(acc_granted, SA_RIGHT_ALIAS_GET_MEMBERS, "_samr_query_aliasmem"))) {
3864                 return r_u->status;
3865         }
3866
3867         DEBUG(10, ("sid is %s\n", sid_string_static(&alias_sid)));
3868
3869         become_root();
3870         status = pdb_enum_aliasmem(&alias_sid, &sids, &num_sids);
3871         unbecome_root();
3872
3873         if (!NT_STATUS_IS_OK(status)) {
3874                 return status;
3875         }
3876
3877         sid = TALLOC_ZERO_ARRAY(p->mem_ctx, DOM_SID2, num_sids);        
3878         if (num_sids!=0 && sid == NULL) {
3879                 SAFE_FREE(sids);
3880                 return NT_STATUS_NO_MEMORY;
3881         }
3882
3883         for (i = 0; i < num_sids; i++) {
3884                 init_dom_sid2(&sid[i], &sids[i]);
3885         }
3886
3887         init_samr_r_query_aliasmem(r_u, num_sids, sid, NT_STATUS_OK);
3888
3889         SAFE_FREE(sids);
3890
3891         return NT_STATUS_OK;
3892 }
3893
3894 /*********************************************************************
3895  _samr_query_groupmem
3896 *********************************************************************/
3897
3898 NTSTATUS _samr_query_groupmem(pipes_struct *p, SAMR_Q_QUERY_GROUPMEM *q_u, SAMR_R_QUERY_GROUPMEM *r_u)
3899 {
3900         DOM_SID group_sid;
3901         fstring group_sid_str;
3902         size_t i, num_members;
3903
3904         uint32 *rid=NULL;
3905         uint32 *attr=NULL;
3906
3907         uint32 acc_granted;
3908
3909         NTSTATUS result;
3910
3911         /* find the policy handle.  open a policy on it. */
3912         if (!get_lsa_policy_samr_sid(p, &q_u->group_pol, &group_sid, &acc_granted, NULL)) 
3913                 return NT_STATUS_INVALID_HANDLE;
3914                 
3915         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_GROUP_GET_MEMBERS, "_samr_query_groupmem"))) {
3916                 return r_u->status;
3917         }
3918                 
3919         sid_to_string(group_sid_str, &group_sid);
3920         DEBUG(10, ("sid is %s\n", group_sid_str));
3921
3922         if (!sid_check_is_in_our_domain(&group_sid)) {
3923                 DEBUG(3, ("sid %s is not in our domain\n", group_sid_str));
3924                 return NT_STATUS_NO_SUCH_GROUP;
3925         }
3926
3927         DEBUG(10, ("lookup on Domain SID\n"));
3928
3929         become_root();
3930         result = pdb_enum_group_members(p->mem_ctx, &group_sid,
3931                                         &rid, &num_members);
3932         unbecome_root();
3933
3934         if (!NT_STATUS_IS_OK(result))
3935                 return result;
3936
3937         attr=TALLOC_ZERO_ARRAY(p->mem_ctx, uint32, num_members);
3938         
3939         if ((num_members!=0) && (attr==NULL))
3940                 return NT_STATUS_NO_MEMORY;
3941         
3942         for (i=0; i<num_members; i++)
3943                 attr[i] = SID_NAME_USER;
3944
3945         init_samr_r_query_groupmem(r_u, num_members, rid, attr, NT_STATUS_OK);
3946
3947         return NT_STATUS_OK;
3948 }
3949
3950 /*********************************************************************
3951  _samr_add_aliasmem
3952 *********************************************************************/
3953
3954 NTSTATUS _samr_add_aliasmem(pipes_struct *p, SAMR_Q_ADD_ALIASMEM *q_u, SAMR_R_ADD_ALIASMEM *r_u)
3955 {
3956         DOM_SID alias_sid;
3957         uint32 acc_granted;
3958         SE_PRIV se_rights;
3959         BOOL can_add_accounts;
3960         NTSTATUS ret;
3961         DISP_INFO *disp_info = NULL;
3962
3963         /* Find the policy handle. Open a policy on it. */
3964         if (!get_lsa_policy_samr_sid(p, &q_u->alias_pol, &alias_sid, &acc_granted, &disp_info)) 
3965                 return NT_STATUS_INVALID_HANDLE;
3966         
3967         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_ALIAS_ADD_MEMBER, "_samr_add_aliasmem"))) {
3968                 return r_u->status;
3969         }
3970                 
3971         DEBUG(10, ("sid is %s\n", sid_string_static(&alias_sid)));
3972         
3973         se_priv_copy( &se_rights, &se_add_users );
3974         can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
3975
3976         /******** BEGIN SeAddUsers BLOCK *********/
3977         
3978         if ( can_add_accounts )
3979                 become_root();
3980         
3981         ret = pdb_add_aliasmem(&alias_sid, &q_u->sid.sid);
3982         
3983         if ( can_add_accounts )
3984                 unbecome_root();
3985                 
3986         /******** END SeAddUsers BLOCK *********/
3987         
3988         if (NT_STATUS_IS_OK(ret)) {
3989                 force_flush_samr_cache(disp_info);
3990         }
3991
3992         return ret;
3993 }
3994
3995 /*********************************************************************
3996  _samr_del_aliasmem
3997 *********************************************************************/
3998
3999 NTSTATUS _samr_del_aliasmem(pipes_struct *p, SAMR_Q_DEL_ALIASMEM *q_u, SAMR_R_DEL_ALIASMEM *r_u)
4000 {
4001         DOM_SID alias_sid;
4002         uint32 acc_granted;
4003         SE_PRIV se_rights;
4004         BOOL can_add_accounts;
4005         NTSTATUS ret;
4006         DISP_INFO *disp_info = NULL;
4007
4008         /* Find the policy handle. Open a policy on it. */
4009         if (!get_lsa_policy_samr_sid(p, &q_u->alias_pol, &alias_sid, &acc_granted, &disp_info)) 
4010                 return NT_STATUS_INVALID_HANDLE;
4011         
4012         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_ALIAS_REMOVE_MEMBER, "_samr_del_aliasmem"))) {
4013                 return r_u->status;
4014         }
4015         
4016         DEBUG(10, ("_samr_del_aliasmem:sid is %s\n",
4017                    sid_string_static(&alias_sid)));
4018
4019         se_priv_copy( &se_rights, &se_add_users );
4020         can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
4021
4022         /******** BEGIN SeAddUsers BLOCK *********/
4023         
4024         if ( can_add_accounts )
4025                 become_root();
4026
4027         ret = pdb_del_aliasmem(&alias_sid, &q_u->sid.sid);
4028         
4029         if ( can_add_accounts )
4030                 unbecome_root();
4031                 
4032         /******** END SeAddUsers BLOCK *********/
4033         
4034         if (NT_STATUS_IS_OK(ret)) {
4035                 force_flush_samr_cache(disp_info);
4036         }
4037
4038         return ret;
4039 }
4040
4041 /*********************************************************************
4042  _samr_add_groupmem
4043 *********************************************************************/
4044
4045 NTSTATUS _samr_add_groupmem(pipes_struct *p, SAMR_Q_ADD_GROUPMEM *q_u, SAMR_R_ADD_GROUPMEM *r_u)
4046 {
4047         DOM_SID group_sid;
4048         uint32 group_rid;
4049         uint32 acc_granted;
4050         SE_PRIV se_rights;
4051         BOOL can_add_accounts;
4052         DISP_INFO *disp_info = NULL;
4053
4054         /* Find the policy handle. Open a policy on it. */
4055         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &group_sid, &acc_granted, &disp_info)) 
4056                 return NT_STATUS_INVALID_HANDLE;
4057         
4058         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_GROUP_ADD_MEMBER, "_samr_add_groupmem"))) {
4059                 return r_u->status;
4060         }
4061
4062         DEBUG(10, ("sid is %s\n", sid_string_static(&group_sid)));
4063
4064         if (!sid_peek_check_rid(get_global_sam_sid(), &group_sid,
4065                                 &group_rid)) {
4066                 return NT_STATUS_INVALID_HANDLE;
4067         }
4068
4069         se_priv_copy( &se_rights, &se_add_users );
4070         can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
4071
4072         /******** BEGIN SeAddUsers BLOCK *********/
4073         
4074         if ( can_add_accounts )
4075                 become_root();
4076
4077         r_u->status = pdb_add_groupmem(p->mem_ctx, group_rid, q_u->rid);
4078                 
4079         if ( can_add_accounts )
4080                 unbecome_root();
4081                 
4082         /******** END SeAddUsers BLOCK *********/
4083         
4084         force_flush_samr_cache(disp_info);
4085
4086         return r_u->status;
4087 }
4088
4089 /*********************************************************************
4090  _samr_del_groupmem
4091 *********************************************************************/
4092
4093 NTSTATUS _samr_del_groupmem(pipes_struct *p, SAMR_Q_DEL_GROUPMEM *q_u, SAMR_R_DEL_GROUPMEM *r_u)
4094 {
4095         DOM_SID group_sid;
4096         uint32 group_rid;
4097         uint32 acc_granted;
4098         SE_PRIV se_rights;
4099         BOOL can_add_accounts;
4100         DISP_INFO *disp_info = NULL;
4101
4102         /*
4103          * delete the group member named q_u->rid
4104          * who is a member of the sid associated with the handle
4105          * the rid is a user's rid as the group is a domain group.
4106          */
4107
4108         /* Find the policy handle. Open a policy on it. */
4109         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &group_sid, &acc_granted, &disp_info)) 
4110                 return NT_STATUS_INVALID_HANDLE;
4111         
4112         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_GROUP_REMOVE_MEMBER, "_samr_del_groupmem"))) {
4113                 return r_u->status;
4114         }
4115
4116         if (!sid_peek_check_rid(get_global_sam_sid(), &group_sid,
4117                                 &group_rid)) {
4118                 return NT_STATUS_INVALID_HANDLE;
4119         }
4120
4121         se_priv_copy( &se_rights, &se_add_users );
4122         can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
4123
4124         /******** BEGIN SeAddUsers BLOCK *********/
4125         
4126         if ( can_add_accounts )
4127                 become_root();
4128                 
4129         r_u->status = pdb_del_groupmem(p->mem_ctx, group_rid, q_u->rid);
4130
4131         if ( can_add_accounts )
4132                 unbecome_root();
4133                 
4134         /******** END SeAddUsers BLOCK *********/
4135         
4136         force_flush_samr_cache(disp_info);
4137
4138         return r_u->status;
4139 }
4140
4141 /*********************************************************************
4142  _samr_delete_dom_user
4143 *********************************************************************/
4144
4145 NTSTATUS _samr_delete_dom_user(pipes_struct *p, SAMR_Q_DELETE_DOM_USER *q_u, SAMR_R_DELETE_DOM_USER *r_u )
4146 {
4147         DOM_SID user_sid;
4148         struct samu *sam_pass=NULL;
4149         uint32 acc_granted;
4150         BOOL can_add_accounts;
4151         uint32 acb_info;
4152         DISP_INFO *disp_info = NULL;
4153         BOOL ret;
4154
4155         DEBUG(5, ("_samr_delete_dom_user: %d\n", __LINE__));
4156
4157         /* Find the policy handle. Open a policy on it. */
4158         if (!get_lsa_policy_samr_sid(p, &q_u->user_pol, &user_sid, &acc_granted, &disp_info)) 
4159                 return NT_STATUS_INVALID_HANDLE;
4160                 
4161         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, STD_RIGHT_DELETE_ACCESS, "_samr_delete_dom_user"))) {
4162                 return r_u->status;
4163         }
4164                 
4165         if (!sid_check_is_in_our_domain(&user_sid))
4166                 return NT_STATUS_CANNOT_DELETE;
4167
4168         /* check if the user exists before trying to delete */
4169         if ( !(sam_pass = samu_new( NULL )) ) {
4170                 return NT_STATUS_NO_MEMORY;
4171         }
4172
4173         become_root();
4174         ret = pdb_getsampwsid(sam_pass, &user_sid);
4175         unbecome_root();
4176
4177         if( !ret ) {
4178                 DEBUG(5,("_samr_delete_dom_user:User %s doesn't exist.\n", 
4179                         sid_string_static(&user_sid)));
4180                 TALLOC_FREE(sam_pass);
4181                 return NT_STATUS_NO_SUCH_USER;
4182         }
4183         
4184         acb_info = pdb_get_acct_ctrl(sam_pass);
4185
4186         /* For machine accounts it's the SeMachineAccountPrivilege that counts. */
4187         if ( acb_info & ACB_WSTRUST ) {
4188                 can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_machine_account );
4189         } else {
4190                 can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_add_users );
4191         } 
4192
4193         /******** BEGIN SeAddUsers BLOCK *********/
4194         
4195         if ( can_add_accounts )
4196                 become_root();
4197
4198         r_u->status = pdb_delete_user(p->mem_ctx, sam_pass);
4199
4200         if ( can_add_accounts )
4201                 unbecome_root();
4202                 
4203         /******** END SeAddUsers BLOCK *********/
4204                 
4205         if ( !NT_STATUS_IS_OK(r_u->status) ) {
4206                 DEBUG(5,("_samr_delete_dom_user: Failed to delete entry for "
4207                          "user %s: %s.\n", pdb_get_username(sam_pass),
4208                          nt_errstr(r_u->status)));
4209                 TALLOC_FREE(sam_pass);
4210                 return r_u->status;
4211         }
4212
4213
4214         TALLOC_FREE(sam_pass);
4215
4216         if (!close_policy_hnd(p, &q_u->user_pol))
4217                 return NT_STATUS_OBJECT_NAME_INVALID;
4218
4219         force_flush_samr_cache(disp_info);
4220
4221         return NT_STATUS_OK;
4222 }
4223
4224 /*********************************************************************
4225  _samr_delete_dom_group
4226 *********************************************************************/
4227
4228 NTSTATUS _samr_delete_dom_group(pipes_struct *p, SAMR_Q_DELETE_DOM_GROUP *q_u, SAMR_R_DELETE_DOM_GROUP *r_u)
4229 {
4230         DOM_SID group_sid;
4231         uint32 group_rid;
4232         uint32 acc_granted;
4233         SE_PRIV se_rights;
4234         BOOL can_add_accounts;
4235         DISP_INFO *disp_info = NULL;
4236
4237         DEBUG(5, ("samr_delete_dom_group: %d\n", __LINE__));
4238
4239         /* Find the policy handle. Open a policy on it. */
4240         if (!get_lsa_policy_samr_sid(p, &q_u->group_pol, &group_sid, &acc_granted, &disp_info)) 
4241                 return NT_STATUS_INVALID_HANDLE;
4242                 
4243         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, STD_RIGHT_DELETE_ACCESS, "_samr_delete_dom_group"))) {
4244                 return r_u->status;
4245         }
4246
4247         DEBUG(10, ("sid is %s\n", sid_string_static(&group_sid)));
4248
4249         if (!sid_peek_check_rid(get_global_sam_sid(), &group_sid,
4250                                 &group_rid)) {
4251                 return NT_STATUS_NO_SUCH_GROUP;
4252         }
4253
4254         se_priv_copy( &se_rights, &se_add_users );
4255         can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
4256
4257         /******** BEGIN SeAddUsers BLOCK *********/
4258         
4259         if ( can_add_accounts )
4260                 become_root();
4261
4262         r_u->status = pdb_delete_dom_group(p->mem_ctx, group_rid);
4263
4264         if ( can_add_accounts )
4265                 unbecome_root();
4266                 
4267         /******** END SeAddUsers BLOCK *********/
4268         
4269         if ( !NT_STATUS_IS_OK(r_u->status) ) {
4270                 DEBUG(5,("_samr_delete_dom_group: Failed to delete mapping "
4271                          "entry for group %s: %s\n",
4272                          sid_string_static(&group_sid),
4273                          nt_errstr(r_u->status)));
4274                 return r_u->status;
4275         }
4276         
4277         if (!close_policy_hnd(p, &q_u->group_pol))
4278                 return NT_STATUS_OBJECT_NAME_INVALID;
4279
4280         force_flush_samr_cache(disp_info);
4281
4282         return NT_STATUS_OK;
4283 }
4284
4285 /*********************************************************************
4286  _samr_delete_dom_alias
4287 *********************************************************************/
4288
4289 NTSTATUS _samr_delete_dom_alias(pipes_struct *p, SAMR_Q_DELETE_DOM_ALIAS *q_u, SAMR_R_DELETE_DOM_ALIAS *r_u)
4290 {
4291         DOM_SID alias_sid;
4292         uint32 acc_granted;
4293         SE_PRIV se_rights;
4294         BOOL can_add_accounts;
4295         BOOL ret;
4296         DISP_INFO *disp_info = NULL;
4297
4298         DEBUG(5, ("_samr_delete_dom_alias: %d\n", __LINE__));
4299
4300         /* Find the policy handle. Open a policy on it. */
4301         if (!get_lsa_policy_samr_sid(p, &q_u->alias_pol, &alias_sid, &acc_granted, &disp_info)) 
4302                 return NT_STATUS_INVALID_HANDLE;
4303         
4304         /* copy the handle to the outgoing reply */
4305
4306         memcpy( &r_u->pol, &q_u->alias_pol, sizeof(r_u->pol) );
4307
4308         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, STD_RIGHT_DELETE_ACCESS, "_samr_delete_dom_alias"))) {
4309                 return r_u->status;
4310         }
4311
4312         DEBUG(10, ("sid is %s\n", sid_string_static(&alias_sid)));
4313
4314         /* Don't let Windows delete builtin groups */
4315
4316         if ( sid_check_is_in_builtin( &alias_sid ) ) {
4317                 return NT_STATUS_SPECIAL_ACCOUNT;
4318         }
4319
4320         if (!sid_check_is_in_our_domain(&alias_sid))
4321                 return NT_STATUS_NO_SUCH_ALIAS;
4322                 
4323         DEBUG(10, ("lookup on Local SID\n"));
4324
4325         se_priv_copy( &se_rights, &se_add_users );
4326         can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
4327
4328         /******** BEGIN SeAddUsers BLOCK *********/
4329         
4330         if ( can_add_accounts )
4331                 become_root();
4332
4333         /* Have passdb delete the alias */
4334         ret = pdb_delete_alias(&alias_sid);
4335         
4336         if ( can_add_accounts )
4337                 unbecome_root();
4338                 
4339         /******** END SeAddUsers BLOCK *********/
4340
4341         if ( !ret )
4342                 return NT_STATUS_ACCESS_DENIED;
4343
4344         if (!close_policy_hnd(p, &q_u->alias_pol))
4345                 return NT_STATUS_OBJECT_NAME_INVALID;
4346
4347         force_flush_samr_cache(disp_info);
4348
4349         return NT_STATUS_OK;
4350 }
4351
4352 /*********************************************************************
4353  _samr_create_dom_group
4354 *********************************************************************/
4355
4356 NTSTATUS _samr_create_dom_group(pipes_struct *p, SAMR_Q_CREATE_DOM_GROUP *q_u, SAMR_R_CREATE_DOM_GROUP *r_u)
4357 {
4358         DOM_SID dom_sid;
4359         DOM_SID info_sid;
4360         const char *name;
4361         struct samr_info *info;
4362         uint32 acc_granted;
4363         SE_PRIV se_rights;
4364         BOOL can_add_accounts;
4365         DISP_INFO *disp_info = NULL;
4366
4367         /* Find the policy handle. Open a policy on it. */
4368         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &dom_sid, &acc_granted, &disp_info)) 
4369                 return NT_STATUS_INVALID_HANDLE;
4370         
4371         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_DOMAIN_CREATE_GROUP, "_samr_create_dom_group"))) {
4372                 return r_u->status;
4373         }
4374                 
4375         if (!sid_equal(&dom_sid, get_global_sam_sid()))
4376                 return NT_STATUS_ACCESS_DENIED;
4377
4378         name = rpcstr_pull_unistr2_talloc(p->mem_ctx, &q_u->uni_acct_desc);
4379         if (name == NULL) {
4380                 return NT_STATUS_NO_MEMORY;
4381         }
4382
4383         r_u->status = can_create(p->mem_ctx, name);
4384         if (!NT_STATUS_IS_OK(r_u->status)) {
4385                 return r_u->status;
4386         }
4387
4388         se_priv_copy( &se_rights, &se_add_users );
4389         can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
4390
4391         /******** BEGIN SeAddUsers BLOCK *********/
4392         
4393         if ( can_add_accounts )
4394                 become_root();
4395         
4396         /* check that we successfully create the UNIX group */
4397         
4398         r_u->status = pdb_create_dom_group(p->mem_ctx, name, &r_u->rid);
4399
4400         if ( can_add_accounts )
4401                 unbecome_root();
4402                 
4403         /******** END SeAddUsers BLOCK *********/
4404         
4405         /* check if we should bail out here */
4406         
4407         if ( !NT_STATUS_IS_OK(r_u->status) )
4408                 return r_u->status;
4409
4410         sid_compose(&info_sid, get_global_sam_sid(), r_u->rid);
4411         
4412         if ((info = get_samr_info_by_sid(&info_sid)) == NULL)
4413                 return NT_STATUS_NO_MEMORY;
4414
4415         /* they created it; let the user do what he wants with it */
4416
4417         info->acc_granted = GENERIC_RIGHTS_GROUP_ALL_ACCESS;
4418
4419         /* get a (unique) handle.  open a policy on it. */
4420         if (!create_policy_hnd(p, &r_u->pol, free_samr_info, (void *)info))
4421                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4422
4423         force_flush_samr_cache(disp_info);
4424
4425         return NT_STATUS_OK;
4426 }
4427
4428 /*********************************************************************
4429  _samr_create_dom_alias
4430 *********************************************************************/
4431
4432 NTSTATUS _samr_create_dom_alias(pipes_struct *p, SAMR_Q_CREATE_DOM_ALIAS *q_u, SAMR_R_CREATE_DOM_ALIAS *r_u)
4433 {
4434         DOM_SID dom_sid;
4435         DOM_SID info_sid;
4436         fstring name;
4437         struct samr_info *info;
4438         uint32 acc_granted;
4439         gid_t gid;
4440         NTSTATUS result;
4441         SE_PRIV se_rights;
4442         BOOL can_add_accounts;
4443         DISP_INFO *disp_info = NULL;
4444
4445         /* Find the policy handle. Open a policy on it. */
4446         if (!get_lsa_policy_samr_sid(p, &q_u->dom_pol, &dom_sid, &acc_granted, &disp_info)) 
4447                 return NT_STATUS_INVALID_HANDLE;
4448                 
4449         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_DOMAIN_CREATE_ALIAS, "_samr_create_alias"))) {
4450                 return r_u->status;
4451         }
4452                 
4453         if (!sid_equal(&dom_sid, get_global_sam_sid()))
4454                 return NT_STATUS_ACCESS_DENIED;
4455
4456         unistr2_to_ascii(name, &q_u->uni_acct_desc, sizeof(name)-1);
4457
4458         se_priv_copy( &se_rights, &se_add_users );
4459         can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
4460
4461         result = can_create(p->mem_ctx, name);
4462         if (!NT_STATUS_IS_OK(result)) {
4463                 return result;
4464         }
4465
4466         /******** BEGIN SeAddUsers BLOCK *********/
4467         
4468         if ( can_add_accounts )
4469                 become_root();
4470
4471         /* Have passdb create the alias */
4472         result = pdb_create_alias(name, &r_u->rid);
4473
4474         if ( can_add_accounts )
4475                 unbecome_root();
4476                 
4477         /******** END SeAddUsers BLOCK *********/
4478
4479         if (!NT_STATUS_IS_OK(result)) {
4480                 DEBUG(10, ("pdb_create_alias failed: %s\n",
4481                            nt_errstr(result)));
4482                 return result;
4483         }
4484
4485         sid_copy(&info_sid, get_global_sam_sid());
4486         sid_append_rid(&info_sid, r_u->rid);
4487
4488         if (!sid_to_gid(&info_sid, &gid)) {
4489                 DEBUG(10, ("Could not find alias just created\n"));
4490                 return NT_STATUS_ACCESS_DENIED;
4491         }
4492
4493         /* check if the group has been successfully created */
4494         if ( getgrgid(gid) == NULL ) {
4495                 DEBUG(10, ("getgrgid(%d) of just created alias failed\n",
4496                            gid));
4497                 return NT_STATUS_ACCESS_DENIED;
4498         }
4499
4500         if ((info = get_samr_info_by_sid(&info_sid)) == NULL)
4501                 return NT_STATUS_NO_MEMORY;
4502
4503         /* they created it; let the user do what he wants with it */
4504
4505         info->acc_granted = GENERIC_RIGHTS_ALIAS_ALL_ACCESS;
4506
4507         /* get a (unique) handle.  open a policy on it. */
4508         if (!create_policy_hnd(p, &r_u->alias_pol, free_samr_info, (void *)info))
4509                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4510
4511         force_flush_samr_cache(disp_info);
4512
4513         return NT_STATUS_OK;
4514 }
4515
4516 /*********************************************************************
4517  _samr_query_groupinfo
4518
4519 sends the name/comment pair of a domain group
4520 level 1 send also the number of users of that group
4521 *********************************************************************/
4522
4523 NTSTATUS _samr_query_groupinfo(pipes_struct *p, SAMR_Q_QUERY_GROUPINFO *q_u, SAMR_R_QUERY_GROUPINFO *r_u)
4524 {
4525         DOM_SID group_sid;
4526         GROUP_MAP map;
4527         GROUP_INFO_CTR *ctr;
4528         uint32 acc_granted;
4529         BOOL ret;
4530
4531         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &group_sid, &acc_granted, NULL)) 
4532                 return NT_STATUS_INVALID_HANDLE;
4533         
4534         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_GROUP_LOOKUP_INFO, "_samr_query_groupinfo"))) {
4535                 return r_u->status;
4536         }
4537                 
4538         become_root();
4539         ret = get_domain_group_from_sid(group_sid, &map);
4540         unbecome_root();
4541         if (!ret)
4542                 return NT_STATUS_INVALID_HANDLE;
4543
4544         ctr=TALLOC_ZERO_P(p->mem_ctx, GROUP_INFO_CTR);
4545         if (ctr==NULL)
4546                 return NT_STATUS_NO_MEMORY;
4547
4548         switch (q_u->switch_level) {
4549                 case 1: {
4550                         uint32 *members;
4551                         size_t num_members;
4552
4553                         ctr->switch_value1 = 1;
4554
4555                         become_root();
4556                         r_u->status = pdb_enum_group_members(
4557                                 p->mem_ctx, &group_sid, &members, &num_members);
4558                         unbecome_root();
4559         
4560                         if (!NT_STATUS_IS_OK(r_u->status)) {
4561                                 return r_u->status;
4562                         }
4563
4564                         init_samr_group_info1(&ctr->group.info1, map.nt_name,
4565                                       map.comment, num_members);
4566                         break;
4567                 }
4568                 case 2:
4569                         ctr->switch_value1 = 2;
4570                         init_samr_group_info2(&ctr->group.info2, map.nt_name);
4571                         break;
4572                 case 3:
4573                         ctr->switch_value1 = 3;
4574                         init_samr_group_info3(&ctr->group.info3);
4575                         break;
4576                 case 4:
4577                         ctr->switch_value1 = 4;
4578                         init_samr_group_info4(&ctr->group.info4, map.comment);
4579                         break;
4580                 case 5: {
4581                         /*
4582                         uint32 *members;
4583                         size_t num_members;
4584                         */
4585
4586                         ctr->switch_value1 = 5;
4587
4588                         /*
4589                         become_root();
4590                         r_u->status = pdb_enum_group_members(
4591                                 p->mem_ctx, &group_sid, &members, &num_members);
4592                         unbecome_root();
4593         
4594                         if (!NT_STATUS_IS_OK(r_u->status)) {
4595                                 return r_u->status;
4596                         }
4597                         */
4598                         init_samr_group_info5(&ctr->group.info5, map.nt_name,
4599                                       map.comment, 0 /* num_members */); /* in w2k3 this is always 0 */
4600                         break;
4601                 }
4602                 default:
4603                         return NT_STATUS_INVALID_INFO_CLASS;
4604         }
4605
4606         init_samr_r_query_groupinfo(r_u, ctr, NT_STATUS_OK);
4607
4608         return NT_STATUS_OK;
4609 }
4610
4611 /*********************************************************************
4612  _samr_set_groupinfo
4613  
4614  update a domain group's comment.
4615 *********************************************************************/
4616
4617 NTSTATUS _samr_set_groupinfo(pipes_struct *p, SAMR_Q_SET_GROUPINFO *q_u, SAMR_R_SET_GROUPINFO *r_u)
4618 {
4619         DOM_SID group_sid;
4620         GROUP_MAP map;
4621         GROUP_INFO_CTR *ctr;
4622         uint32 acc_granted;
4623         NTSTATUS ret;
4624         BOOL result;
4625         BOOL can_mod_accounts;
4626         DISP_INFO *disp_info = NULL;
4627
4628         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &group_sid, &acc_granted, &disp_info))
4629                 return NT_STATUS_INVALID_HANDLE;
4630         
4631         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_GROUP_SET_INFO, "_samr_set_groupinfo"))) {
4632                 return r_u->status;
4633         }
4634
4635         become_root();
4636         result = get_domain_group_from_sid(group_sid, &map);
4637         unbecome_root();
4638         if (!result)
4639                 return NT_STATUS_NO_SUCH_GROUP;
4640         
4641         ctr=q_u->ctr;
4642
4643         switch (ctr->switch_value1) {
4644                 case 1:
4645                         unistr2_to_ascii(map.comment, &(ctr->group.info1.uni_acct_desc), sizeof(map.comment)-1);
4646                         break;
4647                 case 4:
4648                         unistr2_to_ascii(map.comment, &(ctr->group.info4.uni_acct_desc), sizeof(map.comment)-1);
4649                         break;
4650                 default:
4651                         return NT_STATUS_INVALID_INFO_CLASS;
4652         }
4653
4654         can_mod_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_add_users );
4655
4656         /******** BEGIN SeAddUsers BLOCK *********/
4657
4658         if ( can_mod_accounts )
4659                 become_root();
4660           
4661         ret = pdb_update_group_mapping_entry(&map);
4662
4663         if ( can_mod_accounts )
4664                 unbecome_root();
4665
4666         /******** End SeAddUsers BLOCK *********/
4667
4668         if (NT_STATUS_IS_OK(ret)) {
4669                 force_flush_samr_cache(disp_info);
4670         }
4671
4672         return ret;
4673 }
4674
4675 /*********************************************************************
4676  _samr_set_aliasinfo
4677  
4678  update an alias's comment.
4679 *********************************************************************/
4680
4681 NTSTATUS _samr_set_aliasinfo(pipes_struct *p, SAMR_Q_SET_ALIASINFO *q_u, SAMR_R_SET_ALIASINFO *r_u)
4682 {
4683         DOM_SID group_sid;
4684         struct acct_info info;
4685         ALIAS_INFO_CTR *ctr;
4686         uint32 acc_granted;
4687         BOOL ret;
4688         BOOL can_mod_accounts;
4689         DISP_INFO *disp_info = NULL;
4690
4691         if (!get_lsa_policy_samr_sid(p, &q_u->alias_pol, &group_sid, &acc_granted, &disp_info))
4692                 return NT_STATUS_INVALID_HANDLE;
4693         
4694         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_ALIAS_SET_INFO, "_samr_set_aliasinfo"))) {
4695                 return r_u->status;
4696         }
4697                 
4698         ctr=&q_u->ctr;
4699
4700         /* get the current group information */
4701
4702         become_root();
4703         ret = pdb_get_aliasinfo( &group_sid, &info );
4704         unbecome_root();
4705
4706         if ( !ret ) {
4707                 return NT_STATUS_NO_SUCH_ALIAS;
4708         }
4709
4710         switch (ctr->level) {
4711                 case 2:
4712                 {
4713                         fstring group_name, acct_name;
4714                         NTSTATUS status;
4715
4716                         /* We currently do not support renaming groups in the
4717                            the BUILTIN domain.  Refer to util_builtin.c to understand 
4718                            why.  The eventually needs to be fixed to be like Windows
4719                            where you can rename builtin groups, just not delete them */
4720
4721                         if ( sid_check_is_in_builtin( &group_sid ) ) {
4722                                 return NT_STATUS_SPECIAL_ACCOUNT;
4723                         }
4724
4725                         /* There has to be a valid name (and it has to be different) */
4726
4727                         if ( !ctr->alias.info2.name.string ) 
4728                                 return NT_STATUS_INVALID_PARAMETER;
4729
4730                         unistr2_to_ascii( acct_name, ctr->alias.info2.name.string, 
4731                                 sizeof(acct_name)-1 );
4732
4733                         /* If the name is the same just reply "ok".  Yes this
4734                            doesn't allow you to change the case of a group name. */
4735
4736                         if ( strequal( acct_name, info.acct_name ) )
4737                                 return NT_STATUS_OK;
4738
4739                         fstrcpy( info.acct_name, acct_name );
4740
4741                         /* make sure the name doesn't already exist as a user 
4742                            or local group */
4743
4744                         fstr_sprintf( group_name, "%s\\%s", global_myname(), info.acct_name );
4745                         status = can_create( p->mem_ctx, group_name );
4746                         if ( !NT_STATUS_IS_OK( status ) ) 
4747                                 return status;
4748                         break;
4749                 }
4750                 case 3:
4751                         if ( ctr->alias.info3.description.string ) {
4752                                 unistr2_to_ascii( info.acct_desc, 
4753                                         ctr->alias.info3.description.string, 
4754                                         sizeof(info.acct_desc)-1 );
4755                         }
4756                         else
4757                                 fstrcpy( info.acct_desc, "" );
4758                         break;
4759                 default:
4760                         return NT_STATUS_INVALID_INFO_CLASS;
4761         }
4762
4763         can_mod_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_add_users );
4764
4765         /******** BEGIN SeAddUsers BLOCK *********/
4766
4767         if ( can_mod_accounts )
4768                 become_root();
4769
4770         ret = pdb_set_aliasinfo( &group_sid, &info );
4771
4772         if ( can_mod_accounts )
4773                 unbecome_root();
4774
4775         /******** End SeAddUsers BLOCK *********/
4776
4777         if (ret) {
4778                 force_flush_samr_cache(disp_info);
4779         }
4780
4781         return ret ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4782 }
4783
4784 /*********************************************************************
4785  _samr_get_dom_pwinfo
4786 *********************************************************************/
4787
4788 NTSTATUS _samr_get_dom_pwinfo(pipes_struct *p, SAMR_Q_GET_DOM_PWINFO *q_u, SAMR_R_GET_DOM_PWINFO *r_u)
4789 {
4790         /* Perform access check.  Since this rpc does not require a
4791            policy handle it will not be caught by the access checks on
4792            SAMR_CONNECT or SAMR_CONNECT_ANON. */
4793
4794         if (!pipe_access_check(p)) {
4795                 DEBUG(3, ("access denied to samr_get_dom_pwinfo\n"));
4796                 r_u->status = NT_STATUS_ACCESS_DENIED;
4797                 return r_u->status;
4798         }
4799
4800         /* Actually, returning zeros here works quite well :-). */
4801
4802         return NT_STATUS_OK;
4803 }
4804
4805 /*********************************************************************
4806  _samr_open_group
4807 *********************************************************************/
4808
4809 NTSTATUS _samr_open_group(pipes_struct *p, SAMR_Q_OPEN_GROUP *q_u, SAMR_R_OPEN_GROUP *r_u)
4810 {
4811         DOM_SID sid;
4812         DOM_SID info_sid;
4813         GROUP_MAP map;
4814         struct samr_info *info;
4815         SEC_DESC         *psd = NULL;
4816         uint32            acc_granted;
4817         uint32            des_access = q_u->access_mask;
4818         size_t            sd_size;
4819         NTSTATUS          status;
4820         fstring sid_string;
4821         BOOL ret;
4822         SE_PRIV se_rights;
4823
4824         if (!get_lsa_policy_samr_sid(p, &q_u->domain_pol, &sid, &acc_granted, NULL)) 
4825                 return NT_STATUS_INVALID_HANDLE;
4826         
4827         status = access_check_samr_function(acc_granted, 
4828                 SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_open_group");
4829                 
4830         if ( !NT_STATUS_IS_OK(status) )
4831                 return status;
4832                 
4833         /*check if access can be granted as requested by client. */
4834         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &grp_generic_mapping, NULL, 0);
4835         se_map_generic(&des_access,&grp_generic_mapping);
4836
4837         se_priv_copy( &se_rights, &se_add_users );
4838
4839         status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
4840                 &se_rights, GENERIC_RIGHTS_GROUP_WRITE, des_access, 
4841                 &acc_granted, "_samr_open_group");
4842                 
4843         if ( !NT_STATUS_IS_OK(status) ) 
4844                 return status;
4845
4846         /* this should not be hard-coded like this */
4847         
4848         if (!sid_equal(&sid, get_global_sam_sid()))
4849                 return NT_STATUS_ACCESS_DENIED;
4850
4851         sid_copy(&info_sid, get_global_sam_sid());
4852         sid_append_rid(&info_sid, q_u->rid_group);
4853         sid_to_string(sid_string, &info_sid);
4854
4855         if ((info = get_samr_info_by_sid(&info_sid)) == NULL)
4856                 return NT_STATUS_NO_MEMORY;
4857                 
4858         info->acc_granted = acc_granted;
4859
4860         DEBUG(10, ("_samr_open_group:Opening SID: %s\n", sid_string));
4861
4862         /* check if that group really exists */
4863         become_root();
4864         ret = get_domain_group_from_sid(info->sid, &map);
4865         unbecome_root();
4866         if (!ret)
4867                 return NT_STATUS_NO_SUCH_GROUP;
4868
4869         /* get a (unique) handle.  open a policy on it. */
4870         if (!create_policy_hnd(p, &r_u->pol, free_samr_info, (void *)info))
4871                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4872
4873         return NT_STATUS_OK;
4874 }
4875
4876 /*********************************************************************
4877  _samr_remove_sid_foreign_domain
4878 *********************************************************************/
4879
4880 NTSTATUS _samr_remove_sid_foreign_domain(pipes_struct *p, 
4881                                           SAMR_Q_REMOVE_SID_FOREIGN_DOMAIN *q_u, 
4882                                           SAMR_R_REMOVE_SID_FOREIGN_DOMAIN *r_u)
4883 {
4884         DOM_SID                 delete_sid, domain_sid;
4885         uint32                  acc_granted;
4886         NTSTATUS                result;
4887         DISP_INFO *disp_info = NULL;
4888
4889         sid_copy( &delete_sid, &q_u->sid.sid );
4890         
4891         DEBUG(5,("_samr_remove_sid_foreign_domain: removing SID [%s]\n",
4892                 sid_string_static(&delete_sid)));
4893                 
4894         /* Find the policy handle. Open a policy on it. */
4895         
4896         if (!get_lsa_policy_samr_sid(p, &q_u->dom_pol, &domain_sid,
4897                                      &acc_granted, &disp_info)) 
4898                 return NT_STATUS_INVALID_HANDLE;
4899         
4900         result = access_check_samr_function(acc_granted, STD_RIGHT_DELETE_ACCESS, 
4901                 "_samr_remove_sid_foreign_domain");
4902                 
4903         if (!NT_STATUS_IS_OK(result)) 
4904                 return result;
4905                         
4906         DEBUG(8, ("_samr_remove_sid_foreign_domain:sid is %s\n", 
4907                 sid_string_static(&domain_sid)));
4908
4909         /* we can only delete a user from a group since we don't have 
4910            nested groups anyways.  So in the latter case, just say OK */
4911
4912         /* TODO: The above comment nowadays is bogus. Since we have nested
4913          * groups now, and aliases members are never reported out of the unix
4914          * group membership, the "just say OK" makes this call a no-op. For
4915          * us. This needs fixing however. */
4916
4917         /* I've only ever seen this in the wild when deleting a user from
4918          * usrmgr.exe. domain_sid is the builtin domain, and the sid to delete
4919          * is the user about to be deleted. I very much suspect this is the
4920          * only application of this call. To verify this, let people report
4921          * other cases. */
4922
4923         if (!sid_check_is_builtin(&domain_sid)) {
4924                 DEBUG(1,("_samr_remove_sid_foreign_domain: domain_sid = %s, "
4925                          "global_sam_sid() = %s\n",
4926                          sid_string_static(&domain_sid),
4927                          sid_string_static(get_global_sam_sid())));
4928                 DEBUGADD(1,("please report to samba-technical@samba.org!\n"));
4929                 return NT_STATUS_OK;
4930         }
4931
4932         force_flush_samr_cache(disp_info);
4933
4934         result = NT_STATUS_OK;
4935
4936         return result;
4937 }
4938
4939 /*******************************************************************
4940  _samr_query_domain_info2
4941  ********************************************************************/
4942
4943 NTSTATUS _samr_query_domain_info2(pipes_struct *p,
4944                                   SAMR_Q_QUERY_DOMAIN_INFO2 *q_u,
4945                                   SAMR_R_QUERY_DOMAIN_INFO2 *r_u)
4946 {
4947         SAMR_Q_QUERY_DOMAIN_INFO q;
4948         SAMR_R_QUERY_DOMAIN_INFO r;
4949
4950         ZERO_STRUCT(q);
4951         ZERO_STRUCT(r);
4952
4953         DEBUG(5,("_samr_query_domain_info2: %d\n", __LINE__));
4954
4955         q.domain_pol = q_u->domain_pol;
4956         q.switch_value = q_u->switch_value;
4957
4958         r_u->status = _samr_query_domain_info(p, &q, &r);
4959
4960         r_u->ptr_0              = r.ptr_0;
4961         r_u->switch_value       = r.switch_value;
4962         r_u->ctr                = r.ctr;
4963
4964         return r_u->status;
4965 }
4966
4967 /*******************************************************************
4968  _samr_set_dom_info
4969  ********************************************************************/
4970
4971 NTSTATUS _samr_set_dom_info(pipes_struct *p, SAMR_Q_SET_DOMAIN_INFO *q_u, SAMR_R_SET_DOMAIN_INFO *r_u)
4972 {
4973         time_t u_expire, u_min_age;
4974         time_t u_logout;
4975         time_t u_lock_duration, u_reset_time;
4976
4977         r_u->status = NT_STATUS_OK;
4978
4979         DEBUG(5,("_samr_set_dom_info: %d\n", __LINE__));
4980
4981         /* find the policy handle.  open a policy on it. */
4982         if (!find_policy_by_hnd(p, &q_u->domain_pol, NULL))
4983                 return NT_STATUS_INVALID_HANDLE;
4984
4985         DEBUG(5,("_samr_set_dom_info: switch_value: %d\n", q_u->switch_value));
4986
4987         switch (q_u->switch_value) {
4988                 case 0x01:
4989                         u_expire=nt_time_to_unix_abs(&q_u->ctr->info.inf1.expire);
4990                         u_min_age=nt_time_to_unix_abs(&q_u->ctr->info.inf1.min_passwordage);
4991                         
4992                         pdb_set_account_policy(AP_MIN_PASSWORD_LEN, (uint32)q_u->ctr->info.inf1.min_length_password);
4993                         pdb_set_account_policy(AP_PASSWORD_HISTORY, (uint32)q_u->ctr->info.inf1.password_history);
4994                         pdb_set_account_policy(AP_USER_MUST_LOGON_TO_CHG_PASS, (uint32)q_u->ctr->info.inf1.password_properties);
4995                         pdb_set_account_policy(AP_MAX_PASSWORD_AGE, (int)u_expire);
4996                         pdb_set_account_policy(AP_MIN_PASSWORD_AGE, (int)u_min_age);
4997                         break;
4998                 case 0x02:
4999                         break;
5000                 case 0x03:
5001                         u_logout=nt_time_to_unix_abs(&q_u->ctr->info.inf3.logout);
5002                         pdb_set_account_policy(AP_TIME_TO_LOGOUT, (int)u_logout);
5003                         break;
5004                 case 0x05:
5005                         break;
5006                 case 0x06:
5007                         break;
5008                 case 0x07:
5009                         break;
5010                 case 0x0c:
5011                         u_lock_duration=nt_time_to_unix_abs(&q_u->ctr->info.inf12.duration);
5012                         if (u_lock_duration != -1)
5013                                 u_lock_duration /= 60;
5014
5015                         u_reset_time=nt_time_to_unix_abs(&q_u->ctr->info.inf12.reset_count)/60;
5016                         
5017                         pdb_set_account_policy(AP_LOCK_ACCOUNT_DURATION, (int)u_lock_duration);
5018                         pdb_set_account_policy(AP_RESET_COUNT_TIME, (int)u_reset_time);
5019                         pdb_set_account_policy(AP_BAD_ATTEMPT_LOCKOUT, (uint32)q_u->ctr->info.inf12.bad_attempt_lockout);
5020                         break;
5021                 default:
5022                         return NT_STATUS_INVALID_INFO_CLASS;
5023         }
5024
5025         init_samr_r_set_domain_info(r_u, NT_STATUS_OK);
5026
5027         DEBUG(5,("_samr_set_dom_info: %d\n", __LINE__));
5028
5029         return r_u->status;
5030 }