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