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