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