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