3cc8f01d2cc4f8f7550ec07699faefeb61930810
[amitay/samba.git] / source3 / rpc_server / srv_samr_nt.c
1 /*
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Copyright (C) Andrew Tridgell                   1992-1997,
5  *  Copyright (C) Luke Kenneth Casson Leighton      1996-1997,
6  *  Copyright (C) Paul Ashton                       1997,
7  *  Copyright (C) Marc Jacobsen                     1999,
8  *  Copyright (C) Jeremy Allison                    2001-2005,
9  *  Copyright (C) Jean Fran├žois Micouleau           1998-2001,
10  *  Copyright (C) Jim McDonough <jmcd@us.ibm.com>   2002,
11  *  Copyright (C) Gerald (Jerry) Carter             2003-2004,
12  *  Copyright (C) Simo Sorce                        2003.
13  *  Copyright (C) Volker Lendecke                   2005.
14  *
15  *  This program is free software; you can redistribute it and/or modify
16  *  it under the terms of the GNU General Public License as published by
17  *  the Free Software Foundation; either version 3 of the License, or
18  *  (at your option) any later version.
19  *
20  *  This program is distributed in the hope that it will be useful,
21  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  *  GNU General Public License for more details.
24  *
25  *  You should have received a copy of the GNU General Public License
26  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
27  */
28
29 /*
30  * This is the implementation of the SAMR code.
31  */
32
33 #include "includes.h"
34
35 #undef DBGC_CLASS
36 #define DBGC_CLASS DBGC_RPC_SRV
37
38 #define SAMR_USR_RIGHTS_WRITE_PW \
39                 ( READ_CONTROL_ACCESS           | \
40                   SA_RIGHT_USER_CHANGE_PASSWORD | \
41                   SA_RIGHT_USER_SET_LOC_COM )
42 #define SAMR_USR_RIGHTS_CANT_WRITE_PW \
43                 ( READ_CONTROL_ACCESS | SA_RIGHT_USER_SET_LOC_COM )
44
45 #define DISP_INFO_CACHE_TIMEOUT 10
46
47 typedef struct disp_info {
48         DOM_SID sid; /* identify which domain this is. */
49         bool builtin_domain; /* Quick flag to check if this is the builtin domain. */
50         struct pdb_search *users; /* querydispinfo 1 and 4 */
51         struct pdb_search *machines; /* querydispinfo 2 */
52         struct pdb_search *groups; /* querydispinfo 3 and 5, enumgroups */
53         struct pdb_search *aliases; /* enumaliases */
54
55         uint16 enum_acb_mask;
56         struct pdb_search *enum_users; /* enumusers with a mask */
57
58         struct timed_event *cache_timeout_event; /* cache idle timeout
59                                                   * handler. */
60 } DISP_INFO;
61
62 /* We keep a static list of these by SID as modern clients close down
63    all resources between each request in a complete enumeration. */
64
65 struct samr_info {
66         /* for use by the \PIPE\samr policy */
67         DOM_SID sid;
68         bool builtin_domain; /* Quick flag to check if this is the builtin domain. */
69         uint32 status; /* some sort of flag.  best to record it.  comes from opnum 0x39 */
70         uint32 acc_granted;
71         DISP_INFO *disp_info;
72         TALLOC_CTX *mem_ctx;
73 };
74
75 static const struct generic_mapping sam_generic_mapping = {
76         GENERIC_RIGHTS_SAM_READ,
77         GENERIC_RIGHTS_SAM_WRITE,
78         GENERIC_RIGHTS_SAM_EXECUTE,
79         GENERIC_RIGHTS_SAM_ALL_ACCESS};
80 static const struct generic_mapping dom_generic_mapping = {
81         GENERIC_RIGHTS_DOMAIN_READ,
82         GENERIC_RIGHTS_DOMAIN_WRITE,
83         GENERIC_RIGHTS_DOMAIN_EXECUTE,
84         GENERIC_RIGHTS_DOMAIN_ALL_ACCESS};
85 static const struct generic_mapping usr_generic_mapping = {
86         GENERIC_RIGHTS_USER_READ,
87         GENERIC_RIGHTS_USER_WRITE,
88         GENERIC_RIGHTS_USER_EXECUTE,
89         GENERIC_RIGHTS_USER_ALL_ACCESS};
90 static const struct generic_mapping usr_nopwchange_generic_mapping = {
91         GENERIC_RIGHTS_USER_READ,
92         GENERIC_RIGHTS_USER_WRITE,
93         GENERIC_RIGHTS_USER_EXECUTE & ~SA_RIGHT_USER_CHANGE_PASSWORD,
94         GENERIC_RIGHTS_USER_ALL_ACCESS};
95 static const struct generic_mapping grp_generic_mapping = {
96         GENERIC_RIGHTS_GROUP_READ,
97         GENERIC_RIGHTS_GROUP_WRITE,
98         GENERIC_RIGHTS_GROUP_EXECUTE,
99         GENERIC_RIGHTS_GROUP_ALL_ACCESS};
100 static const struct generic_mapping ali_generic_mapping = {
101         GENERIC_RIGHTS_ALIAS_READ,
102         GENERIC_RIGHTS_ALIAS_WRITE,
103         GENERIC_RIGHTS_ALIAS_EXECUTE,
104         GENERIC_RIGHTS_ALIAS_ALL_ACCESS};
105
106 /*******************************************************************
107 *******************************************************************/
108
109 static NTSTATUS make_samr_object_sd( TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd_size,
110                                      const struct generic_mapping *map,
111                                      DOM_SID *sid, uint32 sid_access )
112 {
113         DOM_SID domadmin_sid;
114         SEC_ACE ace[5];         /* at most 5 entries */
115         SEC_ACCESS mask;
116         size_t i = 0;
117
118         SEC_ACL *psa = NULL;
119
120         /* basic access for Everyone */
121
122         init_sec_access(&mask, map->generic_execute | map->generic_read );
123         init_sec_ace(&ace[i++], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
124
125         /* add Full Access 'BUILTIN\Administrators' and 'BUILTIN\Account Operators */
126
127         init_sec_access(&mask, map->generic_all);
128         
129         init_sec_ace(&ace[i++], &global_sid_Builtin_Administrators, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
130         init_sec_ace(&ace[i++], &global_sid_Builtin_Account_Operators, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
131
132         /* Add Full Access for Domain Admins if we are a DC */
133         
134         if ( IS_DC ) {
135                 sid_copy( &domadmin_sid, get_global_sam_sid() );
136                 sid_append_rid( &domadmin_sid, DOMAIN_GROUP_RID_ADMINS );
137                 init_sec_ace(&ace[i++], &domadmin_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
138         }
139
140         /* if we have a sid, give it some special access */
141
142         if ( sid ) {
143                 init_sec_access( &mask, sid_access );
144                 init_sec_ace(&ace[i++], sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
145         }
146
147         /* create the security descriptor */
148
149         if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, i, ace)) == NULL)
150                 return NT_STATUS_NO_MEMORY;
151
152         if ((*psd = make_sec_desc(ctx, SEC_DESC_REVISION, SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL, psa, sd_size)) == NULL)
153                 return NT_STATUS_NO_MEMORY;
154
155         return NT_STATUS_OK;
156 }
157
158 /*******************************************************************
159  Checks if access to an object should be granted, and returns that
160  level of access for further checks.
161 ********************************************************************/
162
163 static NTSTATUS access_check_samr_object( SEC_DESC *psd, NT_USER_TOKEN *token, 
164                                           SE_PRIV *rights, uint32 rights_mask,
165                                           uint32 des_access, uint32 *acc_granted, 
166                                           const char *debug )
167 {
168         NTSTATUS status = NT_STATUS_ACCESS_DENIED;
169         uint32 saved_mask = 0;
170
171         /* check privileges; certain SAM access bits should be overridden 
172            by privileges (mostly having to do with creating/modifying/deleting 
173            users and groups) */
174         
175         if ( rights && user_has_any_privilege( token, rights ) ) {
176         
177                 saved_mask = (des_access & rights_mask);
178                 des_access &= ~saved_mask;
179                 
180                 DEBUG(4,("access_check_samr_object: user rights access mask [0x%x]\n",
181                         rights_mask));
182         }
183                 
184         
185         /* check the security descriptor first */
186         
187         if ( se_access_check(psd, token, des_access, acc_granted, &status) )
188                 goto done;
189         
190         /* give root a free pass */
191         
192         if ( geteuid() == sec_initial_uid() ) {
193         
194                 DEBUG(4,("%s: ACCESS should be DENIED  (requested: %#010x)\n", debug, des_access));
195                 DEBUGADD(4,("but overritten by euid == sec_initial_uid()\n"));
196                 
197                 *acc_granted = des_access;
198                 
199                 status = NT_STATUS_OK;
200                 goto done;
201         }
202         
203         
204 done:
205         /* add in any bits saved during the privilege check (only 
206            matters is status is ok) */
207         
208         *acc_granted |= rights_mask;
209
210         DEBUG(4,("%s: access %s (requested: 0x%08x, granted: 0x%08x)\n", 
211                 debug, NT_STATUS_IS_OK(status) ? "GRANTED" : "DENIED", 
212                 des_access, *acc_granted));
213         
214         return status;
215 }
216
217 /*******************************************************************
218  Checks if access to a function can be granted
219 ********************************************************************/
220
221 static NTSTATUS access_check_samr_function(uint32 acc_granted, uint32 acc_required, const char *debug)
222 {
223         DEBUG(5,("%s: access check ((granted: %#010x;  required: %#010x)\n",  
224                 debug, acc_granted, acc_required));
225
226         /* check the security descriptor first */
227         
228         if ( (acc_granted&acc_required) == acc_required )
229                 return NT_STATUS_OK;
230                 
231         /* give root a free pass */
232
233         if (geteuid() == sec_initial_uid()) {
234         
235                 DEBUG(4,("%s: ACCESS should be DENIED (granted: %#010x;  required: %#010x)\n",
236                         debug, acc_granted, acc_required));
237                 DEBUGADD(4,("but overwritten by euid == 0\n"));
238                 
239                 return NT_STATUS_OK;
240         }
241         
242         DEBUG(2,("%s: ACCESS DENIED (granted: %#010x;  required: %#010x)\n", 
243                 debug, acc_granted, acc_required));
244                 
245         return NT_STATUS_ACCESS_DENIED;
246 }
247
248 /*******************************************************************
249  Fetch or create a dispinfo struct.
250 ********************************************************************/
251
252 static DISP_INFO *get_samr_dispinfo_by_sid(DOM_SID *psid)
253 {
254         /*
255          * We do a static cache for DISP_INFO's here. Explanation can be found
256          * in Jeremy's checkin message to r11793:
257          *
258          * Fix the SAMR cache so it works across completely insane
259          * client behaviour (ie.:
260          * open pipe/open SAMR handle/enumerate 0 - 1024
261          * close SAMR handle, close pipe.
262          * open pipe/open SAMR handle/enumerate 1024 - 2048...
263          * close SAMR handle, close pipe.
264          * And on ad-nausium. Amazing.... probably object-oriented
265          * client side programming in action yet again.
266          * This change should *massively* improve performance when
267          * enumerating users from an LDAP database.
268          * Jeremy.
269          *
270          * "Our" and the builtin domain are the only ones where we ever
271          * enumerate stuff, so just cache 2 entries.
272          */
273
274         static struct disp_info builtin_dispinfo;
275         static struct disp_info domain_dispinfo;
276
277         /* There are two cases to consider here:
278            1) The SID is a domain SID and we look for an equality match, or
279            2) This is an account SID and so we return the DISP_INFO* for our 
280               domain */
281
282         if (psid == NULL) {
283                 return NULL;
284         }
285
286         if (sid_check_is_builtin(psid) || sid_check_is_in_builtin(psid)) {
287                 /*
288                  * Necessary only once, but it does not really hurt.
289                  */
290                 sid_copy(&builtin_dispinfo.sid, &global_sid_Builtin);
291
292                 return &builtin_dispinfo;
293         }
294                 
295         if (sid_check_is_domain(psid) || sid_check_is_in_our_domain(psid)) {
296                 /*
297                  * Necessary only once, but it does not really hurt.
298                  */
299                 sid_copy(&domain_dispinfo.sid, get_global_sam_sid());
300
301                 return &domain_dispinfo;
302         }
303
304         return NULL;
305 }
306
307 /*******************************************************************
308  Create a samr_info struct.
309 ********************************************************************/
310
311 static struct samr_info *get_samr_info_by_sid(DOM_SID *psid)
312 {
313         struct samr_info *info;
314         fstring sid_str;
315         TALLOC_CTX *mem_ctx;
316         
317         if (psid) {
318                 sid_to_string(sid_str, psid);
319         } else {
320                 fstrcpy(sid_str,"(NULL)");
321         }
322
323         mem_ctx = talloc_init("samr_info for domain sid %s", sid_str);
324
325         if ((info = TALLOC_ZERO_P(mem_ctx, struct samr_info)) == NULL)
326                 return NULL;
327
328         DEBUG(10,("get_samr_info_by_sid: created new info for sid %s\n", sid_str));
329         if (psid) {
330                 sid_copy( &info->sid, psid);
331                 info->builtin_domain = sid_check_is_builtin(psid);
332         } else {
333                 DEBUG(10,("get_samr_info_by_sid: created new info for NULL sid.\n"));
334                 info->builtin_domain = False;
335         }
336         info->mem_ctx = mem_ctx;
337
338         info->disp_info = get_samr_dispinfo_by_sid(psid);
339
340         return info;
341 }
342
343 /*******************************************************************
344  Function to free the per SID data.
345  ********************************************************************/
346
347 static void free_samr_cache(DISP_INFO *disp_info)
348 {
349         DEBUG(10, ("free_samr_cache: deleting cache for SID %s\n",
350                    sid_string_static(&disp_info->sid)));
351
352         /* We need to become root here because the paged search might have to
353          * tell the LDAP server we're not interested in the rest anymore. */
354
355         become_root();
356
357         if (disp_info->users) {
358                 DEBUG(10,("free_samr_cache: deleting users cache\n"));
359                 pdb_search_destroy(disp_info->users);
360                 disp_info->users = NULL;
361         }
362         if (disp_info->machines) {
363                 DEBUG(10,("free_samr_cache: deleting machines cache\n"));
364                 pdb_search_destroy(disp_info->machines);
365                 disp_info->machines = NULL;
366         }
367         if (disp_info->groups) {
368                 DEBUG(10,("free_samr_cache: deleting groups cache\n"));
369                 pdb_search_destroy(disp_info->groups);
370                 disp_info->groups = NULL;
371         }
372         if (disp_info->aliases) {
373                 DEBUG(10,("free_samr_cache: deleting aliases cache\n"));
374                 pdb_search_destroy(disp_info->aliases);
375                 disp_info->aliases = NULL;
376         }
377         if (disp_info->enum_users) {
378                 DEBUG(10,("free_samr_cache: deleting enum_users cache\n"));
379                 pdb_search_destroy(disp_info->enum_users);
380                 disp_info->enum_users = NULL;
381         }
382         disp_info->enum_acb_mask = 0;
383
384         unbecome_root();
385 }
386
387 /*******************************************************************
388  Function to free the per handle data.
389  ********************************************************************/
390
391 static void free_samr_info(void *ptr)
392 {
393         struct samr_info *info=(struct samr_info *) ptr;
394
395         /* Only free the dispinfo cache if no one bothered to set up
396            a timeout. */
397
398         if (info->disp_info && info->disp_info->cache_timeout_event == NULL) {
399                 free_samr_cache(info->disp_info);
400         }
401
402         talloc_destroy(info->mem_ctx);
403 }
404
405 /*******************************************************************
406  Idle event handler. Throw away the disp info cache.
407  ********************************************************************/
408
409 static void disp_info_cache_idle_timeout_handler(struct event_context *ev_ctx,
410                                                  struct timed_event *te,
411                                                  const struct timeval *now,
412                                                  void *private_data)
413 {
414         DISP_INFO *disp_info = (DISP_INFO *)private_data;
415
416         TALLOC_FREE(disp_info->cache_timeout_event);
417
418         DEBUG(10, ("disp_info_cache_idle_timeout_handler: caching timed "
419                    "out\n"));
420         free_samr_cache(disp_info);
421 }
422
423 /*******************************************************************
424  Setup cache removal idle event handler.
425  ********************************************************************/
426
427 static void set_disp_info_cache_timeout(DISP_INFO *disp_info, time_t secs_fromnow)
428 {
429         /* Remove any pending timeout and update. */
430
431         TALLOC_FREE(disp_info->cache_timeout_event);
432
433         DEBUG(10,("set_disp_info_cache_timeout: caching enumeration for "
434                   "SID %s for %u seconds\n",
435                   sid_string_static(&disp_info->sid),
436                   (unsigned int)secs_fromnow ));
437
438         disp_info->cache_timeout_event = event_add_timed(
439                 smbd_event_context(), NULL,
440                 timeval_current_ofs(secs_fromnow, 0),
441                 "disp_info_cache_idle_timeout_handler",
442                 disp_info_cache_idle_timeout_handler, (void *)disp_info);
443 }
444
445 /*******************************************************************
446  Force flush any cache. We do this on any samr_set_xxx call.
447  We must also remove the timeout handler.
448  ********************************************************************/
449
450 static void force_flush_samr_cache(DISP_INFO *disp_info)
451 {
452         if ((disp_info == NULL) || (disp_info->cache_timeout_event == NULL)) {
453                 return;
454         }
455
456         DEBUG(10,("force_flush_samr_cache: clearing idle event\n"));
457         TALLOC_FREE(disp_info->cache_timeout_event);
458         free_samr_cache(disp_info);
459 }
460
461 /*******************************************************************
462  Ensure password info is never given out. Paranioa... JRA.
463  ********************************************************************/
464
465 static void samr_clear_sam_passwd(struct samu *sam_pass)
466 {
467         
468         if (!sam_pass)
469                 return;
470
471         /* These now zero out the old password */
472
473         pdb_set_lanman_passwd(sam_pass, NULL, PDB_DEFAULT);
474         pdb_set_nt_passwd(sam_pass, NULL, PDB_DEFAULT);
475 }
476
477 static uint32 count_sam_users(struct disp_info *info, uint32 acct_flags)
478 {
479         struct samr_displayentry *entry;
480
481         if (info->builtin_domain) {
482                 /* No users in builtin. */
483                 return 0;
484         }
485
486         if (info->users == NULL) {
487                 info->users = pdb_search_users(acct_flags);
488                 if (info->users == NULL) {
489                         return 0;
490                 }
491         }
492         /* Fetch the last possible entry, thus trigger an enumeration */
493         pdb_search_entries(info->users, 0xffffffff, 1, &entry);
494
495         /* Ensure we cache this enumeration. */
496         set_disp_info_cache_timeout(info, DISP_INFO_CACHE_TIMEOUT);
497
498         return info->users->num_entries;
499 }
500
501 static uint32 count_sam_groups(struct disp_info *info)
502 {
503         struct samr_displayentry *entry;
504
505         if (info->builtin_domain) {
506                 /* No groups in builtin. */
507                 return 0;
508         }
509
510         if (info->groups == NULL) {
511                 info->groups = pdb_search_groups();
512                 if (info->groups == NULL) {
513                         return 0;
514                 }
515         }
516         /* Fetch the last possible entry, thus trigger an enumeration */
517         pdb_search_entries(info->groups, 0xffffffff, 1, &entry);
518
519         /* Ensure we cache this enumeration. */
520         set_disp_info_cache_timeout(info, DISP_INFO_CACHE_TIMEOUT);
521
522         return info->groups->num_entries;
523 }
524
525 static uint32 count_sam_aliases(struct disp_info *info)
526 {
527         struct samr_displayentry *entry;
528
529         if (info->aliases == NULL) {
530                 info->aliases = pdb_search_aliases(&info->sid);
531                 if (info->aliases == NULL) {
532                         return 0;
533                 }
534         }
535         /* Fetch the last possible entry, thus trigger an enumeration */
536         pdb_search_entries(info->aliases, 0xffffffff, 1, &entry);
537
538         /* Ensure we cache this enumeration. */
539         set_disp_info_cache_timeout(info, DISP_INFO_CACHE_TIMEOUT);
540
541         return info->aliases->num_entries;
542 }
543
544 /*******************************************************************
545  _samr_close_hnd
546  ********************************************************************/
547
548 NTSTATUS _samr_close_hnd(pipes_struct *p, SAMR_Q_CLOSE_HND *q_u, SAMR_R_CLOSE_HND *r_u)
549 {
550         r_u->status = NT_STATUS_OK;
551
552         /* close the policy handle */
553         if (!close_policy_hnd(p, &q_u->pol))
554                 return NT_STATUS_OBJECT_NAME_INVALID;
555
556         DEBUG(5,("samr_reply_close_hnd: %d\n", __LINE__));
557
558         return r_u->status;
559 }
560
561 /*******************************************************************
562  samr_reply_open_domain
563  ********************************************************************/
564
565 NTSTATUS _samr_open_domain(pipes_struct *p, SAMR_Q_OPEN_DOMAIN *q_u, SAMR_R_OPEN_DOMAIN *r_u)
566 {
567         struct    samr_info *info;
568         SEC_DESC *psd = NULL;
569         uint32    acc_granted;
570         uint32    des_access = q_u->flags;
571         NTSTATUS  status;
572         size_t    sd_size;
573         SE_PRIV se_rights;
574
575         r_u->status = NT_STATUS_OK;
576
577         /* find the connection policy handle. */
578         
579         if ( !find_policy_by_hnd(p, &q_u->pol, (void**)(void *)&info) )
580                 return NT_STATUS_INVALID_HANDLE;
581
582         status = access_check_samr_function( info->acc_granted, 
583                 SA_RIGHT_SAM_OPEN_DOMAIN, "_samr_open_domain" );
584                 
585         if ( !NT_STATUS_IS_OK(status) )
586                 return status;
587
588         /*check if access can be granted as requested by client. */
589         
590         make_samr_object_sd( p->mem_ctx, &psd, &sd_size, &dom_generic_mapping, NULL, 0 );
591         se_map_generic( &des_access, &dom_generic_mapping );
592         
593         se_priv_copy( &se_rights, &se_machine_account );
594         se_priv_add( &se_rights, &se_add_users );
595
596         status = access_check_samr_object( psd, p->pipe_user.nt_user_token, 
597                 &se_rights, GENERIC_RIGHTS_DOMAIN_WRITE, des_access, 
598                 &acc_granted, "_samr_open_domain" );
599                 
600         if ( !NT_STATUS_IS_OK(status) )
601                 return status;
602
603         if (!sid_check_is_domain(&q_u->dom_sid.sid) &&
604             !sid_check_is_builtin(&q_u->dom_sid.sid)) {
605                 return NT_STATUS_NO_SUCH_DOMAIN;
606         }
607
608         /* associate the domain SID with the (unique) handle. */
609         if ((info = get_samr_info_by_sid(&q_u->dom_sid.sid))==NULL)
610                 return NT_STATUS_NO_MEMORY;
611         info->acc_granted = acc_granted;
612
613         /* get a (unique) handle.  open a policy on it. */
614         if (!create_policy_hnd(p, &r_u->domain_pol, free_samr_info, (void *)info))
615                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
616
617         DEBUG(5,("samr_open_domain: %d\n", __LINE__));
618
619         return r_u->status;
620 }
621
622 /*******************************************************************
623  _samr_get_usrdom_pwinfo
624  ********************************************************************/
625
626 NTSTATUS _samr_get_usrdom_pwinfo(pipes_struct *p, SAMR_Q_GET_USRDOM_PWINFO *q_u, SAMR_R_GET_USRDOM_PWINFO *r_u)
627 {
628         struct samr_info *info = NULL;
629
630         r_u->status = NT_STATUS_OK;
631
632         /* find the policy handle.  open a policy on it. */
633         if (!find_policy_by_hnd(p, &q_u->user_pol, (void **)(void *)&info))
634                 return NT_STATUS_INVALID_HANDLE;
635
636         if (!sid_check_is_in_our_domain(&info->sid))
637                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
638
639         init_samr_r_get_usrdom_pwinfo(r_u, NT_STATUS_OK);
640
641         DEBUG(5,("_samr_get_usrdom_pwinfo: %d\n", __LINE__));
642
643         /* 
644          * NT sometimes return NT_STATUS_ACCESS_DENIED
645          * I don't know yet why.
646          */
647
648         return r_u->status;
649 }
650
651 /*******************************************************************
652 ********************************************************************/
653
654 static bool get_lsa_policy_samr_sid( pipes_struct *p, POLICY_HND *pol, 
655                                         DOM_SID *sid, uint32 *acc_granted,
656                                         DISP_INFO **ppdisp_info)
657 {
658         struct samr_info *info = NULL;
659
660         /* find the policy handle.  open a policy on it. */
661         if (!find_policy_by_hnd(p, pol, (void **)(void *)&info))
662                 return False;
663
664         if (!info)
665                 return False;
666
667         *sid = info->sid;
668         *acc_granted = info->acc_granted;
669         if (ppdisp_info) {
670                 *ppdisp_info = info->disp_info;
671         }
672
673         return True;
674 }
675
676 /*******************************************************************
677  _samr_set_sec_obj
678  ********************************************************************/
679
680 NTSTATUS _samr_set_sec_obj(pipes_struct *p, SAMR_Q_SET_SEC_OBJ *q_u, SAMR_R_SET_SEC_OBJ *r_u)
681 {
682         DOM_SID pol_sid;
683         uint32 acc_granted, i;
684         SEC_ACL *dacl;
685         bool ret;
686         struct samu *sampass=NULL;
687         NTSTATUS status;
688
689         r_u->status = NT_STATUS_OK;
690
691         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &pol_sid, &acc_granted, NULL))
692                 return NT_STATUS_INVALID_HANDLE;
693
694         if (!(sampass = samu_new( p->mem_ctx))) {
695                 DEBUG(0,("No memory!\n"));
696                 return NT_STATUS_NO_MEMORY;
697         }
698
699         /* get the user record */
700         become_root();
701         ret = pdb_getsampwsid(sampass, &pol_sid);
702         unbecome_root();
703
704         if (!ret) {
705                 DEBUG(4, ("User %s not found\n", sid_string_static(&pol_sid)));
706                 TALLOC_FREE(sampass);
707                 return NT_STATUS_INVALID_HANDLE;
708         }
709
710         dacl = q_u->buf->sd->dacl;
711         for (i=0; i < dacl->num_aces; i++) {
712                 if (sid_equal(&pol_sid, &dacl->aces[i].trustee)) {
713                         ret = pdb_set_pass_can_change(sampass, 
714                                 (dacl->aces[i].access_mask & 
715                                  SA_RIGHT_USER_CHANGE_PASSWORD) ? 
716                                                       True: False);
717                         break;
718                 }
719         }
720
721         if (!ret) {
722                 TALLOC_FREE(sampass);
723                 return NT_STATUS_ACCESS_DENIED;
724         }
725
726         status = access_check_samr_function(acc_granted, SA_RIGHT_USER_SET_ATTRIBUTES, "_samr_set_sec_obj");
727         if (NT_STATUS_IS_OK(status)) {
728                 become_root();
729                 status = pdb_update_sam_account(sampass);
730                 unbecome_root();
731         }
732
733         TALLOC_FREE(sampass);
734
735         return status;
736 }
737
738 /*******************************************************************
739   build correct perms based on policies and password times for _samr_query_sec_obj
740 *******************************************************************/
741 static bool check_change_pw_access(TALLOC_CTX *mem_ctx, DOM_SID *user_sid)
742 {
743         struct samu *sampass=NULL;
744         bool ret;
745
746         if ( !(sampass = samu_new( mem_ctx )) ) {
747                 DEBUG(0,("No memory!\n"));
748                 return False;
749         }
750
751         become_root();
752         ret = pdb_getsampwsid(sampass, user_sid);
753         unbecome_root();
754
755         if (ret == False) {
756                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
757                 TALLOC_FREE(sampass);
758                 return False;
759         }
760
761         DEBUG(3,("User:[%s]\n",  pdb_get_username(sampass) ));
762
763         if (pdb_get_pass_can_change(sampass)) {
764                 TALLOC_FREE(sampass);
765                 return True;
766         }
767         TALLOC_FREE(sampass);
768         return False;
769 }
770
771
772 /*******************************************************************
773  _samr_query_sec_obj
774  ********************************************************************/
775
776 NTSTATUS _samr_query_sec_obj(pipes_struct *p, SAMR_Q_QUERY_SEC_OBJ *q_u, SAMR_R_QUERY_SEC_OBJ *r_u)
777 {
778         DOM_SID pol_sid;
779         fstring str_sid;
780         SEC_DESC * psd = NULL;
781         uint32 acc_granted;
782         size_t sd_size;
783
784         r_u->status = NT_STATUS_OK;
785
786         /* Get the SID. */
787         if (!get_lsa_policy_samr_sid(p, &q_u->user_pol, &pol_sid, &acc_granted, NULL))
788                 return NT_STATUS_INVALID_HANDLE;
789
790         DEBUG(10,("_samr_query_sec_obj: querying security on SID: %s\n", sid_to_string(str_sid, &pol_sid)));
791
792         /* Check what typ of SID is beeing queried (e.g Domain SID, User SID, Group SID) */
793
794         /* To query the security of the SAM it self an invalid SID with S-0-0 is passed to this function */
795         if (pol_sid.sid_rev_num == 0) {
796                 DEBUG(5,("_samr_query_sec_obj: querying security on SAM\n"));
797                 r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &sam_generic_mapping, NULL, 0);
798         } else if (sid_equal(&pol_sid,get_global_sam_sid())) { 
799                 /* check if it is our domain SID */
800                 DEBUG(5,("_samr_query_sec_obj: querying security on Domain with SID: %s\n", sid_to_string(str_sid, &pol_sid)));
801                 r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &dom_generic_mapping, NULL, 0);
802         } else if (sid_equal(&pol_sid,&global_sid_Builtin)) {
803                 /* check if it is the Builtin  Domain */
804                 /* TODO: Builtin probably needs a different SD with restricted write access*/
805                 DEBUG(5,("_samr_query_sec_obj: querying security on Builtin Domain with SID: %s\n", sid_to_string(str_sid, &pol_sid)));
806                 r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &dom_generic_mapping, NULL, 0);
807         } else if (sid_check_is_in_our_domain(&pol_sid) ||
808                  sid_check_is_in_builtin(&pol_sid)) {
809                 /* TODO: different SDs have to be generated for aliases groups and users.
810                          Currently all three get a default user SD  */
811                 DEBUG(10,("_samr_query_sec_obj: querying security on Object with SID: %s\n", sid_to_string(str_sid, &pol_sid)));
812                 if (check_change_pw_access(p->mem_ctx, &pol_sid)) {
813                         r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &usr_generic_mapping, 
814                                                           &pol_sid, SAMR_USR_RIGHTS_WRITE_PW);
815                 } else {
816                         r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &usr_nopwchange_generic_mapping, 
817                                                           &pol_sid, SAMR_USR_RIGHTS_CANT_WRITE_PW);
818                 }
819         } else {
820                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
821         }
822
823         if ((r_u->buf = make_sec_desc_buf(p->mem_ctx, sd_size, psd)) == NULL)
824                 return NT_STATUS_NO_MEMORY;
825
826         if (NT_STATUS_IS_OK(r_u->status))
827                 r_u->ptr = 1;
828
829         return r_u->status;
830 }
831
832 /*******************************************************************
833 makes a SAM_ENTRY / UNISTR2* structure from a user list.
834 ********************************************************************/
835
836 static NTSTATUS make_user_sam_entry_list(TALLOC_CTX *ctx, SAM_ENTRY **sam_pp,
837                                          UNISTR2 **uni_name_pp,
838                                          uint32 num_entries, uint32 start_idx,
839                                          struct samr_displayentry *entries)
840 {
841         uint32 i;
842         SAM_ENTRY *sam;
843         UNISTR2 *uni_name;
844         
845         *sam_pp = NULL;
846         *uni_name_pp = NULL;
847
848         if (num_entries == 0)
849                 return NT_STATUS_OK;
850
851         sam = TALLOC_ZERO_ARRAY(ctx, SAM_ENTRY, num_entries);
852
853         uni_name = TALLOC_ZERO_ARRAY(ctx, UNISTR2, num_entries);
854
855         if (sam == NULL || uni_name == NULL) {
856                 DEBUG(0, ("make_user_sam_entry_list: TALLOC_ZERO failed!\n"));
857                 return NT_STATUS_NO_MEMORY;
858         }
859
860         for (i = 0; i < num_entries; i++) {
861                 UNISTR2 uni_temp_name;
862                 /*
863                  * usrmgr expects a non-NULL terminated string with
864                  * trust relationships
865                  */
866                 if (entries[i].acct_flags & ACB_DOMTRUST) {
867                         init_unistr2(&uni_temp_name, entries[i].account_name,
868                                      UNI_FLAGS_NONE);
869                 } else {
870                         init_unistr2(&uni_temp_name, entries[i].account_name,
871                                      UNI_STR_TERMINATE);
872                 }
873
874                 init_sam_entry(&sam[i], &uni_temp_name, entries[i].rid);
875                 copy_unistr2(&uni_name[i], &uni_temp_name);
876         }
877
878         *sam_pp = sam;
879         *uni_name_pp = uni_name;
880         return NT_STATUS_OK;
881 }
882
883 /*******************************************************************
884  samr_reply_enum_dom_users
885  ********************************************************************/
886
887 NTSTATUS _samr_enum_dom_users(pipes_struct *p, SAMR_Q_ENUM_DOM_USERS *q_u, 
888                               SAMR_R_ENUM_DOM_USERS *r_u)
889 {
890         struct samr_info *info = NULL;
891         int num_account;
892         uint32 enum_context=q_u->start_idx;
893         enum remote_arch_types ra_type = get_remote_arch();
894         int max_sam_entries = (ra_type == RA_WIN95) ? MAX_SAM_ENTRIES_W95 : MAX_SAM_ENTRIES_W2K;
895         uint32 max_entries = max_sam_entries;
896         struct samr_displayentry *entries = NULL;
897         
898         r_u->status = NT_STATUS_OK;
899
900         /* find the policy handle.  open a policy on it. */
901         if (!find_policy_by_hnd(p, &q_u->pol, (void **)(void *)&info))
902                 return NT_STATUS_INVALID_HANDLE;
903
904         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(info->acc_granted, 
905                                         SA_RIGHT_DOMAIN_ENUM_ACCOUNTS, 
906                                         "_samr_enum_dom_users"))) {
907                 return r_u->status;
908         }
909         
910         DEBUG(5,("_samr_enum_dom_users: %d\n", __LINE__));
911
912         if (info->builtin_domain) {
913                 /* No users in builtin. */
914                 init_samr_r_enum_dom_users(r_u, q_u->start_idx, 0);
915                 DEBUG(5,("_samr_enum_dom_users: No users in BUILTIN\n"));
916                 return r_u->status;
917         }
918
919         become_root();
920
921         /* AS ROOT !!!! */
922
923         if ((info->disp_info->enum_users != NULL) &&
924             (info->disp_info->enum_acb_mask != q_u->acb_mask)) {
925                 pdb_search_destroy(info->disp_info->enum_users);
926                 info->disp_info->enum_users = NULL;
927         }
928
929         if (info->disp_info->enum_users == NULL) {
930                 info->disp_info->enum_users = pdb_search_users(q_u->acb_mask);
931                 info->disp_info->enum_acb_mask = q_u->acb_mask;
932         }
933
934         if (info->disp_info->enum_users == NULL) {
935                 /* END AS ROOT !!!! */
936                 unbecome_root();
937                 return NT_STATUS_ACCESS_DENIED;
938         }
939
940         num_account = pdb_search_entries(info->disp_info->enum_users,
941                                          enum_context, max_entries,
942                                          &entries);
943
944         /* END AS ROOT !!!! */
945
946         unbecome_root();
947
948         if (num_account == 0) {
949                 DEBUG(5, ("_samr_enum_dom_users: enumeration handle over "
950                           "total entries\n"));
951                 init_samr_r_enum_dom_users(r_u, q_u->start_idx, 0);
952                 return NT_STATUS_OK;
953         }
954
955         r_u->status = make_user_sam_entry_list(p->mem_ctx, &r_u->sam,
956                                                &r_u->uni_acct_name, 
957                                                num_account, enum_context,
958                                                entries);
959
960         if (!NT_STATUS_IS_OK(r_u->status))
961                 return r_u->status;
962
963         if (max_entries <= num_account) {
964                 r_u->status = STATUS_MORE_ENTRIES;
965         } else {
966                 r_u->status = NT_STATUS_OK;
967         }
968
969         /* Ensure we cache this enumeration. */
970         set_disp_info_cache_timeout(info->disp_info, DISP_INFO_CACHE_TIMEOUT);
971
972         DEBUG(5, ("_samr_enum_dom_users: %d\n", __LINE__));
973
974         init_samr_r_enum_dom_users(r_u, q_u->start_idx + num_account,
975                                    num_account);
976
977         DEBUG(5,("_samr_enum_dom_users: %d\n", __LINE__));
978
979         return r_u->status;
980 }
981
982 /*******************************************************************
983 makes a SAM_ENTRY / UNISTR2* structure from a group list.
984 ********************************************************************/
985
986 static void make_group_sam_entry_list(TALLOC_CTX *ctx, SAM_ENTRY **sam_pp,
987                                       UNISTR2 **uni_name_pp,
988                                       uint32 num_sam_entries,
989                                       struct samr_displayentry *entries)
990 {
991         uint32 i;
992         SAM_ENTRY *sam;
993         UNISTR2 *uni_name;
994
995         *sam_pp = NULL;
996         *uni_name_pp = NULL;
997
998         if (num_sam_entries == 0)
999                 return;
1000
1001         sam = TALLOC_ZERO_ARRAY(ctx, SAM_ENTRY, num_sam_entries);
1002         uni_name = TALLOC_ZERO_ARRAY(ctx, UNISTR2, num_sam_entries);
1003
1004         if (sam == NULL || uni_name == NULL) {
1005                 DEBUG(0, ("NULL pointers in SAMR_R_QUERY_DISPINFO\n"));
1006                 return;
1007         }
1008
1009         for (i = 0; i < num_sam_entries; i++) {
1010                 /*
1011                  * JRA. I think this should include the null. TNG does not.
1012                  */
1013                 init_unistr2(&uni_name[i], entries[i].account_name,
1014                              UNI_STR_TERMINATE);
1015                 init_sam_entry(&sam[i], &uni_name[i], entries[i].rid);
1016         }
1017
1018         *sam_pp = sam;
1019         *uni_name_pp = uni_name;
1020 }
1021
1022 /*******************************************************************
1023  samr_reply_enum_dom_groups
1024  ********************************************************************/
1025
1026 NTSTATUS _samr_enum_dom_groups(pipes_struct *p, SAMR_Q_ENUM_DOM_GROUPS *q_u, SAMR_R_ENUM_DOM_GROUPS *r_u)
1027 {
1028         struct samr_info *info = NULL;
1029         struct samr_displayentry *groups;
1030         uint32 num_groups;
1031
1032         r_u->status = NT_STATUS_OK;
1033
1034         /* find the policy handle.  open a policy on it. */
1035         if (!find_policy_by_hnd(p, &q_u->pol, (void **)(void *)&info))
1036                 return NT_STATUS_INVALID_HANDLE;
1037
1038         r_u->status = access_check_samr_function(info->acc_granted,
1039                                                  SA_RIGHT_DOMAIN_ENUM_ACCOUNTS,
1040                                                  "_samr_enum_dom_groups");
1041         if (!NT_STATUS_IS_OK(r_u->status))
1042                 return r_u->status;
1043
1044         DEBUG(5,("samr_reply_enum_dom_groups: %d\n", __LINE__));
1045
1046         if (info->builtin_domain) {
1047                 /* No groups in builtin. */
1048                 init_samr_r_enum_dom_groups(r_u, q_u->start_idx, 0);
1049                 DEBUG(5,("_samr_enum_dom_users: No groups in BUILTIN\n"));
1050                 return r_u->status;
1051         }
1052
1053         /* the domain group array is being allocated in the function below */
1054
1055         become_root();
1056
1057         if (info->disp_info->groups == NULL) {
1058                 info->disp_info->groups = pdb_search_groups();
1059
1060                 if (info->disp_info->groups == NULL) {
1061                         unbecome_root();
1062                         return NT_STATUS_ACCESS_DENIED;
1063                 }
1064         }
1065
1066         num_groups = pdb_search_entries(info->disp_info->groups, q_u->start_idx,
1067                                         MAX_SAM_ENTRIES, &groups);
1068         unbecome_root();
1069         
1070         /* Ensure we cache this enumeration. */
1071         set_disp_info_cache_timeout(info->disp_info, DISP_INFO_CACHE_TIMEOUT);
1072
1073         make_group_sam_entry_list(p->mem_ctx, &r_u->sam, &r_u->uni_grp_name,
1074                                   num_groups, groups);
1075
1076         init_samr_r_enum_dom_groups(r_u, q_u->start_idx, num_groups);
1077
1078         DEBUG(5,("samr_enum_dom_groups: %d\n", __LINE__));
1079
1080         return r_u->status;
1081 }
1082
1083 /*******************************************************************
1084  samr_reply_enum_dom_aliases
1085  ********************************************************************/
1086
1087 NTSTATUS _samr_enum_dom_aliases(pipes_struct *p, SAMR_Q_ENUM_DOM_ALIASES *q_u, SAMR_R_ENUM_DOM_ALIASES *r_u)
1088 {
1089         struct samr_info *info;
1090         struct samr_displayentry *aliases;
1091         uint32 num_aliases = 0;
1092
1093         /* find the policy handle.  open a policy on it. */
1094         if (!find_policy_by_hnd(p, &q_u->pol, (void **)(void *)&info))
1095                 return NT_STATUS_INVALID_HANDLE;
1096
1097         r_u->status = access_check_samr_function(info->acc_granted,
1098                                                  SA_RIGHT_DOMAIN_ENUM_ACCOUNTS,
1099                                                  "_samr_enum_dom_aliases");
1100         if (!NT_STATUS_IS_OK(r_u->status))
1101                 return r_u->status;
1102
1103         DEBUG(5,("samr_reply_enum_dom_aliases: sid %s\n",
1104                  sid_string_static(&info->sid)));
1105
1106         become_root();
1107
1108         if (info->disp_info->aliases == NULL) {
1109                 info->disp_info->aliases = pdb_search_aliases(&info->sid);
1110                 if (info->disp_info->aliases == NULL) {
1111                         unbecome_root();
1112                         return NT_STATUS_ACCESS_DENIED;
1113                 }
1114         }
1115
1116         num_aliases = pdb_search_entries(info->disp_info->aliases, q_u->start_idx,
1117                                          MAX_SAM_ENTRIES, &aliases);
1118         unbecome_root();
1119         
1120         /* Ensure we cache this enumeration. */
1121         set_disp_info_cache_timeout(info->disp_info, DISP_INFO_CACHE_TIMEOUT);
1122
1123         make_group_sam_entry_list(p->mem_ctx, &r_u->sam, &r_u->uni_grp_name,
1124                                   num_aliases, aliases);
1125
1126         init_samr_r_enum_dom_aliases(r_u, q_u->start_idx + num_aliases,
1127                                      num_aliases);
1128
1129         DEBUG(5,("samr_enum_dom_aliases: %d\n", __LINE__));
1130
1131         return r_u->status;
1132 }
1133
1134 /*******************************************************************
1135  samr_reply_query_dispinfo
1136  ********************************************************************/
1137
1138 NTSTATUS _samr_query_dispinfo(pipes_struct *p, SAMR_Q_QUERY_DISPINFO *q_u, 
1139                               SAMR_R_QUERY_DISPINFO *r_u)
1140 {
1141         struct samr_info *info = NULL;
1142         uint32 struct_size=0x20; /* W2K always reply that, client doesn't care */
1143         
1144         uint32 max_entries=q_u->max_entries;
1145         uint32 enum_context=q_u->start_idx;
1146         uint32 max_size=q_u->max_size;
1147
1148         SAM_DISPINFO_CTR *ctr;
1149         uint32 temp_size=0, total_data_size=0;
1150         NTSTATUS disp_ret = NT_STATUS_UNSUCCESSFUL;
1151         uint32 num_account = 0;
1152         enum remote_arch_types ra_type = get_remote_arch();
1153         int max_sam_entries = (ra_type == RA_WIN95) ? MAX_SAM_ENTRIES_W95 : MAX_SAM_ENTRIES_W2K;
1154         struct samr_displayentry *entries = NULL;
1155
1156         DEBUG(5, ("samr_reply_query_dispinfo: %d\n", __LINE__));
1157         r_u->status = NT_STATUS_UNSUCCESSFUL;
1158
1159         /* find the policy handle.  open a policy on it. */
1160         if (!find_policy_by_hnd(p, &q_u->domain_pol, (void **)(void *)&info))
1161                 return NT_STATUS_INVALID_HANDLE;
1162
1163         /*
1164          * calculate how many entries we will return.
1165          * based on 
1166          * - the number of entries the client asked
1167          * - our limit on that
1168          * - the starting point (enumeration context)
1169          * - the buffer size the client will accept
1170          */
1171
1172         /*
1173          * We are a lot more like W2K. Instead of reading the SAM
1174          * each time to find the records we need to send back,
1175          * we read it once and link that copy to the sam handle.
1176          * For large user list (over the MAX_SAM_ENTRIES)
1177          * it's a definitive win.
1178          * second point to notice: between enumerations
1179          * our sam is now the same as it's a snapshoot.
1180          * third point: got rid of the static SAM_USER_21 struct
1181          * no more intermediate.
1182          * con: it uses much more memory, as a full copy is stored
1183          * in memory.
1184          *
1185          * If you want to change it, think twice and think
1186          * of the second point , that's really important.
1187          *
1188          * JFM, 12/20/2001
1189          */
1190
1191         if ((q_u->switch_level < 1) || (q_u->switch_level > 5)) {
1192                 DEBUG(0,("_samr_query_dispinfo: Unknown info level (%u)\n",
1193                          (unsigned int)q_u->switch_level ));
1194                 return NT_STATUS_INVALID_INFO_CLASS;
1195         }
1196
1197         /* first limit the number of entries we will return */
1198         if(max_entries > max_sam_entries) {
1199                 DEBUG(5, ("samr_reply_query_dispinfo: client requested %d "
1200                           "entries, limiting to %d\n", max_entries,
1201                           max_sam_entries));
1202                 max_entries = max_sam_entries;
1203         }
1204
1205         /* calculate the size and limit on the number of entries we will
1206          * return */
1207
1208         temp_size=max_entries*struct_size;
1209         
1210         if (temp_size>max_size) {
1211                 max_entries=MIN((max_size/struct_size),max_entries);;
1212                 DEBUG(5, ("samr_reply_query_dispinfo: buffer size limits to "
1213                           "only %d entries\n", max_entries));
1214         }
1215
1216         if (!(ctr = TALLOC_ZERO_P(p->mem_ctx,SAM_DISPINFO_CTR)))
1217                 return NT_STATUS_NO_MEMORY;
1218
1219         ZERO_STRUCTP(ctr);
1220
1221         become_root();
1222
1223         /* THe following done as ROOT. Don't return without unbecome_root(). */
1224
1225         switch (q_u->switch_level) {
1226         case 0x1:
1227         case 0x4:
1228                 if (info->disp_info->users == NULL) {
1229                         info->disp_info->users = pdb_search_users(ACB_NORMAL);
1230                         if (info->disp_info->users == NULL) {
1231                                 unbecome_root();
1232                                 return NT_STATUS_ACCESS_DENIED;
1233                         }
1234                         DEBUG(10,("samr_reply_query_dispinfo: starting user enumeration at index %u\n",
1235                                 (unsigned  int)enum_context ));
1236                 } else {
1237                         DEBUG(10,("samr_reply_query_dispinfo: using cached user enumeration at index %u\n",
1238                                 (unsigned  int)enum_context ));
1239                 }
1240
1241                 num_account = pdb_search_entries(info->disp_info->users,
1242                                                  enum_context, max_entries,
1243                                                  &entries);
1244                 break;
1245         case 0x2:
1246                 if (info->disp_info->machines == NULL) {
1247                         info->disp_info->machines =
1248                                 pdb_search_users(ACB_WSTRUST|ACB_SVRTRUST);
1249                         if (info->disp_info->machines == NULL) {
1250                                 unbecome_root();
1251                                 return NT_STATUS_ACCESS_DENIED;
1252                         }
1253                         DEBUG(10,("samr_reply_query_dispinfo: starting machine enumeration at index %u\n",
1254                                 (unsigned  int)enum_context ));
1255                 } else {
1256                         DEBUG(10,("samr_reply_query_dispinfo: using cached machine enumeration at index %u\n",
1257                                 (unsigned  int)enum_context ));
1258                 }
1259
1260                 num_account = pdb_search_entries(info->disp_info->machines,
1261                                                  enum_context, max_entries,
1262                                                  &entries);
1263                 break;
1264         case 0x3:
1265         case 0x5:
1266                 if (info->disp_info->groups == NULL) {
1267                         info->disp_info->groups = pdb_search_groups();
1268                         if (info->disp_info->groups == NULL) {
1269                                 unbecome_root();
1270                                 return NT_STATUS_ACCESS_DENIED;
1271                         }
1272                         DEBUG(10,("samr_reply_query_dispinfo: starting group enumeration at index %u\n",
1273                                 (unsigned  int)enum_context ));
1274                 } else {
1275                         DEBUG(10,("samr_reply_query_dispinfo: using cached group enumeration at index %u\n",
1276                                 (unsigned  int)enum_context ));
1277                 }
1278
1279                 num_account = pdb_search_entries(info->disp_info->groups,
1280                                                  enum_context, max_entries,
1281                                                  &entries);
1282                 break;
1283         default:
1284                 unbecome_root();
1285                 smb_panic("info class changed");
1286                 break;
1287         }
1288         unbecome_root();
1289
1290         /* Now create reply structure */
1291         switch (q_u->switch_level) {
1292         case 0x1:
1293                 disp_ret = init_sam_dispinfo_1(p->mem_ctx, &ctr->sam.info1,
1294                                                num_account, enum_context,
1295                                                entries);
1296                 break;
1297         case 0x2:
1298                 disp_ret = init_sam_dispinfo_2(p->mem_ctx, &ctr->sam.info2,
1299                                                num_account, enum_context,
1300                                                entries);
1301                 break;
1302         case 0x3:
1303                 disp_ret = init_sam_dispinfo_3(p->mem_ctx, &ctr->sam.info3,
1304                                                num_account, enum_context,
1305                                                entries);
1306                 break;
1307         case 0x4:
1308                 disp_ret = init_sam_dispinfo_4(p->mem_ctx, &ctr->sam.info4,
1309                                                num_account, enum_context,
1310                                                entries);
1311                 break;
1312         case 0x5:
1313                 disp_ret = init_sam_dispinfo_5(p->mem_ctx, &ctr->sam.info5,
1314                                                num_account, enum_context,
1315                                                entries);
1316                 break;
1317         default:
1318                 smb_panic("info class changed");
1319                 break;
1320         }
1321
1322         if (!NT_STATUS_IS_OK(disp_ret))
1323                 return disp_ret;
1324
1325         /* calculate the total size */
1326         total_data_size=num_account*struct_size;
1327
1328         if (num_account) {
1329                 r_u->status = STATUS_MORE_ENTRIES;
1330         } else {
1331                 r_u->status = NT_STATUS_OK;
1332         }
1333
1334         /* Ensure we cache this enumeration. */
1335         set_disp_info_cache_timeout(info->disp_info, DISP_INFO_CACHE_TIMEOUT);
1336
1337         DEBUG(5, ("_samr_query_dispinfo: %d\n", __LINE__));
1338
1339         init_samr_r_query_dispinfo(r_u, num_account, total_data_size,
1340                                    temp_size, q_u->switch_level, ctr,
1341                                    r_u->status);
1342
1343         return r_u->status;
1344
1345 }
1346
1347 /*******************************************************************
1348  samr_reply_query_aliasinfo
1349  ********************************************************************/
1350
1351 NTSTATUS _samr_query_aliasinfo(pipes_struct *p, SAMR_Q_QUERY_ALIASINFO *q_u, SAMR_R_QUERY_ALIASINFO *r_u)
1352 {
1353         DOM_SID   sid;
1354         struct acct_info info;
1355         uint32    acc_granted;
1356         NTSTATUS status;
1357
1358         r_u->status = NT_STATUS_OK;
1359
1360         DEBUG(5,("_samr_query_aliasinfo: %d\n", __LINE__));
1361
1362         /* find the policy handle.  open a policy on it. */
1363         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &sid, &acc_granted, NULL))
1364                 return NT_STATUS_INVALID_HANDLE;
1365         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_ALIAS_LOOKUP_INFO, "_samr_query_aliasinfo"))) {
1366                 return r_u->status;
1367         }
1368
1369         become_root();
1370         status = pdb_get_aliasinfo(&sid, &info);
1371         unbecome_root();
1372         
1373         if ( !NT_STATUS_IS_OK(status))
1374                 return status;
1375
1376         if ( !(r_u->ctr = TALLOC_ZERO_P( p->mem_ctx, ALIAS_INFO_CTR )) ) 
1377                 return NT_STATUS_NO_MEMORY;
1378
1379
1380         switch (q_u->level ) {
1381         case 1:
1382                 r_u->ctr->level = 1;
1383                 init_samr_alias_info1(&r_u->ctr->alias.info1, info.acct_name, 1, info.acct_desc);
1384                 break;
1385         case 3:
1386                 r_u->ctr->level = 3;
1387                 init_samr_alias_info3(&r_u->ctr->alias.info3, info.acct_desc);
1388                 break;
1389         default:
1390                 return NT_STATUS_INVALID_INFO_CLASS;
1391         }
1392
1393         DEBUG(5,("_samr_query_aliasinfo: %d\n", __LINE__));
1394
1395         return r_u->status;
1396 }
1397
1398 #if 0
1399 /*******************************************************************
1400  samr_reply_lookup_ids
1401  ********************************************************************/
1402
1403  uint32 _samr_lookup_ids(pipes_struct *p, SAMR_Q_LOOKUP_IDS *q_u, SAMR_R_LOOKUP_IDS *r_u)
1404 {
1405     uint32 rid[MAX_SAM_ENTRIES];
1406     int num_rids = q_u->num_sids1;
1407
1408     r_u->status = NT_STATUS_OK;
1409
1410     DEBUG(5,("_samr_lookup_ids: %d\n", __LINE__));
1411
1412     if (num_rids > MAX_SAM_ENTRIES) {
1413         num_rids = MAX_SAM_ENTRIES;
1414         DEBUG(5,("_samr_lookup_ids: truncating entries to %d\n", num_rids));
1415     }
1416
1417 #if 0
1418     int i;
1419     SMB_ASSERT_ARRAY(q_u->uni_user_name, num_rids);
1420
1421     for (i = 0; i < num_rids && status == 0; i++)
1422     {
1423         struct sam_passwd *sam_pass;
1424         fstring user_name;
1425
1426
1427         fstrcpy(user_name, unistrn2(q_u->uni_user_name[i].buffer,
1428                                     q_u->uni_user_name[i].uni_str_len));
1429
1430         /* find the user account */
1431         become_root();
1432         sam_pass = get_smb21pwd_entry(user_name, 0);
1433         unbecome_root();
1434
1435         if (sam_pass == NULL)
1436         {
1437             status = 0xC0000000 | NT_STATUS_NO_SUCH_USER;
1438             rid[i] = 0;
1439         }
1440         else
1441         {
1442             rid[i] = sam_pass->user_rid;
1443         }
1444     }
1445 #endif
1446
1447     num_rids = 1;
1448     rid[0] = BUILTIN_ALIAS_RID_USERS;
1449
1450     init_samr_r_lookup_ids(&r_u, num_rids, rid, NT_STATUS_OK);
1451
1452     DEBUG(5,("_samr_lookup_ids: %d\n", __LINE__));
1453
1454     return r_u->status;
1455 }
1456 #endif
1457
1458 /*******************************************************************
1459  _samr_lookup_names
1460  ********************************************************************/
1461
1462 NTSTATUS _samr_lookup_names(pipes_struct *p, SAMR_Q_LOOKUP_NAMES *q_u, SAMR_R_LOOKUP_NAMES *r_u)
1463 {
1464         uint32 rid[MAX_SAM_ENTRIES];
1465         enum lsa_SidType type[MAX_SAM_ENTRIES];
1466         int i;
1467         int num_rids = q_u->num_names2;
1468         DOM_SID pol_sid;
1469         fstring sid_str;
1470         uint32  acc_granted;
1471
1472         r_u->status = NT_STATUS_OK;
1473
1474         DEBUG(5,("_samr_lookup_names: %d\n", __LINE__));
1475
1476         ZERO_ARRAY(rid);
1477         ZERO_ARRAY(type);
1478
1479         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &pol_sid, &acc_granted, NULL)) {
1480                 init_samr_r_lookup_names(p->mem_ctx, r_u, 0, NULL, NULL, NT_STATUS_OBJECT_TYPE_MISMATCH);
1481                 return r_u->status;
1482         }
1483         
1484         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, 0, "_samr_lookup_names"))) { /* Don't know the acc_bits yet */
1485                 return r_u->status;
1486         }
1487
1488         if (num_rids > MAX_SAM_ENTRIES) {
1489                 num_rids = MAX_SAM_ENTRIES;
1490                 DEBUG(5,("_samr_lookup_names: truncating entries to %d\n", num_rids));
1491         }
1492
1493         DEBUG(5,("_samr_lookup_names: looking name on SID %s\n", sid_to_string(sid_str, &pol_sid)));
1494         
1495         for (i = 0; i < num_rids; i++) {
1496                 fstring name;
1497                 int ret;
1498
1499                 r_u->status = NT_STATUS_NONE_MAPPED;
1500                 type[i] = SID_NAME_UNKNOWN;
1501
1502                 rid [i] = 0xffffffff;
1503
1504                 ret = rpcstr_pull(name, q_u->uni_name[i].buffer, sizeof(name), q_u->uni_name[i].uni_str_len*2, 0);
1505
1506                 if (ret <= 0) {
1507                         continue;
1508                 }
1509
1510                 if (sid_check_is_builtin(&pol_sid)) {
1511                         if (lookup_builtin_name(name, &rid[i])) {
1512                                 type[i] = SID_NAME_ALIAS;
1513                         }
1514                 } else {
1515                         lookup_global_sam_name(name, 0, &rid[i], &type[i]);
1516                 }
1517
1518                 if (type[i] != SID_NAME_UNKNOWN) {
1519                         r_u->status = NT_STATUS_OK;
1520                 }
1521         }
1522
1523         init_samr_r_lookup_names(p->mem_ctx, r_u, num_rids, rid, type, r_u->status);
1524
1525         DEBUG(5,("_samr_lookup_names: %d\n", __LINE__));
1526
1527         return r_u->status;
1528 }
1529
1530 /*******************************************************************
1531  _samr_chgpasswd_user
1532  ********************************************************************/
1533
1534 NTSTATUS _samr_chgpasswd_user(pipes_struct *p, SAMR_Q_CHGPASSWD_USER *q_u, SAMR_R_CHGPASSWD_USER *r_u)
1535 {
1536         fstring user_name;
1537         fstring wks;
1538
1539         DEBUG(5,("_samr_chgpasswd_user: %d\n", __LINE__));
1540
1541         r_u->status = NT_STATUS_OK;
1542
1543         rpcstr_pull(user_name, q_u->uni_user_name.buffer, sizeof(user_name), q_u->uni_user_name.uni_str_len*2, 0);
1544         rpcstr_pull(wks, q_u->uni_dest_host.buffer, sizeof(wks), q_u->uni_dest_host.uni_str_len*2,0);
1545
1546         DEBUG(5,("samr_chgpasswd_user: user: %s wks: %s\n", user_name, wks));
1547
1548         /*
1549          * Pass the user through the NT -> unix user mapping
1550          * function.
1551          */
1552  
1553         (void)map_username(user_name);
1554  
1555         /*
1556          * UNIX username case mangling not required, pass_oem_change 
1557          * is case insensitive.
1558          */
1559
1560         r_u->status = pass_oem_change(user_name, q_u->lm_newpass.pass, q_u->lm_oldhash.hash,
1561                                 q_u->nt_newpass.pass, q_u->nt_oldhash.hash, NULL);
1562
1563         init_samr_r_chgpasswd_user(r_u, r_u->status);
1564
1565         DEBUG(5,("_samr_chgpasswd_user: %d\n", __LINE__));
1566
1567         return r_u->status;
1568 }
1569
1570 /*******************************************************************
1571  _samr_chgpasswd_user3
1572  ********************************************************************/
1573
1574 NTSTATUS _samr_chgpasswd_user3(pipes_struct *p, SAMR_Q_CHGPASSWD_USER3 *q_u, SAMR_R_CHGPASSWD_USER3 *r_u)
1575 {
1576         fstring user_name;
1577         fstring wks;
1578         uint32 reject_reason;
1579         SAM_UNK_INFO_1 *info = NULL;
1580         SAMR_CHANGE_REJECT *reject = NULL;
1581
1582         DEBUG(5,("_samr_chgpasswd_user3: %d\n", __LINE__));
1583
1584         rpcstr_pull(user_name, q_u->uni_user_name.buffer, sizeof(user_name), q_u->uni_user_name.uni_str_len*2, 0);
1585         rpcstr_pull(wks, q_u->uni_dest_host.buffer, sizeof(wks), q_u->uni_dest_host.uni_str_len*2,0);
1586
1587         DEBUG(5,("_samr_chgpasswd_user3: user: %s wks: %s\n", user_name, wks));
1588
1589         /*
1590          * Pass the user through the NT -> unix user mapping
1591          * function.
1592          */
1593  
1594         (void)map_username(user_name);
1595  
1596         /*
1597          * UNIX username case mangling not required, pass_oem_change 
1598          * is case insensitive.
1599          */
1600
1601         r_u->status = pass_oem_change(user_name, q_u->lm_newpass.pass, q_u->lm_oldhash.hash,
1602                                       q_u->nt_newpass.pass, q_u->nt_oldhash.hash, &reject_reason);
1603
1604         if (NT_STATUS_EQUAL(r_u->status, NT_STATUS_PASSWORD_RESTRICTION) || 
1605             NT_STATUS_EQUAL(r_u->status, NT_STATUS_ACCOUNT_RESTRICTION)) {
1606
1607                 uint32 min_pass_len,pass_hist,password_properties;
1608                 time_t u_expire, u_min_age;
1609                 NTTIME nt_expire, nt_min_age;
1610                 uint32 account_policy_temp;
1611
1612                 if ((info = TALLOC_ZERO_P(p->mem_ctx, SAM_UNK_INFO_1)) == NULL) {
1613                         return NT_STATUS_NO_MEMORY;
1614                 }
1615
1616                 if ((reject = TALLOC_ZERO_P(p->mem_ctx, SAMR_CHANGE_REJECT)) == NULL) {
1617                         return NT_STATUS_NO_MEMORY;
1618                 }
1619
1620                 ZERO_STRUCTP(info);
1621                 ZERO_STRUCTP(reject);
1622
1623                 become_root();
1624
1625                 /* AS ROOT !!! */
1626
1627                 pdb_get_account_policy(AP_MIN_PASSWORD_LEN, &account_policy_temp);
1628                 min_pass_len = account_policy_temp;
1629
1630                 pdb_get_account_policy(AP_PASSWORD_HISTORY, &account_policy_temp);
1631                 pass_hist = account_policy_temp;
1632
1633                 pdb_get_account_policy(AP_USER_MUST_LOGON_TO_CHG_PASS, &account_policy_temp);
1634                 password_properties = account_policy_temp;
1635
1636                 pdb_get_account_policy(AP_MAX_PASSWORD_AGE, &account_policy_temp);
1637                 u_expire = account_policy_temp;
1638
1639                 pdb_get_account_policy(AP_MIN_PASSWORD_AGE, &account_policy_temp);
1640                 u_min_age = account_policy_temp;
1641
1642                 /* !AS ROOT */
1643                 
1644                 unbecome_root();
1645
1646                 unix_to_nt_time_abs(&nt_expire, u_expire);
1647                 unix_to_nt_time_abs(&nt_min_age, u_min_age);
1648
1649                 init_unk_info1(info, (uint16)min_pass_len, (uint16)pass_hist, 
1650                                password_properties, nt_expire, nt_min_age);
1651
1652                 reject->reject_reason = reject_reason;
1653         }
1654         
1655         init_samr_r_chgpasswd_user3(r_u, r_u->status, reject, info);
1656
1657         DEBUG(5,("_samr_chgpasswd_user3: %d\n", __LINE__));
1658
1659         return r_u->status;
1660 }
1661
1662 /*******************************************************************
1663 makes a SAMR_R_LOOKUP_RIDS structure.
1664 ********************************************************************/
1665
1666 static bool make_samr_lookup_rids(TALLOC_CTX *ctx, uint32 num_names,
1667                                   const char **names, UNIHDR **pp_hdr_name,
1668                                   UNISTR2 **pp_uni_name)
1669 {
1670         uint32 i;
1671         UNIHDR *hdr_name=NULL;
1672         UNISTR2 *uni_name=NULL;
1673
1674         *pp_uni_name = NULL;
1675         *pp_hdr_name = NULL;
1676
1677         if (num_names != 0) {
1678                 hdr_name = TALLOC_ZERO_ARRAY(ctx, UNIHDR, num_names);
1679                 if (hdr_name == NULL)
1680                         return False;
1681
1682                 uni_name = TALLOC_ZERO_ARRAY(ctx,UNISTR2, num_names);
1683                 if (uni_name == NULL)
1684                         return False;
1685         }
1686
1687         for (i = 0; i < num_names; i++) {
1688                 DEBUG(10, ("names[%d]:%s\n", i, names[i] && *names[i] ? names[i] : ""));
1689                 init_unistr2(&uni_name[i], names[i], UNI_FLAGS_NONE);
1690                 init_uni_hdr(&hdr_name[i], &uni_name[i]);
1691         }
1692
1693         *pp_uni_name = uni_name;
1694         *pp_hdr_name = hdr_name;
1695
1696         return True;
1697 }
1698
1699 /*******************************************************************
1700  _samr_lookup_rids
1701  ********************************************************************/
1702
1703 NTSTATUS _samr_lookup_rids(pipes_struct *p, SAMR_Q_LOOKUP_RIDS *q_u, SAMR_R_LOOKUP_RIDS *r_u)
1704 {
1705         const char **names;
1706         enum lsa_SidType *attrs = NULL;
1707         uint32 *wire_attrs = NULL;
1708         UNIHDR *hdr_name = NULL;
1709         UNISTR2 *uni_name = NULL;
1710         DOM_SID pol_sid;
1711         int num_rids = (int)q_u->num_rids1;
1712         uint32 acc_granted;
1713         int i;
1714
1715         r_u->status = NT_STATUS_OK;
1716
1717         DEBUG(5,("_samr_lookup_rids: %d\n", __LINE__));
1718
1719         /* find the policy handle.  open a policy on it. */
1720         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &pol_sid, &acc_granted, NULL))
1721                 return NT_STATUS_INVALID_HANDLE;
1722
1723         if (num_rids > 1000) {
1724                 DEBUG(0, ("Got asked for %d rids (more than 1000) -- according "
1725                           "to samba4 idl this is not possible\n", num_rids));
1726                 return NT_STATUS_UNSUCCESSFUL;
1727         }
1728
1729         if (num_rids) {
1730                 names = TALLOC_ZERO_ARRAY(p->mem_ctx, const char *, num_rids);
1731                 attrs = TALLOC_ZERO_ARRAY(p->mem_ctx, enum lsa_SidType, num_rids);
1732                 wire_attrs = TALLOC_ZERO_ARRAY(p->mem_ctx, uint32, num_rids);
1733
1734                 if ((names == NULL) || (attrs == NULL) || (wire_attrs==NULL))
1735                         return NT_STATUS_NO_MEMORY;
1736         } else {
1737                 names = NULL;
1738                 attrs = NULL;
1739                 wire_attrs = NULL;
1740         }
1741
1742         become_root();  /* lookup_sid can require root privs */
1743         r_u->status = pdb_lookup_rids(&pol_sid, num_rids, q_u->rid,
1744                                       names, attrs);
1745         unbecome_root();
1746
1747         if ( NT_STATUS_EQUAL(r_u->status, NT_STATUS_NONE_MAPPED) && (num_rids == 0) ) {
1748                 r_u->status = NT_STATUS_OK;
1749         }
1750
1751         if(!make_samr_lookup_rids(p->mem_ctx, num_rids, names,
1752                                   &hdr_name, &uni_name))
1753                 return NT_STATUS_NO_MEMORY;
1754
1755         /* Convert from enum lsa_SidType to uint32 for wire format. */
1756         for (i = 0; i < num_rids; i++) {
1757                 wire_attrs[i] = (uint32)attrs[i];
1758         }
1759
1760         init_samr_r_lookup_rids(r_u, num_rids, hdr_name, uni_name, wire_attrs);
1761
1762         DEBUG(5,("_samr_lookup_rids: %d\n", __LINE__));
1763
1764         return r_u->status;
1765 }
1766
1767 /*******************************************************************
1768  _samr_open_user. Safe - gives out no passwd info.
1769  ********************************************************************/
1770
1771 NTSTATUS _samr_open_user(pipes_struct *p, SAMR_Q_OPEN_USER *q_u, SAMR_R_OPEN_USER *r_u)
1772 {
1773         struct samu *sampass=NULL;
1774         DOM_SID sid;
1775         POLICY_HND domain_pol = q_u->domain_pol;
1776         POLICY_HND *user_pol = &r_u->user_pol;
1777         struct samr_info *info = NULL;
1778         SEC_DESC *psd = NULL;
1779         uint32    acc_granted;
1780         uint32    des_access = q_u->access_mask;
1781         size_t    sd_size;
1782         bool ret;
1783         NTSTATUS nt_status;
1784         SE_PRIV se_rights;
1785
1786         r_u->status = NT_STATUS_OK;
1787
1788         /* find the domain policy handle and get domain SID / access bits in the domain policy. */
1789         
1790         if ( !get_lsa_policy_samr_sid(p, &domain_pol, &sid, &acc_granted, NULL) )
1791                 return NT_STATUS_INVALID_HANDLE;
1792         
1793         nt_status = access_check_samr_function( acc_granted, 
1794                 SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_open_user" );
1795                 
1796         if ( !NT_STATUS_IS_OK(nt_status) )
1797                 return nt_status;
1798
1799         if ( !(sampass = samu_new( p->mem_ctx )) ) {
1800                 return NT_STATUS_NO_MEMORY;
1801         }
1802
1803         /* append the user's RID to it */
1804         
1805         if (!sid_append_rid(&sid, q_u->user_rid))
1806                 return NT_STATUS_NO_SUCH_USER;
1807         
1808         /* check if access can be granted as requested by client. */
1809         
1810         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &usr_generic_mapping, &sid, SAMR_USR_RIGHTS_WRITE_PW);
1811         se_map_generic(&des_access, &usr_generic_mapping);
1812         
1813         se_priv_copy( &se_rights, &se_machine_account );
1814         se_priv_add( &se_rights, &se_add_users );
1815         
1816         nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
1817                 &se_rights, GENERIC_RIGHTS_USER_WRITE, des_access, 
1818                 &acc_granted, "_samr_open_user");
1819                 
1820         if ( !NT_STATUS_IS_OK(nt_status) )
1821                 return nt_status;
1822
1823         become_root();
1824         ret=pdb_getsampwsid(sampass, &sid);
1825         unbecome_root();
1826
1827         /* check that the SID exists in our domain. */
1828         if (ret == False) {
1829                 return NT_STATUS_NO_SUCH_USER;
1830         }
1831
1832         TALLOC_FREE(sampass);
1833
1834         /* associate the user's SID and access bits with the new handle. */
1835         if ((info = get_samr_info_by_sid(&sid)) == NULL)
1836                 return NT_STATUS_NO_MEMORY;
1837         info->acc_granted = acc_granted;
1838
1839         /* get a (unique) handle.  open a policy on it. */
1840         if (!create_policy_hnd(p, user_pol, free_samr_info, (void *)info))
1841                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1842
1843         return r_u->status;
1844 }
1845
1846 /*************************************************************************
1847  get_user_info_7. Safe. Only gives out account_name.
1848  *************************************************************************/
1849
1850 static NTSTATUS get_user_info_7(TALLOC_CTX *mem_ctx, SAM_USER_INFO_7 *id7, DOM_SID *user_sid)
1851 {
1852         struct samu *smbpass=NULL;
1853         bool ret;
1854
1855         if ( !(smbpass = samu_new( mem_ctx )) ) {
1856                 return NT_STATUS_NO_MEMORY;
1857         }
1858         
1859         become_root();
1860         ret = pdb_getsampwsid(smbpass, user_sid);
1861         unbecome_root();
1862
1863         if ( !ret ) {
1864                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
1865                 return NT_STATUS_NO_SUCH_USER;
1866         }
1867
1868         DEBUG(3,("User:[%s]\n", pdb_get_username(smbpass) ));
1869
1870         ZERO_STRUCTP(id7);
1871         init_sam_user_info7(id7, pdb_get_username(smbpass) );
1872
1873         TALLOC_FREE(smbpass);
1874
1875         return NT_STATUS_OK;
1876 }
1877
1878 /*************************************************************************
1879  get_user_info_9. Only gives out primary group SID.
1880  *************************************************************************/
1881 static NTSTATUS get_user_info_9(TALLOC_CTX *mem_ctx, SAM_USER_INFO_9 * id9, DOM_SID *user_sid)
1882 {
1883         struct samu *smbpass=NULL;
1884         bool ret;
1885
1886         if ( !(smbpass = samu_new( mem_ctx )) ) {
1887                 return NT_STATUS_NO_MEMORY;
1888         }
1889
1890         become_root();
1891         ret = pdb_getsampwsid(smbpass, user_sid);
1892         unbecome_root();
1893
1894         if (ret==False) {
1895                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
1896                 return NT_STATUS_NO_SUCH_USER;
1897         }
1898
1899         DEBUG(3,("User:[%s]\n", pdb_get_username(smbpass) ));
1900
1901         ZERO_STRUCTP(id9);
1902         init_sam_user_info9(id9, pdb_get_group_rid(smbpass) );
1903
1904         TALLOC_FREE(smbpass);
1905
1906         return NT_STATUS_OK;
1907 }
1908
1909 /*************************************************************************
1910  get_user_info_16. Safe. Only gives out acb bits.
1911  *************************************************************************/
1912
1913 static NTSTATUS get_user_info_16(TALLOC_CTX *mem_ctx, SAM_USER_INFO_16 *id16, DOM_SID *user_sid)
1914 {
1915         struct samu *smbpass=NULL;
1916         bool ret;
1917
1918         if ( !(smbpass = samu_new( mem_ctx )) ) {
1919                 return NT_STATUS_NO_MEMORY;
1920         }
1921
1922         become_root();
1923         ret = pdb_getsampwsid(smbpass, user_sid);
1924         unbecome_root();
1925
1926         if (ret==False) {
1927                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
1928                 return NT_STATUS_NO_SUCH_USER;
1929         }
1930
1931         DEBUG(3,("User:[%s]\n", pdb_get_username(smbpass) ));
1932
1933         ZERO_STRUCTP(id16);
1934         init_sam_user_info16(id16, pdb_get_acct_ctrl(smbpass) );
1935
1936         TALLOC_FREE(smbpass);
1937
1938         return NT_STATUS_OK;
1939 }
1940
1941 /*************************************************************************
1942  get_user_info_18. OK - this is the killer as it gives out password info.
1943  Ensure that this is only allowed on an encrypted connection with a root
1944  user. JRA. 
1945  *************************************************************************/
1946
1947 static NTSTATUS get_user_info_18(pipes_struct *p, TALLOC_CTX *mem_ctx, SAM_USER_INFO_18 * id18, DOM_SID *user_sid)
1948 {
1949         struct samu *smbpass=NULL;
1950         bool ret;
1951
1952         if (p->auth.auth_type != PIPE_AUTH_TYPE_NTLMSSP || p->auth.auth_type != PIPE_AUTH_TYPE_SPNEGO_NTLMSSP) {
1953                 return NT_STATUS_ACCESS_DENIED;
1954         }
1955
1956         if (p->auth.auth_level != PIPE_AUTH_LEVEL_PRIVACY) {
1957                 return NT_STATUS_ACCESS_DENIED;
1958         }
1959
1960         /*
1961          * Do *NOT* do become_root()/unbecome_root() here ! JRA.
1962          */
1963
1964         if ( !(smbpass = samu_new( mem_ctx )) ) {
1965                 return NT_STATUS_NO_MEMORY;
1966         }
1967
1968         ret = pdb_getsampwsid(smbpass, user_sid);
1969
1970         if (ret == False) {
1971                 DEBUG(4, ("User %s not found\n", sid_string_static(user_sid)));
1972                 TALLOC_FREE(smbpass);
1973                 return (geteuid() == (uid_t)0) ? NT_STATUS_NO_SUCH_USER : NT_STATUS_ACCESS_DENIED;
1974         }
1975
1976         DEBUG(3,("User:[%s] 0x%x\n", pdb_get_username(smbpass), pdb_get_acct_ctrl(smbpass) ));
1977
1978         if ( pdb_get_acct_ctrl(smbpass) & ACB_DISABLED) {
1979                 TALLOC_FREE(smbpass);
1980                 return NT_STATUS_ACCOUNT_DISABLED;
1981         }
1982
1983         ZERO_STRUCTP(id18);
1984         init_sam_user_info18(id18, pdb_get_lanman_passwd(smbpass), pdb_get_nt_passwd(smbpass));
1985         
1986         TALLOC_FREE(smbpass);
1987
1988         return NT_STATUS_OK;
1989 }
1990
1991 /*************************************************************************
1992  get_user_info_20
1993  *************************************************************************/
1994
1995 static NTSTATUS get_user_info_20(TALLOC_CTX *mem_ctx, SAM_USER_INFO_20 *id20, DOM_SID *user_sid)
1996 {
1997         struct samu *sampass=NULL;
1998         bool ret;
1999
2000         if ( !(sampass = samu_new( mem_ctx )) ) {
2001                 return NT_STATUS_NO_MEMORY;
2002         }
2003
2004         become_root();
2005         ret = pdb_getsampwsid(sampass, user_sid);
2006         unbecome_root();
2007
2008         if (ret == False) {
2009                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
2010                 return NT_STATUS_NO_SUCH_USER;
2011         }
2012
2013         samr_clear_sam_passwd(sampass);
2014
2015         DEBUG(3,("User:[%s]\n",  pdb_get_username(sampass) ));
2016
2017         ZERO_STRUCTP(id20);
2018         init_sam_user_info20A(id20, sampass);
2019         
2020         TALLOC_FREE(sampass);
2021
2022         return NT_STATUS_OK;
2023 }
2024
2025 /*************************************************************************
2026  get_user_info_21
2027  *************************************************************************/
2028
2029 static NTSTATUS get_user_info_21(TALLOC_CTX *mem_ctx, SAM_USER_INFO_21 *id21, 
2030                                  DOM_SID *user_sid, DOM_SID *domain_sid)
2031 {
2032         struct samu *sampass=NULL;
2033         bool ret;
2034         NTSTATUS nt_status;
2035
2036         if ( !(sampass = samu_new( mem_ctx )) ) {
2037                 return NT_STATUS_NO_MEMORY;
2038         }
2039
2040         become_root();
2041         ret = pdb_getsampwsid(sampass, user_sid);
2042         unbecome_root();
2043
2044         if (ret == False) {
2045                 DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
2046                 return NT_STATUS_NO_SUCH_USER;
2047         }
2048
2049         samr_clear_sam_passwd(sampass);
2050
2051         DEBUG(3,("User:[%s]\n",  pdb_get_username(sampass) ));
2052
2053         ZERO_STRUCTP(id21);
2054         nt_status = init_sam_user_info21A(id21, sampass, domain_sid);
2055         
2056         TALLOC_FREE(sampass);
2057
2058         return nt_status;
2059 }
2060
2061 /*******************************************************************
2062  _samr_query_userinfo
2063  ********************************************************************/
2064
2065 NTSTATUS _samr_query_userinfo(pipes_struct *p, SAMR_Q_QUERY_USERINFO *q_u, SAMR_R_QUERY_USERINFO *r_u)
2066 {
2067         SAM_USERINFO_CTR *ctr;
2068         struct samr_info *info = NULL;
2069         DOM_SID domain_sid;
2070         uint32 rid;
2071         
2072         r_u->status=NT_STATUS_OK;
2073
2074         /* search for the handle */
2075         if (!find_policy_by_hnd(p, &q_u->pol, (void **)(void *)&info))
2076                 return NT_STATUS_INVALID_HANDLE;
2077
2078         domain_sid = info->sid;
2079
2080         sid_split_rid(&domain_sid, &rid);
2081
2082         if (!sid_check_is_in_our_domain(&info->sid))
2083                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
2084
2085         DEBUG(5,("_samr_query_userinfo: sid:%s\n", sid_string_static(&info->sid)));
2086
2087         ctr = TALLOC_ZERO_P(p->mem_ctx, SAM_USERINFO_CTR);
2088         if (!ctr)
2089                 return NT_STATUS_NO_MEMORY;
2090
2091         ZERO_STRUCTP(ctr);
2092
2093         /* ok!  user info levels (lots: see MSDEV help), off we go... */
2094         ctr->switch_value = q_u->switch_value;
2095
2096         DEBUG(5,("_samr_query_userinfo: user info level: %d\n", q_u->switch_value));
2097
2098         switch (q_u->switch_value) {
2099         case 7:
2100                 ctr->info.id7 = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_7);
2101                 if (ctr->info.id7 == NULL)
2102                         return NT_STATUS_NO_MEMORY;
2103
2104                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_7(p->mem_ctx, ctr->info.id7, &info->sid)))
2105                         return r_u->status;
2106                 break;
2107         case 9:
2108                 ctr->info.id9 = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_9);
2109                 if (ctr->info.id9 == NULL)
2110                         return NT_STATUS_NO_MEMORY;
2111
2112                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_9(p->mem_ctx, ctr->info.id9, &info->sid)))
2113                         return r_u->status;
2114                 break;
2115         case 16:
2116                 ctr->info.id16 = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_16);
2117                 if (ctr->info.id16 == NULL)
2118                         return NT_STATUS_NO_MEMORY;
2119
2120                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_16(p->mem_ctx, ctr->info.id16, &info->sid)))
2121                         return r_u->status;
2122                 break;
2123
2124         case 18:
2125                 ctr->info.id18 = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_18);
2126                 if (ctr->info.id18 == NULL)
2127                         return NT_STATUS_NO_MEMORY;
2128
2129                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_18(p, p->mem_ctx, ctr->info.id18, &info->sid)))
2130                         return r_u->status;
2131                 break;
2132                 
2133         case 20:
2134                 ctr->info.id20 = TALLOC_ZERO_P(p->mem_ctx,SAM_USER_INFO_20);
2135                 if (ctr->info.id20 == NULL)
2136                         return NT_STATUS_NO_MEMORY;
2137                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_20(p->mem_ctx, ctr->info.id20, &info->sid)))
2138                         return r_u->status;
2139                 break;
2140
2141         case 21:
2142                 ctr->info.id21 = TALLOC_ZERO_P(p->mem_ctx,SAM_USER_INFO_21);
2143                 if (ctr->info.id21 == NULL)
2144                         return NT_STATUS_NO_MEMORY;
2145                 if (!NT_STATUS_IS_OK(r_u->status = get_user_info_21(p->mem_ctx, ctr->info.id21, 
2146                                                                     &info->sid, &domain_sid)))
2147                         return r_u->status;
2148                 break;
2149
2150         default:
2151                 return NT_STATUS_INVALID_INFO_CLASS;
2152         }
2153
2154         init_samr_r_query_userinfo(r_u, ctr, r_u->status);
2155
2156         DEBUG(5,("_samr_query_userinfo: %d\n", __LINE__));
2157         
2158         return r_u->status;
2159 }
2160
2161 /*******************************************************************
2162  samr_reply_query_usergroups
2163  ********************************************************************/
2164
2165 NTSTATUS _samr_query_usergroups(pipes_struct *p, SAMR_Q_QUERY_USERGROUPS *q_u, SAMR_R_QUERY_USERGROUPS *r_u)
2166 {
2167         struct samu *sam_pass=NULL;
2168         DOM_SID  sid;
2169         DOM_SID *sids;
2170         DOM_GID dom_gid;
2171         DOM_GID *gids = NULL;
2172         uint32 primary_group_rid;
2173         size_t num_groups = 0;
2174         gid_t *unix_gids;
2175         size_t i, num_gids;
2176         uint32 acc_granted;
2177         bool ret;
2178         NTSTATUS result;
2179         bool success = False;
2180
2181         /*
2182          * from the SID in the request:
2183          * we should send back the list of DOMAIN GROUPS
2184          * the user is a member of
2185          *
2186          * and only the DOMAIN GROUPS
2187          * no ALIASES !!! neither aliases of the domain
2188          * nor aliases of the builtin SID
2189          *
2190          * JFM, 12/2/2001
2191          */
2192
2193         r_u->status = NT_STATUS_OK;
2194
2195         DEBUG(5,("_samr_query_usergroups: %d\n", __LINE__));
2196
2197         /* find the policy handle.  open a policy on it. */
2198         if (!get_lsa_policy_samr_sid(p, &q_u->pol, &sid, &acc_granted, NULL))
2199                 return NT_STATUS_INVALID_HANDLE;
2200         
2201         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, SA_RIGHT_USER_GET_GROUPS, "_samr_query_usergroups"))) {
2202                 return r_u->status;
2203         }
2204
2205         if (!sid_check_is_in_our_domain(&sid))
2206                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
2207
2208         if ( !(sam_pass = samu_new( p->mem_ctx )) ) {
2209                 return NT_STATUS_NO_MEMORY;
2210         }
2211
2212         become_root();
2213         ret = pdb_getsampwsid(sam_pass, &sid);
2214         unbecome_root();
2215
2216         if (!ret) {
2217                 DEBUG(10, ("pdb_getsampwsid failed for %s\n",
2218                            sid_string_static(&sid)));
2219                 return NT_STATUS_NO_SUCH_USER;
2220         }
2221
2222         sids = NULL;
2223
2224         /* make both calls inside the root block */
2225         become_root();
2226         result = pdb_enum_group_memberships(p->mem_ctx, sam_pass,
2227                                             &sids, &unix_gids, &num_groups);
2228         if ( NT_STATUS_IS_OK(result) ) {
2229                 success = sid_peek_check_rid(get_global_sam_sid(), 
2230                                              pdb_get_group_sid(sam_pass),
2231                                              &primary_group_rid);
2232         }
2233         unbecome_root();
2234
2235         if (!NT_STATUS_IS_OK(result)) {
2236                 DEBUG(10, ("pdb_enum_group_memberships failed for %s\n",
2237                            sid_string_static(&sid)));
2238                 return result;
2239         }
2240
2241         if ( !success ) {
2242                 DEBUG(5, ("Group sid %s for user %s not in our domain\n",
2243                           sid_string_static(pdb_get_group_sid(sam_pass)),
2244                           pdb_get_username(sam_pass)));
2245                 TALLOC_FREE(sam_pass);
2246                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2247         }
2248
2249         gids = NULL;
2250         num_gids = 0;
2251
2252         dom_gid.attr = (SE_GROUP_MANDATORY|SE_GROUP_ENABLED_BY_DEFAULT|
2253                         SE_GROUP_ENABLED);
2254         dom_gid.g_rid = primary_group_rid;
2255         ADD_TO_ARRAY(p->mem_ctx, DOM_GID, dom_gid, &gids, &num_gids);
2256
2257         for (i=0; i<num_groups; i++) {
2258
2259                 if (!sid_peek_check_rid(get_global_sam_sid(),
2260                                         &(sids[i]), &dom_gid.g_rid)) {
2261                         DEBUG(10, ("Found sid %s not in our domain\n",
2262                                    sid_string_static(&sids[i])));
2263                         continue;
2264                 }
2265
2266                 if (dom_gid.g_rid == primary_group_rid) {
2267                         /* We added the primary group directly from the
2268                          * sam_account. The other SIDs are unique from
2269                          * enum_group_memberships */
2270                         continue;
2271                 }
2272
2273                 ADD_TO_ARRAY(p->mem_ctx, DOM_GID, dom_gid, &gids, &num_gids);
2274         }
2275         
2276         /* construct the response.  lkclXXXX: gids are not copied! */
2277         init_samr_r_query_usergroups(r_u, num_gids, gids, r_u->status);
2278         
2279         DEBUG(5,("_samr_query_usergroups: %d\n", __LINE__));
2280         
2281         return r_u->status;
2282 }
2283
2284 /*******************************************************************
2285  _samr_query_domain_info
2286  ********************************************************************/
2287
2288 NTSTATUS _samr_query_domain_info(pipes_struct *p, 
2289                                  SAMR_Q_QUERY_DOMAIN_INFO *q_u, 
2290                                  SAMR_R_QUERY_DOMAIN_INFO *r_u)
2291 {
2292         struct samr_info *info = NULL;
2293         SAM_UNK_CTR *ctr;
2294         uint32 min_pass_len,pass_hist,password_properties;
2295         time_t u_expire, u_min_age;
2296         NTTIME nt_expire, nt_min_age;
2297
2298         time_t u_lock_duration, u_reset_time;
2299         NTTIME nt_lock_duration, nt_reset_time;
2300         uint32 lockout;
2301         time_t u_logout;
2302         NTTIME nt_logout;
2303
2304         uint32 account_policy_temp;
2305
2306         time_t seq_num;
2307         uint32 server_role;
2308
2309         uint32 num_users=0, num_groups=0, num_aliases=0;
2310
2311         if ((ctr = TALLOC_ZERO_P(p->mem_ctx, SAM_UNK_CTR)) == NULL) {
2312                 return NT_STATUS_NO_MEMORY;
2313         }
2314
2315         ZERO_STRUCTP(ctr);
2316
2317         r_u->status = NT_STATUS_OK;
2318         
2319         DEBUG(5,("_samr_query_domain_info: %d\n", __LINE__));
2320         
2321         /* find the policy handle.  open a policy on it. */
2322         if (!find_policy_by_hnd(p, &q_u->domain_pol, (void **)(void *)&info)) {
2323                 return NT_STATUS_INVALID_HANDLE;
2324         }
2325         
2326         switch (q_u->switch_value) {
2327                 case 0x01:
2328                         
2329                         become_root();
2330
2331                         /* AS ROOT !!! */
2332
2333                         pdb_get_account_policy(AP_MIN_PASSWORD_LEN, &account_policy_temp);
2334                         min_pass_len = account_policy_temp;
2335
2336                         pdb_get_account_policy(AP_PASSWORD_HISTORY, &account_policy_temp);
2337                         pass_hist = account_policy_temp;
2338
2339                         pdb_get_account_policy(AP_USER_MUST_LOGON_TO_CHG_PASS, &account_policy_temp);
2340                         password_properties = account_policy_temp;
2341
2342                         pdb_get_account_policy(AP_MAX_PASSWORD_AGE, &account_policy_temp);
2343                         u_expire = account_policy_temp;
2344
2345                         pdb_get_account_policy(AP_MIN_PASSWORD_AGE, &account_policy_temp);
2346                         u_min_age = account_policy_temp;
2347
2348                         /* !AS ROOT */
2349                         
2350                         unbecome_root();
2351
2352                         unix_to_nt_time_abs(&nt_expire, u_expire);
2353                         unix_to_nt_time_abs(&nt_min_age, u_min_age);
2354
2355                         init_unk_info1(&ctr->info.inf1, (uint16)min_pass_len, (uint16)pass_hist, 
2356                                        password_properties, nt_expire, nt_min_age);
2357                         break;
2358                 case 0x02:
2359
2360                         become_root();
2361
2362                         /* AS ROOT !!! */
2363
2364                         num_users = count_sam_users(info->disp_info, ACB_NORMAL);
2365                         num_groups = count_sam_groups(info->disp_info);
2366                         num_aliases = count_sam_aliases(info->disp_info);
2367
2368                         pdb_get_account_policy(AP_TIME_TO_LOGOUT, &account_policy_temp);
2369                         u_logout = account_policy_temp;
2370
2371                         unix_to_nt_time_abs(&nt_logout, u_logout);
2372
2373                         if (!pdb_get_seq_num(&seq_num))
2374                                 seq_num = time(NULL);
2375
2376                         /* !AS ROOT */
2377                         
2378                         unbecome_root();
2379
2380                         server_role = ROLE_DOMAIN_PDC;
2381                         if (lp_server_role() == ROLE_DOMAIN_BDC)
2382                                 server_role = ROLE_DOMAIN_BDC;
2383
2384                         init_unk_info2(&ctr->info.inf2, lp_serverstring(), lp_workgroup(), global_myname(), seq_num, 
2385                                        num_users, num_groups, num_aliases, nt_logout, server_role);
2386                         break;
2387                 case 0x03:
2388
2389                         become_root();
2390
2391                         /* AS ROOT !!! */
2392
2393                         {
2394                                 uint32 ul;
2395                                 pdb_get_account_policy(AP_TIME_TO_LOGOUT, &ul);
2396                                 u_logout = (time_t)ul;
2397                         }
2398
2399                         /* !AS ROOT */
2400                         
2401                         unbecome_root();
2402
2403                         unix_to_nt_time_abs(&nt_logout, u_logout);
2404                         
2405                         init_unk_info3(&ctr->info.inf3, nt_logout);
2406                         break;
2407                 case 0x04:
2408                         init_unk_info4(&ctr->info.inf4, lp_serverstring());
2409                         break;
2410                 case 0x05:
2411                         init_unk_info5(&ctr->info.inf5, get_global_sam_name());
2412                         break;
2413                 case 0x06:
2414                         /* NT returns its own name when a PDC. win2k and later
2415                          * only the name of the PDC if itself is a BDC (samba4
2416                          * idl) */
2417                         init_unk_info6(&ctr->info.inf6, global_myname());
2418                         break;
2419                 case 0x07:
2420                         server_role = ROLE_DOMAIN_PDC;
2421                         if (lp_server_role() == ROLE_DOMAIN_BDC)
2422                                 server_role = ROLE_DOMAIN_BDC;
2423
2424                         init_unk_info7(&ctr->info.inf7, server_role);
2425                         break;
2426                 case 0x08:
2427
2428                         become_root();
2429
2430                         /* AS ROOT !!! */
2431
2432                         if (!pdb_get_seq_num(&seq_num)) {
2433                                 seq_num = time(NULL);
2434                         }
2435
2436                         /* !AS ROOT */
2437                         
2438                         unbecome_root();
2439
2440                         init_unk_info8(&ctr->info.inf8, (uint32) seq_num);
2441                         break;
2442                 case 0x0c:
2443
2444                         become_root();
2445
2446                         /* AS ROOT !!! */
2447
2448                         pdb_get_account_policy(AP_LOCK_ACCOUNT_DURATION, &account_policy_temp);
2449                         u_lock_duration = account_policy_temp;
2450                         if (u_lock_duration != -1) {
2451                                 u_lock_duration *= 60;
2452                         }
2453
2454                         pdb_get_account_policy(AP_RESET_COUNT_TIME, &account_policy_temp);
2455                         u_reset_time = account_policy_temp * 60;
2456
2457                         pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &account_policy_temp);
2458                         lockout = account_policy_temp;
2459
2460                         /* !AS ROOT */
2461                         
2462                         unbecome_root();
2463
2464                         unix_to_nt_time_abs(&nt_lock_duration, u_lock_duration);
2465                         unix_to_nt_time_abs(&nt_reset_time, u_reset_time);
2466         
2467                         init_unk_info12(&ctr->info.inf12, nt_lock_duration, nt_reset_time, (uint16)lockout);
2468                         break;
2469                 default:
2470                         return NT_STATUS_INVALID_INFO_CLASS;
2471                 }
2472         
2473
2474         init_samr_r_query_domain_info(r_u, q_u->switch_value, ctr, NT_STATUS_OK);
2475         
2476         DEBUG(5,("_samr_query_domain_info: %d\n", __LINE__));
2477         
2478         return r_u->status;
2479 }
2480
2481 /* W2k3 seems to use the same check for all 3 objects that can be created via
2482  * SAMR, if you try to create for example "Dialup" as an alias it says
2483  * "NT_STATUS_USER_EXISTS". This is racy, but we can't really lock the user
2484  * database. */
2485
2486 static NTSTATUS can_create(TALLOC_CTX *mem_ctx, const char *new_name)
2487 {
2488         enum lsa_SidType type;
2489         bool result;
2490
2491         DEBUG(10, ("Checking whether [%s] can be created\n", new_name));
2492
2493         become_root();
2494         /* Lookup in our local databases (only LOOKUP_NAME_ISOLATED set)
2495          * whether the name already exists */
2496         result = lookup_name(mem_ctx, new_name, LOOKUP_NAME_ISOLATED,
2497                              NULL, NULL, NULL, &type);
2498         unbecome_root();
2499
2500         if (!result) {
2501                 DEBUG(10, ("%s does not exist, can create it\n", new_name));
2502                 return NT_STATUS_OK;
2503         }
2504
2505         DEBUG(5, ("trying to create %s, exists as %s\n",
2506                   new_name, sid_type_lookup(type)));
2507
2508         if (type == SID_NAME_DOM_GRP) {
2509                 return NT_STATUS_GROUP_EXISTS;
2510         }
2511         if (type == SID_NAME_ALIAS) {
2512                 return NT_STATUS_ALIAS_EXISTS;
2513         }
2514
2515         /* Yes, the default is NT_STATUS_USER_EXISTS */
2516         return NT_STATUS_USER_EXISTS;
2517 }
2518
2519 /*******************************************************************
2520  _samr_create_user
2521  Create an account, can be either a normal user or a machine.
2522  This funcion will need to be updated for bdc/domain trusts.
2523  ********************************************************************/
2524
2525 NTSTATUS _samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u,
2526                            SAMR_R_CREATE_USER *r_u)
2527 {
2528         char *account;
2529         DOM_SID sid;
2530         POLICY_HND dom_pol = q_u->domain_pol;
2531         uint16 acb_info = q_u->acb_info;
2532         POLICY_HND *user_pol = &r_u->user_pol;
2533         struct samr_info *info = NULL;
2534         NTSTATUS nt_status;
2535         uint32 acc_granted;
2536         SEC_DESC *psd;
2537         size_t    sd_size;
2538         /* check this, when giving away 'add computer to domain' privs */
2539         uint32    des_access = GENERIC_RIGHTS_USER_ALL_ACCESS;
2540         bool can_add_account = False;
2541         SE_PRIV se_rights;
2542         DISP_INFO *disp_info = NULL;
2543
2544         /* Get the domain SID stored in the domain policy */
2545         if (!get_lsa_policy_samr_sid(p, &dom_pol, &sid, &acc_granted,
2546                                      &disp_info))
2547                 return NT_STATUS_INVALID_HANDLE;
2548
2549         nt_status = access_check_samr_function(acc_granted,
2550                                                SA_RIGHT_DOMAIN_CREATE_USER,
2551                                                "_samr_create_user");
2552         if (!NT_STATUS_IS_OK(nt_status)) {
2553                 return nt_status;
2554         }
2555
2556         if (!(acb_info == ACB_NORMAL || acb_info == ACB_DOMTRUST ||
2557               acb_info == ACB_WSTRUST || acb_info == ACB_SVRTRUST)) { 
2558                 /* Match Win2k, and return NT_STATUS_INVALID_PARAMETER if 
2559                    this parameter is not an account type */
2560                 return NT_STATUS_INVALID_PARAMETER;
2561         }
2562
2563         account = rpcstr_pull_unistr2_talloc(p->mem_ctx, &q_u->uni_name);
2564         if (account == NULL) {
2565                 return NT_STATUS_NO_MEMORY;
2566         }
2567
2568         nt_status = can_create(p->mem_ctx, account);
2569         if (!NT_STATUS_IS_OK(nt_status)) {
2570                 return nt_status;
2571         }
2572
2573         /* determine which user right we need to check based on the acb_info */
2574         
2575         if ( acb_info & ACB_WSTRUST )
2576         {
2577                 se_priv_copy( &se_rights, &se_machine_account );
2578                 can_add_account = user_has_privileges(
2579                         p->pipe_user.nt_user_token, &se_rights );
2580         } 
2581         /* usrmgr.exe (and net rpc trustdom grant) creates a normal user 
2582            account for domain trusts and changes the ACB flags later */
2583         else if ( acb_info & ACB_NORMAL &&
2584                   (account[strlen(account)-1] != '$') )
2585         {
2586                 se_priv_copy( &se_rights, &se_add_users );
2587                 can_add_account = user_has_privileges(
2588                         p->pipe_user.nt_user_token, &se_rights );
2589         } 
2590         else    /* implicit assumption of a BDC or domain trust account here
2591                  * (we already check the flags earlier) */
2592         {
2593                 if ( lp_enable_privileges() ) {
2594                         /* only Domain Admins can add a BDC or domain trust */
2595                         se_priv_copy( &se_rights, &se_priv_none );
2596                         can_add_account = nt_token_check_domain_rid(
2597                                 p->pipe_user.nt_user_token,
2598                                 DOMAIN_GROUP_RID_ADMINS );
2599                 }
2600         }
2601                 
2602         DEBUG(5, ("_samr_create_user: %s can add this account : %s\n",
2603                   uidtoname(p->pipe_user.ut.uid),
2604                   can_add_account ? "True":"False" ));
2605                 
2606         /********** BEGIN Admin BLOCK **********/
2607
2608         if ( can_add_account )
2609                 become_root();
2610
2611         nt_status = pdb_create_user(p->mem_ctx, account, acb_info,
2612                                     &r_u->user_rid);
2613
2614         if ( can_add_account )
2615                 unbecome_root();
2616
2617         /********** END Admin BLOCK **********/
2618         
2619         /* now check for failure */
2620         
2621         if ( !NT_STATUS_IS_OK(nt_status) )
2622                 return nt_status;
2623                         
2624         /* Get the user's SID */
2625
2626         sid_compose(&sid, get_global_sam_sid(), r_u->user_rid);
2627         
2628         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &usr_generic_mapping,
2629                             &sid, SAMR_USR_RIGHTS_WRITE_PW);
2630         se_map_generic(&des_access, &usr_generic_mapping);
2631         
2632         nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
2633                 &se_rights, GENERIC_RIGHTS_USER_WRITE, des_access, 
2634                 &acc_granted, "_samr_create_user");
2635                 
2636         if ( !NT_STATUS_IS_OK(nt_status) ) {
2637                 return nt_status;
2638         }
2639
2640         /* associate the user's SID with the new handle. */
2641         if ((info = get_samr_info_by_sid(&sid)) == NULL) {
2642                 return NT_STATUS_NO_MEMORY;
2643         }
2644
2645         ZERO_STRUCTP(info);
2646         info->sid = sid;
2647         info->acc_granted = acc_granted;
2648
2649         /* get a (unique) handle.  open a policy on it. */
2650         if (!create_policy_hnd(p, user_pol, free_samr_info, (void *)info)) {
2651                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2652         }
2653
2654         /* After a "set" ensure we have no cached display info. */
2655         force_flush_samr_cache(info->disp_info);
2656
2657         r_u->access_granted = acc_granted;
2658
2659         return NT_STATUS_OK;
2660 }
2661
2662 /*******************************************************************
2663  samr_reply_connect_anon
2664  ********************************************************************/
2665
2666 NTSTATUS _samr_connect_anon(pipes_struct *p, SAMR_Q_CONNECT_ANON *q_u, SAMR_R_CONNECT_ANON *r_u)
2667 {
2668         struct samr_info *info = NULL;
2669         uint32    des_access = q_u->access_mask;
2670
2671         /* Access check */
2672
2673         if (!pipe_access_check(p)) {
2674                 DEBUG(3, ("access denied to samr_connect_anon\n"));
2675                 r_u->status = NT_STATUS_ACCESS_DENIED;
2676                 return r_u->status;
2677         }
2678
2679         /* set up the SAMR connect_anon response */
2680
2681         r_u->status = NT_STATUS_OK;
2682
2683         /* associate the user's SID with the new handle. */
2684         if ((info = get_samr_info_by_sid(NULL)) == NULL)
2685                 return NT_STATUS_NO_MEMORY;
2686
2687         /* don't give away the farm but this is probably ok.  The SA_RIGHT_SAM_ENUM_DOMAINS
2688            was observed from a win98 client trying to enumerate users (when configured  
2689            user level access control on shares)   --jerry */
2690            
2691         if (des_access == MAXIMUM_ALLOWED_ACCESS) {
2692                 /* Map to max possible knowing we're filtered below. */
2693                 des_access = GENERIC_ALL_ACCESS;
2694         }
2695
2696         se_map_generic( &des_access, &sam_generic_mapping );
2697         info->acc_granted = des_access & (SA_RIGHT_SAM_ENUM_DOMAINS|SA_RIGHT_SAM_OPEN_DOMAIN);
2698         
2699         info->status = q_u->unknown_0;
2700
2701         /* get a (unique) handle.  open a policy on it. */
2702         if (!create_policy_hnd(p, &r_u->connect_pol, free_samr_info, (void *)info))
2703                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2704
2705         return r_u->status;
2706 }
2707
2708 /*******************************************************************
2709  samr_reply_connect
2710  ********************************************************************/
2711
2712 NTSTATUS _samr_connect(pipes_struct *p, SAMR_Q_CONNECT *q_u, SAMR_R_CONNECT *r_u)
2713 {
2714         struct samr_info *info = NULL;
2715         SEC_DESC *psd = NULL;
2716         uint32    acc_granted;
2717         uint32    des_access = q_u->access_mask;
2718         NTSTATUS  nt_status;
2719         size_t    sd_size;
2720
2721
2722         DEBUG(5,("_samr_connect: %d\n", __LINE__));
2723
2724         /* Access check */
2725
2726         if (!pipe_access_check(p)) {
2727                 DEBUG(3, ("access denied to samr_connect\n"));
2728                 r_u->status = NT_STATUS_ACCESS_DENIED;
2729                 return r_u->status;
2730         }
2731
2732         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &sam_generic_mapping, NULL, 0);
2733         se_map_generic(&des_access, &sam_generic_mapping);
2734         
2735         nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
2736                 NULL, 0, des_access, &acc_granted, "_samr_connect");
2737         
2738         if ( !NT_STATUS_IS_OK(nt_status) ) 
2739                 return nt_status;
2740
2741         r_u->status = NT_STATUS_OK;
2742
2743         /* associate the user's SID and access granted with the new handle. */
2744         if ((info = get_samr_info_by_sid(NULL)) == NULL)
2745                 return NT_STATUS_NO_MEMORY;
2746
2747         info->acc_granted = acc_granted;
2748         info->status = q_u->access_mask;
2749
2750         /* get a (unique) handle.  open a policy on it. */
2751         if (!create_policy_hnd(p, &r_u->connect_pol, free_samr_info, (void *)info))
2752                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2753
2754         DEBUG(5,("_samr_connect: %d\n", __LINE__));
2755
2756         return r_u->status;
2757 }
2758
2759 /*******************************************************************
2760  samr_connect4
2761  ********************************************************************/
2762
2763 NTSTATUS _samr_connect4(pipes_struct *p, SAMR_Q_CONNECT4 *q_u, SAMR_R_CONNECT4 *r_u)
2764 {
2765         struct samr_info *info = NULL;
2766         SEC_DESC *psd = NULL;
2767         uint32    acc_granted;
2768         uint32    des_access = q_u->access_mask;
2769         NTSTATUS  nt_status;
2770         size_t    sd_size;
2771
2772
2773         DEBUG(5,("_samr_connect4: %d\n", __LINE__));
2774
2775         /* Access check */
2776
2777         if (!pipe_access_check(p)) {
2778                 DEBUG(3, ("access denied to samr_connect4\n"));
2779                 r_u->status = NT_STATUS_ACCESS_DENIED;
2780                 return r_u->status;
2781         }
2782
2783         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &sam_generic_mapping, NULL, 0);
2784         se_map_generic(&des_access, &sam_generic_mapping);
2785         
2786         nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
2787                 NULL, 0, des_access, &acc_granted, "_samr_connect4");
2788         
2789         if ( !NT_STATUS_IS_OK(nt_status) ) 
2790                 return nt_status;
2791
2792         r_u->status = NT_STATUS_OK;
2793
2794         /* associate the user's SID and access granted with the new handle. */
2795         if ((info = get_samr_info_by_sid(NULL)) == NULL)
2796                 return NT_STATUS_NO_MEMORY;
2797
2798         info->acc_granted = acc_granted;
2799         info->status = q_u->access_mask;
2800
2801         /* get a (unique) handle.  open a policy on it. */
2802         if (!create_policy_hnd(p, &r_u->connect_pol, free_samr_info, (void *)info))
2803                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2804
2805         DEBUG(5,("_samr_connect: %d\n", __LINE__));
2806
2807         return r_u->status;
2808 }
2809
2810 /*******************************************************************
2811  samr_connect5
2812  ********************************************************************/
2813
2814 NTSTATUS _samr_connect5(pipes_struct *p, SAMR_Q_CONNECT5 *q_u, SAMR_R_CONNECT5 *r_u)
2815 {
2816         struct samr_info *info = NULL;
2817         SEC_DESC *psd = NULL;
2818         uint32    acc_granted;
2819         uint32    des_access = q_u->access_mask;
2820         NTSTATUS  nt_status;
2821         POLICY_HND pol;
2822         size_t    sd_size;
2823
2824
2825         DEBUG(5,("_samr_connect5: %d\n", __LINE__));
2826
2827         ZERO_STRUCTP(r_u);
2828
2829         /* Access check */
2830
2831         if (!pipe_access_check(p)) {
2832                 DEBUG(3, ("access denied to samr_connect5\n"));
2833                 r_u->status = NT_STATUS_ACCESS_DENIED;
2834                 return r_u->status;
2835         }
2836
2837         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &sam_generic_mapping, NULL, 0);
2838         se_map_generic(&des_access, &sam_generic_mapping);
2839         
2840         nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
2841                 NULL, 0, des_access, &acc_granted, "_samr_connect5");
2842         
2843         if ( !NT_STATUS_IS_OK(nt_status) ) 
2844                 return nt_status;
2845
2846         /* associate the user's SID and access granted with the new handle. */
2847         if ((info = get_samr_info_by_sid(NULL)) == NULL)
2848                 return NT_STATUS_NO_MEMORY;
2849
2850         info->acc_granted = acc_granted;
2851         info->status = q_u->access_mask;
2852
2853         /* get a (unique) handle.  open a policy on it. */
2854         if (!create_policy_hnd(p, &pol, free_samr_info, (void *)info))
2855                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2856
2857         DEBUG(5,("_samr_connect: %d\n", __LINE__));
2858
2859         init_samr_r_connect5(r_u, &pol, NT_STATUS_OK);
2860
2861         return r_u->status;
2862 }
2863
2864 /**********************************************************************
2865  api_samr_lookup_domain
2866  **********************************************************************/
2867
2868 NTSTATUS _samr_lookup_domain(pipes_struct *p, SAMR_Q_LOOKUP_DOMAIN *q_u, SAMR_R_LOOKUP_DOMAIN *r_u)
2869 {
2870         struct samr_info *info;
2871         fstring domain_name;
2872         DOM_SID sid;
2873
2874         r_u->status = NT_STATUS_OK;
2875
2876         if (!find_policy_by_hnd(p, &q_u->connect_pol, (void**)(void *)&info))
2877                 return NT_STATUS_INVALID_HANDLE;
2878
2879         /* win9x user manager likes to use SA_RIGHT_SAM_ENUM_DOMAINS here.  
2880            Reverted that change so we will work with RAS servers again */
2881
2882         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(info->acc_granted, 
2883                 SA_RIGHT_SAM_OPEN_DOMAIN, "_samr_lookup_domain"))) 
2884         {
2885                 return r_u->status;
2886         }
2887
2888         rpcstr_pull(domain_name, q_u->uni_domain.buffer, sizeof(domain_name), q_u->uni_domain.uni_str_len*2, 0);
2889
2890         ZERO_STRUCT(sid);
2891
2892         if (strequal(domain_name, builtin_domain_name())) {
2893                 sid_copy(&sid, &global_sid_Builtin);
2894         } else {
2895                 if (!secrets_fetch_domain_sid(domain_name, &sid)) {
2896                         r_u->status = NT_STATUS_NO_SUCH_DOMAIN;
2897                 }
2898         }
2899
2900         DEBUG(2,("Returning domain sid for domain %s -> %s\n", domain_name, sid_string_static(&sid)));
2901
2902         init_samr_r_lookup_domain(r_u, &sid, r_u->status);
2903
2904         return r_u->status;
2905 }
2906
2907 /******************************************************************
2908 makes a SAMR_R_ENUM_DOMAINS structure.
2909 ********************************************************************/
2910
2911 static bool make_enum_domains(TALLOC_CTX *ctx, SAM_ENTRY **pp_sam,
2912                         UNISTR2 **pp_uni_name, uint32 num_sam_entries, fstring doms[])
2913 {
2914         uint32 i;
2915         SAM_ENTRY *sam;
2916         UNISTR2 *uni_name;
2917
2918         DEBUG(5, ("make_enum_domains\n"));
2919
2920         *pp_sam = NULL;
2921         *pp_uni_name = NULL;
2922
2923         if (num_sam_entries == 0)
2924                 return True;
2925
2926         sam = TALLOC_ZERO_ARRAY(ctx, SAM_ENTRY, num_sam_entries);
2927         uni_name = TALLOC_ZERO_ARRAY(ctx, UNISTR2, num_sam_entries);
2928
2929         if (sam == NULL || uni_name == NULL)
2930                 return False;
2931
2932         for (i = 0; i < num_sam_entries; i++) {
2933                 init_unistr2(&uni_name[i], doms[i], UNI_FLAGS_NONE);
2934                 init_sam_entry(&sam[i], &uni_name[i], 0);
2935         }
2936
2937         *pp_sam = sam;
2938         *pp_uni_name = uni_name;
2939
2940         return True;
2941 }
2942
2943 /**********************************************************************
2944  api_samr_enum_domains
2945  **********************************************************************/
2946
2947 NTSTATUS _samr_enum_domains(pipes_struct *p, SAMR_Q_ENUM_DOMAINS *q_u, SAMR_R_ENUM_DOMAINS *r_u)
2948 {
2949         struct samr_info *info;
2950         uint32 num_entries = 2;
2951         fstring dom[2];
2952         const char *name;
2953
2954         r_u->status = NT_STATUS_OK;
2955         
2956         if (!find_policy_by_hnd(p, &q_u->pol, (void**)(void *)&info))
2957                 return NT_STATUS_INVALID_HANDLE;
2958         
2959         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(info->acc_granted, SA_RIGHT_SAM_ENUM_DOMAINS, "_samr_enum_domains"))) {
2960                 return r_u->status;
2961         }
2962
2963         name = get_global_sam_name();
2964
2965         fstrcpy(dom[0],name);
2966         strupper_m(dom[0]);
2967         fstrcpy(dom[1],"Builtin");
2968
2969         if (!make_enum_domains(p->mem_ctx, &r_u->sam, &r_u->uni_dom_name, num_entries, dom))
2970                 return NT_STATUS_NO_MEMORY;
2971
2972         init_samr_r_enum_domains(r_u, q_u->start_idx + num_entries, num_entries);
2973
2974         return r_u->status;
2975 }
2976
2977 /*******************************************************************
2978  api_samr_open_alias
2979  ********************************************************************/
2980
2981 NTSTATUS _samr_open_alias(pipes_struct *p, SAMR_Q_OPEN_ALIAS *q_u, SAMR_R_OPEN_ALIAS *r_u)
2982 {
2983         DOM_SID sid;
2984         POLICY_HND domain_pol = q_u->dom_pol;
2985         uint32 alias_rid = q_u->rid_alias;
2986         POLICY_HND *alias_pol = &r_u->pol;
2987         struct    samr_info *info = NULL;
2988         SEC_DESC *psd = NULL;
2989         uint32    acc_granted;
2990         uint32    des_access = q_u->access_mask;
2991         size_t    sd_size;
2992         NTSTATUS  status;
2993         SE_PRIV se_rights;
2994
2995         r_u->status = NT_STATUS_OK;
2996
2997         /* find the domain policy and get the SID / access bits stored in the domain policy */
2998         
2999         if ( !get_lsa_policy_samr_sid(p, &domain_pol, &sid, &acc_granted, NULL) )
3000                 return NT_STATUS_INVALID_HANDLE;
3001         
3002         status = access_check_samr_function(acc_granted, 
3003                 SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_open_alias");
3004                 
3005         if ( !NT_STATUS_IS_OK(status) ) 
3006                 return status;
3007
3008         /* append the alias' RID to it */
3009         
3010         if (!sid_append_rid(&sid, alias_rid))
3011                 return NT_STATUS_NO_SUCH_ALIAS;
3012                 
3013         /*check if access can be granted as requested by client. */
3014         
3015         make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &ali_generic_mapping, NULL, 0);
3016         se_map_generic(&des_access,&ali_generic_mapping);
3017         
3018         se_priv_copy( &se_rights, &se_add_users );
3019         
3020         
3021         status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
3022                 &se_rights, GENERIC_RIGHTS_ALIAS_WRITE, des_access, 
3023                 &acc_granted, "_samr_open_alias");
3024                 
3025         if ( !NT_STATUS_IS_OK(status) )
3026                 return status;
3027
3028         {
3029                 /* Check we actually have the requested alias */
3030                 enum lsa_SidType type;
3031                 bool result;
3032                 gid_t gid;
3033
3034                 become_root();
3035                 result = lookup_sid(NULL, &sid, NULL, NULL, &type);
3036                 unbecome_root();
3037
3038                 if (!result || (type != SID_NAME_ALIAS)) {
3039                         return NT_STATUS_NO_SUCH_ALIAS;
3040                 }
3041
3042                 /* make sure there is a mapping */
3043                 
3044                 if ( !sid_to_gid( &sid, &gid ) ) {
3045                         return NT_STATUS_NO_SUCH_ALIAS;
3046                 }
3047
3048         }
3049
3050         /* associate the alias SID with the new handle. */
3051         if ((info = get_samr_info_by_sid(&sid)) == NULL)
3052                 return NT_STATUS_NO_MEMORY;
3053                 
3054         info->acc_granted = acc_granted;
3055
3056         /* get a (unique) handle.  open a policy on it. */
3057         if (!create_policy_hnd(p, alias_pol, free_samr_info, (void *)info))
3058                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3059
3060         return r_u->status;
3061 }
3062
3063 /*******************************************************************
3064  set_user_info_7
3065  ********************************************************************/
3066 static NTSTATUS set_user_info_7(TALLOC_CTX *mem_ctx,
3067                                 const SAM_USER_INFO_7 *id7, struct samu *pwd)
3068 {
3069         fstring new_name;
3070         NTSTATUS rc;
3071
3072         if (id7 == NULL) {
3073                 DEBUG(5, ("set_user_info_7: NULL id7\n"));
3074                 TALLOC_FREE(pwd);
3075                 return NT_STATUS_ACCESS_DENIED;
3076         }
3077
3078         if(!rpcstr_pull(new_name, id7->uni_name.buffer, sizeof(new_name), id7->uni_name.uni_str_len*2, 0)) {
3079                 DEBUG(5, ("set_user_info_7: failed to get new username\n"));
3080                 TALLOC_FREE(pwd);
3081                 return NT_STATUS_ACCESS_DENIED;
3082         }
3083
3084         /* check to see if the new username already exists.  Note: we can't
3085            reliably lock all backends, so there is potentially the 
3086            possibility that a user can be created in between this check and
3087            the rename.  The rename should fail, but may not get the
3088            exact same failure status code.  I think this is small enough
3089            of a window for this type of operation and the results are
3090            simply that the rename fails with a slightly different status
3091            code (like UNSUCCESSFUL instead of ALREADY_EXISTS). */
3092
3093         rc = can_create(mem_ctx, new_name);
3094         if (!NT_STATUS_IS_OK(rc)) {
3095                 return rc;
3096         }
3097
3098         rc = pdb_rename_sam_account(pwd, new_name);
3099
3100         TALLOC_FREE(pwd);
3101         return rc;
3102 }
3103
3104 /*******************************************************************
3105  set_user_info_16
3106  ********************************************************************/
3107
3108 static bool set_user_info_16(const SAM_USER_INFO_16 *id16, struct samu *pwd)
3109 {
3110         if (id16 == NULL) {
3111                 DEBUG(5, ("set_user_info_16: NULL id16\n"));
3112                 TALLOC_FREE(pwd);
3113                 return False;
3114         }
3115         
3116         /* FIX ME: check if the value is really changed --metze */
3117         if (!pdb_set_acct_ctrl(pwd, id16->acb_info, PDB_CHANGED)) {
3118                 TALLOC_FREE(pwd);
3119                 return False;
3120         }
3121
3122         if(!NT_STATUS_IS_OK(pdb_update_sam_account(pwd))) {
3123                 TALLOC_FREE(pwd);
3124                 return False;
3125         }
3126
3127         TALLOC_FREE(pwd);
3128
3129         return True;
3130 }
3131
3132 /*******************************************************************
3133  set_user_info_18
3134  ********************************************************************/
3135
3136 static bool set_user_info_18(SAM_USER_INFO_18 *id18, struct samu *pwd)
3137 {
3138
3139         if (id18 == NULL) {
3140                 DEBUG(2, ("set_user_info_18: id18 is NULL\n"));
3141                 TALLOC_FREE(pwd);
3142                 return False;
3143         }
3144  
3145         if (!pdb_set_lanman_passwd (pwd, id18->lm_pwd, PDB_CHANGED)) {
3146                 TALLOC_FREE(pwd);
3147                 return False;
3148         }
3149         if (!pdb_set_nt_passwd     (pwd, id18->nt_pwd, PDB_CHANGED)) {
3150                 TALLOC_FREE(pwd);
3151                 return False;
3152         }
3153         if (!pdb_set_pass_last_set_time (pwd, time(NULL), PDB_CHANGED)) {
3154                 TALLOC_FREE(pwd);
3155                 return False; 
3156         }
3157  
3158         if(!NT_STATUS_IS_OK(pdb_update_sam_account(pwd))) {
3159                 TALLOC_FREE(pwd);
3160                 return False;
3161         }
3162
3163         TALLOC_FREE(pwd);
3164         return True;
3165 }
3166
3167 /*******************************************************************
3168  set_user_info_20
3169  ********************************************************************/
3170
3171 static bool set_user_info_20(SAM_USER_INFO_20 *id20, struct samu *pwd)
3172 {
3173         if (id20 == NULL) {
3174                 DEBUG(5, ("set_user_info_20: NULL id20\n"));
3175                 return False;
3176         }
3177  
3178         copy_id20_to_sam_passwd(pwd, id20);
3179
3180         /* write the change out */
3181         if(!NT_STATUS_IS_OK(pdb_update_sam_account(pwd))) {
3182                 TALLOC_FREE(pwd);
3183                 return False;
3184         }
3185
3186         TALLOC_FREE(pwd);
3187
3188         return True;
3189 }
3190 /*******************************************************************
3191  set_user_info_21
3192  ********************************************************************/
3193
3194 static NTSTATUS set_user_info_21(TALLOC_CTX *mem_ctx, SAM_USER_INFO_21 *id21,
3195                                  struct samu *pwd)
3196 {
3197         fstring new_name;
3198         NTSTATUS status;
3199         
3200         if (id21 == NULL) {
3201                 DEBUG(5, ("set_user_info_21: NULL id21\n"));
3202                 return NT_STATUS_INVALID_PARAMETER;
3203         }
3204
3205         /* we need to separately check for an account rename first */
3206         
3207         if (rpcstr_pull(new_name, id21->uni_user_name.buffer, 
3208                 sizeof(new_name), id21->uni_user_name.uni_str_len*2, 0) 
3209                 && (!strequal(new_name, pdb_get_username(pwd)))) 
3210         {
3211
3212                 /* check to see if the new username already exists.  Note: we can't
3213                    reliably lock all backends, so there is potentially the 
3214                    possibility that a user can be created in between this check and
3215                    the rename.  The rename should fail, but may not get the
3216                    exact same failure status code.  I think this is small enough
3217                    of a window for this type of operation and the results are
3218                    simply that the rename fails with a slightly different status
3219                    code (like UNSUCCESSFUL instead of ALREADY_EXISTS). */
3220
3221                 status = can_create(mem_ctx, new_name);
3222                 if (!NT_STATUS_IS_OK(status)) {
3223                         return status;
3224                 }
3225
3226                 status = pdb_rename_sam_account(pwd, new_name);
3227
3228                 if (!NT_STATUS_IS_OK(status)) {
3229                         DEBUG(0,("set_user_info_21: failed to rename account: %s\n", 
3230                                 nt_errstr(status)));
3231                         TALLOC_FREE(pwd);
3232                         return status;
3233                 }
3234
3235                 /* set the new username so that later 
3236                    functions can work on the new account */
3237                 pdb_set_username(pwd, new_name, PDB_SET);
3238         }
3239
3240         copy_id21_to_sam_passwd(pwd, id21);
3241  
3242         /*
3243          * The funny part about the previous two calls is
3244          * that pwd still has the password hashes from the
3245          * passdb entry.  These have not been updated from
3246          * id21.  I don't know if they need to be set.    --jerry
3247          */
3248  
3249         if ( IS_SAM_CHANGED(pwd, PDB_GROUPSID) ) {
3250                 status = pdb_set_unix_primary_group(mem_ctx, pwd);
3251                 if ( !NT_STATUS_IS_OK(status) ) {
3252                         return status;
3253                 }
3254         }
3255         
3256         /* Don't worry about writing out the user account since the
3257            primary group SID is generated solely from the user's Unix 
3258            primary group. */
3259
3260         /* write the change out */
3261         if(!NT_STATUS_IS_OK(status = pdb_update_sam_account(pwd))) {
3262                 TALLOC_FREE(pwd);
3263                 return status;
3264         }
3265
3266         TALLOC_FREE(pwd);
3267
3268         return NT_STATUS_OK;
3269 }
3270
3271 /*******************************************************************
3272  set_user_info_23
3273  ********************************************************************/
3274
3275 static NTSTATUS set_user_info_23(TALLOC_CTX *mem_ctx, SAM_USER_INFO_23 *id23,
3276                                  struct samu *pwd)
3277 {
3278         char *plaintext_buf = NULL;
3279         uint32 len = 0;
3280         uint16 acct_ctrl;
3281         NTSTATUS status;
3282
3283         if (id23 == NULL) {
3284                 DEBUG(5, ("set_user_info_23: NULL id23\n"));
3285                 return NT_STATUS_INVALID_PARAMETER;
3286         }
3287
3288         DEBUG(5, ("Attempting administrator password change (level 23) for user %s\n",
3289                   pdb_get_username(pwd)));
3290
3291         acct_ctrl = pdb_get_acct_ctrl(pwd);
3292
3293         if (!decode_pw_buffer(mem_ctx,
3294                                 id23->pass,
3295                                 &plaintext_buf,
3296                                 &len,
3297                                 STR_UNICODE)) {
3298                 TALLOC_FREE(pwd);
3299                 return NT_STATUS_INVALID_PARAMETER;
3300         }
3301
3302         if (!pdb_set_plaintext_passwd (pwd, plaintext_buf)) {
3303                 TALLOC_FREE(pwd);
3304                 return NT_STATUS_ACCESS_DENIED;
3305         }
3306
3307         copy_id23_to_sam_passwd(pwd, id23);
3308
3309         /* if it's a trust account, don't update /etc/passwd */
3310         if (    ( (acct_ctrl &  ACB_DOMTRUST) == ACB_DOMTRUST ) ||
3311                 ( (acct_ctrl &  ACB_WSTRUST) ==  ACB_WSTRUST) ||
3312                 ( (acct_ctrl &  ACB_SVRTRUST) ==  ACB_SVRTRUST) ) {
3313                 DEBUG(5, ("Changing trust account.  Not updating /etc/passwd\n"));
3314         } else  {
3315                 /* update the UNIX password */
3316                 if (lp_unix_password_sync() ) {
3317                         struct passwd *passwd;
3318                         if (pdb_get_username(pwd) == NULL) {
3319                                 DEBUG(1, ("chgpasswd: User without name???\n"));
3320                                 TALLOC_FREE(pwd);
3321                                 return NT_STATUS_ACCESS_DENIED;
3322                         }
3323
3324                         if ((passwd = Get_Pwnam(pdb_get_username(pwd))) == NULL) {
3325                                 DEBUG(1, ("chgpasswd: Username does not exist in system !?!\n"));
3326                         }
3327
3328                         if(!chgpasswd(pdb_get_username(pwd), passwd, "", plaintext_buf, True)) {
3329                                 TALLOC_FREE(pwd);
3330                                 return NT_STATUS_ACCESS_DENIED;
3331                         }
3332                 }
3333         }
3334
3335         memset(plaintext_buf, '\0', strlen(plaintext_buf));
3336
3337         if (IS_SAM_CHANGED(pwd, PDB_GROUPSID) &&
3338             (!NT_STATUS_IS_OK(status =  pdb_set_unix_primary_group(mem_ctx,
3339                                                                    pwd)))) {
3340                 TALLOC_FREE(pwd);
3341                 return status;
3342         }
3343
3344         if(!NT_STATUS_IS_OK(status = pdb_update_sam_account(pwd))) {
3345                 TALLOC_FREE(pwd);
3346                 return status;
3347         }
3348
3349         TALLOC_FREE(pwd);
3350
3351         return NT_STATUS_OK;
3352 }
3353
3354 /*******************************************************************
3355  set_user_info_pw
3356  ********************************************************************/
3357
3358 static bool set_user_info_pw(uint8 *pass, struct samu *pwd)
3359 {
3360         uint32 len = 0;
3361         char *plaintext_buf = NULL;
3362         uint32 acct_ctrl;
3363         time_t last_set_time;
3364         enum pdb_value_state last_set_state;
3365
3366         DEBUG(5, ("Attempting administrator password change for user %s\n",
3367                   pdb_get_username(pwd)));
3368
3369         acct_ctrl = pdb_get_acct_ctrl(pwd);
3370         /* we need to know if it's expired, because this is an admin change, not a
3371            user change, so it's still expired when we're done */
3372         last_set_state = pdb_get_init_flags(pwd, PDB_PASSLASTSET);
3373         last_set_time = pdb_get_pass_last_set_time(pwd);
3374
3375         if (!decode_pw_buffer(talloc_tos(),
3376                                 pass,
3377                                 &plaintext_buf,
3378                                 &len,
3379                                 STR_UNICODE)) {
3380                 TALLOC_FREE(pwd);
3381                 return False;
3382         }
3383
3384         if (!pdb_set_plaintext_passwd (pwd, plaintext_buf)) {
3385                 TALLOC_FREE(pwd);
3386                 return False;
3387         }
3388
3389         /* if it's a trust account, don't update /etc/passwd */
3390         if ( ( (acct_ctrl &  ACB_DOMTRUST) == ACB_DOMTRUST ) ||
3391                 ( (acct_ctrl &  ACB_WSTRUST) ==  ACB_WSTRUST) ||
3392                 ( (acct_ctrl &  ACB_SVRTRUST) ==  ACB_SVRTRUST) ) {
3393                 DEBUG(5, ("Changing trust account or non-unix-user password, not updating /etc/passwd\n"));
3394         } else {
3395                 /* update the UNIX password */
3396                 if (lp_unix_password_sync()) {
3397                         struct passwd *passwd;
3398
3399                         if (pdb_get_username(pwd) == NULL) {
3400                                 DEBUG(1, ("chgpasswd: User without name???\n"));
3401                                 TALLOC_FREE(pwd);
3402                                 return False;
3403                         }
3404
3405                         if ((passwd = Get_Pwnam(pdb_get_username(pwd))) == NULL) {
3406                                 DEBUG(1, ("chgpasswd: Username does not exist in system !?!\n"));
3407                         }
3408
3409                         if(!chgpasswd(pdb_get_username(pwd), passwd, "", plaintext_buf, True)) {
3410                                 TALLOC_FREE(pwd);
3411                                 return False;
3412                         }
3413                 }
3414         }
3415
3416         memset(plaintext_buf, '\0', strlen(plaintext_buf));
3417
3418         /* restore last set time as this is an admin change, not a user pw change */
3419         pdb_set_pass_last_set_time (pwd, last_set_time, last_set_state);
3420
3421         DEBUG(5,("set_user_info_pw: pdb_update_pwd()\n"));
3422
3423         /* update the SAMBA password */
3424         if(!NT_STATUS_IS_OK(pdb_update_sam_account(pwd))) {
3425                 TALLOC_FREE(pwd);
3426                 return False;
3427         }
3428
3429         TALLOC_FREE(pwd);
3430
3431         return True;
3432 }
3433
3434 /*******************************************************************
3435  set_user_info_25
3436  ********************************************************************/
3437
3438 static NTSTATUS set_user_info_25(TALLOC_CTX *mem_ctx, SAM_USER_INFO_25 *id25,
3439                                  struct samu *pwd)
3440 {
3441         NTSTATUS status;
3442         
3443         if (id25 == NULL) {
3444                 DEBUG(5, ("set_user_info_25: NULL id25\n"));
3445                 return NT_STATUS_INVALID_PARAMETER;
3446         }
3447
3448         copy_id25_to_sam_passwd(pwd, id25);
3449  
3450         /* write the change out */
3451         if(!NT_STATUS_IS_OK(status = pdb_update_sam_account(pwd))) {
3452                 TALLOC_FREE(pwd);
3453                 return status;
3454         }
3455
3456         /*
3457          * We need to "pdb_update_sam_account" before the unix primary group
3458          * is set, because the idealx scripts would also change the
3459          * sambaPrimaryGroupSid using the ldap replace method. pdb_ldap uses
3460          * the delete explicit / add explicit, which would then fail to find
3461          * the previous primaryGroupSid value.
3462          */
3463
3464         if ( IS_SAM_CHANGED(pwd, PDB_GROUPSID) ) {
3465                 status = pdb_set_unix_primary_group(mem_ctx, pwd);
3466                 if ( !NT_STATUS_IS_OK(status) ) {
3467                         return status;
3468                 }
3469         }
3470         
3471         /* WARNING: No TALLOC_FREE(pwd), we are about to set the password
3472          * hereafter! */
3473
3474         return NT_STATUS_OK;
3475 }
3476
3477 /*******************************************************************
3478  samr_reply_set_userinfo
3479  ********************************************************************/
3480
3481 NTSTATUS _samr_set_userinfo(pipes_struct *p, SAMR_Q_SET_USERINFO *q_u, SAMR_R_SET_USERINFO *r_u)
3482 {
3483         struct samu *pwd = NULL;
3484         DOM_SID sid;
3485         POLICY_HND *pol = &q_u->pol;
3486         uint16 switch_value = q_u->switch_value;
3487         SAM_USERINFO_CTR *ctr = q_u->ctr;
3488         uint32 acc_granted;
3489         uint32 acc_required;
3490         bool ret;
3491         bool has_enough_rights = False;
3492         uint32 acb_info;
3493         DISP_INFO *disp_info = NULL;
3494
3495         DEBUG(5, ("_samr_set_userinfo: %d\n", __LINE__));
3496
3497         r_u->status = NT_STATUS_OK;
3498
3499         /* find the policy handle.  open a policy on it. */
3500         if (!get_lsa_policy_samr_sid(p, pol, &sid, &acc_granted, &disp_info))
3501                 return NT_STATUS_INVALID_HANDLE;
3502
3503         /* This is tricky.  A WinXP domain join sets 
3504           (SA_RIGHT_USER_SET_PASSWORD|SA_RIGHT_USER_SET_ATTRIBUTES|SA_RIGHT_USER_ACCT_FLAGS_EXPIRY)
3505           The MMC lusrmgr plugin includes these perms and more in the SamrOpenUser().  But the 
3506           standard Win32 API calls just ask for SA_RIGHT_USER_SET_PASSWORD in the SamrOpenUser().  
3507           This should be enough for levels 18, 24, 25,& 26.  Info level 23 can set more so 
3508           we'll use the set from the WinXP join as the basis. */
3509         
3510         switch (switch_value) {
3511         case 18:
3512         case 24:
3513         case 25:
3514         case 26:
3515                 acc_required = SA_RIGHT_USER_SET_PASSWORD;
3516                 break;
3517         default:
3518                 acc_required = SA_RIGHT_USER_SET_PASSWORD | SA_RIGHT_USER_SET_ATTRIBUTES | SA_RIGHT_USER_ACCT_FLAGS_EXPIRY;
3519                 break;
3520         }
3521         
3522         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, acc_required, "_samr_set_userinfo"))) {
3523                 return r_u->status;
3524         }
3525
3526         DEBUG(5, ("_samr_set_userinfo: sid:%s, level:%d\n", sid_string_static(&sid), switch_value));
3527
3528         if (ctr == NULL) {
3529                 DEBUG(5, ("_samr_set_userinfo: NULL info level\n"));
3530                 return NT_STATUS_INVALID_INFO_CLASS;
3531         }
3532         
3533         if ( !(pwd = samu_new( NULL )) ) {
3534                 return NT_STATUS_NO_MEMORY;
3535         }
3536         
3537         become_root();
3538         ret = pdb_getsampwsid(pwd, &sid);
3539         unbecome_root();
3540         
3541         if ( !ret ) {
3542                 TALLOC_FREE(pwd);
3543                 return NT_STATUS_NO_SUCH_USER;
3544         }
3545         
3546         /* deal with machine password changes differently from userinfo changes */
3547         /* check to see if we have the sufficient rights */
3548         
3549         acb_info = pdb_get_acct_ctrl(pwd);
3550         if ( acb_info & ACB_WSTRUST ) 
3551                 has_enough_rights = user_has_privileges( p->pipe_user.nt_user_token, &se_machine_account);
3552         else if ( acb_info & ACB_NORMAL )
3553                 has_enough_rights = user_has_privileges( p->pipe_user.nt_user_token, &se_add_users );
3554         else if ( acb_info & (ACB_SVRTRUST|ACB_DOMTRUST) ) {
3555                 if ( lp_enable_privileges() )
3556                         has_enough_rights = nt_token_check_domain_rid( p->pipe_user.nt_user_token, DOMAIN_GROUP_RID_ADMINS );
3557         }
3558         
3559         DEBUG(5, ("_samr_set_userinfo: %s does%s possess sufficient rights\n",
3560                   uidtoname(p->pipe_user.ut.uid),
3561                   has_enough_rights ? "" : " not"));
3562
3563         /* ================ BEGIN SeMachineAccountPrivilege BLOCK ================ */
3564         
3565         if ( has_enough_rights )                                
3566                 become_root(); 
3567         
3568         /* ok!  user info levels (lots: see MSDEV help), off we go... */
3569
3570         switch (switch_value) {
3571                 case 18:
3572                         if (!set_user_info_18(ctr->info.id18, pwd))
3573                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3574                         break;
3575
3576                 case 24:
3577                         if (!p->session_key.length) {
3578                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3579                         }
3580                         SamOEMhashBlob(ctr->info.id24->pass, 516, &p->session_key);
3581
3582                         dump_data(100, ctr->info.id24->pass, 516);
3583
3584                         if (!set_user_info_pw(ctr->info.id24->pass, pwd))
3585                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3586                         break;
3587
3588                 case 25:
3589                         if (!p->session_key.length) {
3590                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3591                         }
3592                         encode_or_decode_arc4_passwd_buffer(ctr->info.id25->pass, &p->session_key);
3593
3594                         dump_data(100, ctr->info.id25->pass, 532);
3595
3596                         r_u->status = set_user_info_25(p->mem_ctx,
3597                                                        ctr->info.id25, pwd);
3598                         if (!NT_STATUS_IS_OK(r_u->status)) {
3599                                 goto done;
3600                         }
3601                         if (!set_user_info_pw(ctr->info.id25->pass, pwd))
3602                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3603                         break;
3604
3605                 case 26:
3606                         if (!p->session_key.length) {
3607                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3608                         }
3609                         encode_or_decode_arc4_passwd_buffer(ctr->info.id26->pass, &p->session_key);
3610
3611                         dump_data(100, ctr->info.id26->pass, 516);
3612
3613                         if (!set_user_info_pw(ctr->info.id26->pass, pwd))
3614                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3615                         break;
3616
3617                 case 23:
3618                         if (!p->session_key.length) {
3619                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3620                         }
3621                         SamOEMhashBlob(ctr->info.id23->pass, 516, &p->session_key);
3622
3623                         dump_data(100, ctr->info.id23->pass, 516);
3624
3625                         r_u->status = set_user_info_23(p->mem_ctx,
3626                                                        ctr->info.id23, pwd);
3627                         break;
3628
3629                 default:
3630                         r_u->status = NT_STATUS_INVALID_INFO_CLASS;
3631         }
3632
3633  done:
3634         
3635         if ( has_enough_rights )                                
3636                 unbecome_root();
3637                 
3638         /* ================ END SeMachineAccountPrivilege BLOCK ================ */
3639
3640         if (NT_STATUS_IS_OK(r_u->status)) {
3641                 force_flush_samr_cache(disp_info);
3642         }
3643
3644         return r_u->status;
3645 }
3646
3647 /*******************************************************************
3648  samr_reply_set_userinfo2
3649  ********************************************************************/
3650
3651 NTSTATUS _samr_set_userinfo2(pipes_struct *p, SAMR_Q_SET_USERINFO2 *q_u, SAMR_R_SET_USERINFO2 *r_u)
3652 {
3653         struct samu *pwd = NULL;
3654         DOM_SID sid;
3655         SAM_USERINFO_CTR *ctr = q_u->ctr;
3656         POLICY_HND *pol = &q_u->pol;
3657         uint16 switch_value = q_u->switch_value;
3658         uint32 acc_granted;
3659         uint32 acc_required;
3660         bool ret;
3661         bool has_enough_rights = False;
3662         uint32 acb_info;
3663         DISP_INFO *disp_info = NULL;
3664
3665         DEBUG(5, ("samr_reply_set_userinfo2: %d\n", __LINE__));
3666
3667         r_u->status = NT_STATUS_OK;
3668
3669         /* find the policy handle.  open a policy on it. */
3670         if (!get_lsa_policy_samr_sid(p, pol, &sid, &acc_granted, &disp_info))
3671                 return NT_STATUS_INVALID_HANDLE;
3672
3673                 
3674 #if 0   /* this really should be applied on a per info level basis   --jerry */
3675
3676         /* observed when joining XP client to Samba domain */
3677         acc_required = SA_RIGHT_USER_SET_PASSWORD | SA_RIGHT_USER_SET_ATTRIBUTES | SA_RIGHT_USER_ACCT_FLAGS_EXPIRY;
3678 #else
3679         acc_required = SA_RIGHT_USER_SET_ATTRIBUTES;
3680 #endif
3681         
3682         if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, acc_required, "_samr_set_userinfo2"))) {
3683                 return r_u->status;
3684         }
3685
3686         DEBUG(5, ("samr_reply_set_userinfo2: sid:%s\n", sid_string_static(&sid)));
3687
3688         if (ctr == NULL) {
3689                 DEBUG(5, ("samr_reply_set_userinfo2: NULL info level\n"));
3690                 return NT_STATUS_INVALID_INFO_CLASS;
3691         }
3692
3693         switch_value=ctr->switch_value;
3694
3695         if ( !(pwd = samu_new( NULL )) ) {
3696                 return NT_STATUS_NO_MEMORY;
3697         }
3698
3699         become_root();
3700         ret = pdb_getsampwsid(pwd, &sid);
3701         unbecome_root();
3702         
3703         if ( !ret ) {
3704                 TALLOC_FREE(pwd);
3705                 return NT_STATUS_NO_SUCH_USER;
3706         }
3707         
3708         acb_info = pdb_get_acct_ctrl(pwd);
3709         if ( acb_info & ACB_WSTRUST ) 
3710                 has_enough_rights = user_has_privileges( p->pipe_user.nt_user_token, &se_machine_account);
3711         else if ( acb_info & ACB_NORMAL )
3712                 has_enough_rights = user_has_privileges( p->pipe_user.nt_user_token, &se_add_users );
3713         else if ( acb_info & (ACB_SVRTRUST|ACB_DOMTRUST) ) {
3714                 if ( lp_enable_privileges() )
3715                         has_enough_rights = nt_token_check_domain_rid( p->pipe_user.nt_user_token, DOMAIN_GROUP_RID_ADMINS );
3716         }
3717         
3718         DEBUG(5, ("_samr_set_userinfo2: %s does%s possess sufficient rights\n",
3719                   uidtoname(p->pipe_user.ut.uid),
3720                   has_enough_rights ? "" : " not"));
3721
3722         /* ================ BEGIN SeMachineAccountPrivilege BLOCK ================ */
3723         
3724         if ( has_enough_rights )                                
3725                 become_root(); 
3726         
3727         /* ok!  user info levels (lots: see MSDEV help), off we go... */
3728         
3729         switch (switch_value) {
3730                 case 7:
3731                         r_u->status = set_user_info_7(p->mem_ctx,
3732                                                       ctr->info.id7, pwd);
3733                         break;
3734                 case 16:
3735                         if (!set_user_info_16(ctr->info.id16, pwd))
3736                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3737                         break;
3738                 case 18:
3739                         /* Used by AS/U JRA. */
3740                         if (!set_user_info_18(ctr->info.id18, pwd))
3741                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3742                         break;
3743                 case 20:
3744                         if (!set_user_info_20(ctr->info.id20, pwd))
3745                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3746                         break;
3747                 case 21:
3748                         r_u->status = set_user_info_21(p->mem_ctx,
3749                                                        ctr->info.id21, pwd);
3750                         break;
3751                 case 23:
3752                         if (!p->session_key.length) {
3753                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3754                         }
3755                         SamOEMhashBlob(ctr->info.id23->pass, 516, &p->session_key);
3756
3757                         dump_data(100, ctr->info.id23->pass, 516);
3758
3759                         r_u->status = set_user_info_23(p->mem_ctx,
3760                                                        ctr->info.id23, pwd);
3761                         break;
3762                 case 26:
3763                         if (!p->session_key.length) {
3764                                 r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
3765                         }
3766                         encode_or_decode_arc4_passwd_buffer(ctr->info.id26->pass, &p->session_key);
3767
3768                         dump_data(100, ctr->info.id26->pass, 516);
3769
3770                         if (!set_user_info_pw(ctr->info.id26->pass, pwd))
3771                                 r_u->status = NT_STATUS_ACCESS_DENIED;
3772                         break;
3773                 default:
3774                         r_u->status = NT_STATUS_INVALID_INFO_CLASS;
3775         }
3776
3777         if ( has_enough_rights )                                
3778                 unbecome_root();
3779                 
3780         /* ================ END SeMachineAccountPrivilege BLOCK ================ */
3781
3782         if (NT_STATUS_IS_OK(r_u->status)) {
3783                 force_flush_samr_cache(disp_info);
3784         }
3785
3786         return r_u->status;
3787 }
3788
3789 /*********************************************************************
3790  _samr_query_aliasmem
3791 *********************************************************************/
3792
3793 NTSTATUS _samr_query_useraliases(pipes_struct *p, SAMR_Q_QUERY_USERALIASES *q_u, SAMR_R_QUERY_USERALIASES *r_u)
3794 {
3795         size_t num_alias_rids;
3796         uint32 *alias_rids;
3797         struct samr_info *info = NULL;
3798         size_t i;
3799                 
3800         NTSTATUS ntstatus1;
3801         NTSTATUS ntstatus2;
3802
3803         DOM_SID *members;
3804
3805         r_u->status = NT_STATUS_OK;
3806
3807         DEBUG(5,("_samr_query_useraliases: %d\n", __LINE__));
3808
3809         /* find the policy handle.  open a policy on it. */
3810         if (!find_policy_by_hnd(p, &q_u->pol, (void **)(void *)&info))
3811                 return NT_STATUS_INVALID_HANDLE;
3812                 
3813         ntstatus1 = access_check_samr_function(info->acc_granted, SA_RIGHT_DOMAIN_LOOKUP_ALIAS_BY_MEM, "_samr_query_useraliases");
3814         ntstatus2 = access_check_samr_function(info->acc_granted, SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_query_useraliases");
3815         
3816         if (!NT_STATUS_IS_OK(ntstatus1) || !NT_STATUS_IS_OK(ntstatus2)) {
3817                 if (!(NT_STATUS_EQUAL(ntstatus1,NT_STATUS_ACCESS_DENIED) && NT_STATUS_IS_OK(ntstatus2)) &&
3818                     !(NT_STATUS_EQUAL(ntstatus1,NT_STATUS_ACCESS_DENIED) && NT_STATUS_IS_OK(ntstatus1))) {
3819                         return (NT_STATUS_IS_OK(ntstatus1)) ? ntstatus2 : ntstatus1;
3820