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