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