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