Initial import
[samba] / source / nsswitch / winbindd_ads.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Winbind ADS backend functions
5
6    Copyright (C) Andrew Tridgell 2001
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003
8    Copyright (C) Gerald (Jerry) Carter 2004
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "winbindd.h"
27
28 #ifdef HAVE_ADS
29
30 #undef DBGC_CLASS
31 #define DBGC_CLASS DBGC_WINBIND
32
33 /*
34   return our ads connections structure for a domain. We keep the connection
35   open to make things faster
36 */
37 static ADS_STRUCT *ads_cached_connection(struct winbindd_domain *domain)
38 {
39         ADS_STRUCT *ads;
40         ADS_STATUS status;
41
42         if (domain->private_data) {
43                 ads = (ADS_STRUCT *)domain->private_data;
44
45                 /* check for a valid structure */
46
47                 DEBUG(7, ("Current tickets expire at %d, time is now %d\n",
48                           (uint32) ads->auth.expire, (uint32) time(NULL)));
49                 if ( ads->config.realm && (ads->auth.expire > time(NULL))) {
50                         return ads;
51                 }
52                 else {
53                         /* we own this ADS_STRUCT so make sure it goes away */
54                         ads->is_mine = True;
55                         ads_destroy( &ads );
56                         ads_kdestroy("MEMORY:winbind_ccache");
57                         domain->private_data = NULL;
58                 }       
59         }
60
61         /* we don't want this to affect the users ccache */
62         setenv("KRB5CCNAME", "MEMORY:winbind_ccache", 1);
63
64         ads = ads_init(domain->alt_name, domain->name, NULL);
65         if (!ads) {
66                 DEBUG(1,("ads_init for domain %s failed\n", domain->name));
67                 return NULL;
68         }
69
70         /* the machine acct password might have change - fetch it every time */
71
72         SAFE_FREE(ads->auth.password);
73         SAFE_FREE(ads->auth.realm);
74
75         if ( IS_DC ) {
76                 DOM_SID sid;
77                 time_t last_set_time;
78
79                 if ( !secrets_fetch_trusted_domain_password( domain->name, &ads->auth.password, &sid, &last_set_time ) ) {
80                         ads_destroy( &ads );
81                         return NULL;
82                 }
83                 ads->auth.realm = SMB_STRDUP( ads->server.realm );
84                 strupper_m( ads->auth.realm );
85         }
86         else {
87                 struct winbindd_domain *our_domain = domain;
88
89                 ads->auth.password = secrets_fetch_machine_password(lp_workgroup(), NULL, NULL);
90
91                 /* always give preference to the alt_name in our 
92                    primary domain if possible */
93
94                 if ( !domain->primary )
95                         our_domain = find_our_domain();
96
97                 if ( our_domain->alt_name[0] != '\0' ) {
98                         ads->auth.realm = SMB_STRDUP( our_domain->alt_name );
99                         strupper_m( ads->auth.realm );
100                 }
101                 else
102                         ads->auth.realm = SMB_STRDUP( lp_realm() );
103         }
104
105         status = ads_connect(ads);
106         if (!ADS_ERR_OK(status) || !ads->config.realm) {
107                 extern struct winbindd_methods msrpc_methods, cache_methods;
108                 DEBUG(1,("ads_connect for domain %s failed: %s\n", 
109                          domain->name, ads_errstr(status)));
110                 ads_destroy(&ads);
111
112                 /* if we get ECONNREFUSED then it might be a NT4
113                    server, fall back to MSRPC */
114                 if (status.error_type == ENUM_ADS_ERROR_SYSTEM &&
115                     status.err.rc == ECONNREFUSED) {
116                         DEBUG(1,("Trying MSRPC methods\n"));
117                         if (domain->methods == &cache_methods) {
118                                 domain->backend = &msrpc_methods;
119                         } else {
120                                 domain->methods = &msrpc_methods;
121                         }
122                 }
123                 return NULL;
124         }
125
126         if (use_nss_info("sfu") && (!ads_check_sfu_mapping(ads))) {
127                 DEBUG(0,("ads_cached_connection: failed to check sfu attributes\n"));
128                 return NULL;
129         }
130         
131         /* set the flag that says we don't own the memory even 
132            though we do so that ads_destroy() won't destroy the 
133            structure we pass back by reference */
134
135         ads->is_mine = False;
136
137         domain->private_data = (void *)ads;
138         return ads;
139 }
140
141
142 /* Query display info for a realm. This is the basic user list fn */
143 static NTSTATUS query_user_list(struct winbindd_domain *domain,
144                                TALLOC_CTX *mem_ctx,
145                                uint32 *num_entries, 
146                                WINBIND_USERINFO **info)
147 {
148         ADS_STRUCT *ads = NULL;
149         const char *attrs[] = {"userPrincipalName",
150                                "sAMAccountName",
151                                "name", "objectSid", "primaryGroupID", 
152                                "sAMAccountType", 
153                                ADS_ATTR_SFU_HOMEDIR_OID, 
154                                ADS_ATTR_SFU_SHELL_OID,
155                                ADS_ATTR_SFU_GECOS_OID,
156                                NULL};
157         int i, count;
158         ADS_STATUS rc;
159         void *res = NULL;
160         void *msg = NULL;
161         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
162
163         *num_entries = 0;
164
165         DEBUG(3,("ads: query_user_list\n"));
166
167         ads = ads_cached_connection(domain);
168         
169         if (!ads) {
170                 domain->last_status = NT_STATUS_SERVER_DISABLED;
171                 goto done;
172         }
173
174         rc = ads_search_retry(ads, &res, "(objectClass=user)", attrs);
175         if (!ADS_ERR_OK(rc) || !res) {
176                 DEBUG(1,("query_user_list ads_search: %s\n", ads_errstr(rc)));
177                 goto done;
178         }
179
180         count = ads_count_replies(ads, res);
181         if (count == 0) {
182                 DEBUG(1,("query_user_list: No users found\n"));
183                 goto done;
184         }
185
186         (*info) = TALLOC_ZERO_ARRAY(mem_ctx, WINBIND_USERINFO, count);
187         if (!*info) {
188                 status = NT_STATUS_NO_MEMORY;
189                 goto done;
190         }
191
192         i = 0;
193
194         for (msg = ads_first_entry(ads, res); msg; msg = ads_next_entry(ads, msg)) {
195                 char *name, *gecos = NULL;
196                 char *homedir = NULL;
197                 char *shell = NULL;
198                 uint32 group;
199                 uint32 atype;
200
201                 if (!ads_pull_uint32(ads, msg, "sAMAccountType", &atype) ||
202                     ads_atype_map(atype) != SID_NAME_USER) {
203                         DEBUG(1,("Not a user account? atype=0x%x\n", atype));
204                         continue;
205                 }
206
207                 name = ads_pull_username(ads, mem_ctx, msg);
208
209                 if (use_nss_info("sfu")) {
210                         homedir = ads_pull_string(ads, mem_ctx, msg, 
211                                                   ads->schema.sfu_homedir_attr);
212                         shell   = ads_pull_string(ads, mem_ctx, msg, 
213                                                   ads->schema.sfu_shell_attr);
214                         gecos   = ads_pull_string(ads, mem_ctx, msg, 
215                                                   ads->schema.sfu_gecos_attr);
216                 }
217
218                 if (gecos == NULL) {
219                         gecos = ads_pull_string(ads, mem_ctx, msg, "name");
220                 }
221         
222                 if (!ads_pull_sid(ads, msg, "objectSid",
223                                   &(*info)[i].user_sid)) {
224                         DEBUG(1,("No sid for %s !?\n", name));
225                         continue;
226                 }
227                 if (!ads_pull_uint32(ads, msg, "primaryGroupID", &group)) {
228                         DEBUG(1,("No primary group for %s !?\n", name));
229                         continue;
230                 }
231
232                 (*info)[i].acct_name = name;
233                 (*info)[i].full_name = gecos;
234                 (*info)[i].homedir = homedir;
235                 (*info)[i].shell = shell;
236                 sid_compose(&(*info)[i].group_sid, &domain->sid, group);
237                 i++;
238         }
239
240         (*num_entries) = i;
241         status = NT_STATUS_OK;
242
243         DEBUG(3,("ads query_user_list gave %d entries\n", (*num_entries)));
244
245 done:
246         if (res) 
247                 ads_msgfree(ads, res);
248
249         return status;
250 }
251
252 /* list all domain groups */
253 static NTSTATUS enum_dom_groups(struct winbindd_domain *domain,
254                                 TALLOC_CTX *mem_ctx,
255                                 uint32 *num_entries, 
256                                 struct acct_info **info)
257 {
258         ADS_STRUCT *ads = NULL;
259         const char *attrs[] = {"userPrincipalName", "sAMAccountName",
260                                "name", "objectSid", NULL};
261         int i, count;
262         ADS_STATUS rc;
263         void *res = NULL;
264         void *msg = NULL;
265         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
266         const char *filter;
267         BOOL enum_dom_local_groups = False;
268
269         *num_entries = 0;
270
271         DEBUG(3,("ads: enum_dom_groups\n"));
272
273         /* only grab domain local groups for our domain */
274         if ( domain->native_mode && strequal(lp_realm(), domain->alt_name)  ) {
275                 enum_dom_local_groups = True;
276         }
277
278         /* Workaround ADS LDAP bug present in MS W2K3 SP0 and W2K SP4 w/o
279          * rollup-fixes:
280          *
281          * According to Section 5.1(4) of RFC 2251 if a value of a type is it's
282          * default value, it MUST be absent. In case of extensible matching the
283          * "dnattr" boolean defaults to FALSE and so it must be only be present
284          * when set to TRUE. 
285          *
286          * When it is set to FALSE and the OpenLDAP lib (correctly) encodes a
287          * filter using bitwise matching rule then the buggy AD fails to decode
288          * the extensible match. As a workaround set it to TRUE and thereby add
289          * the dnAttributes "dn" field to cope with those older AD versions.
290          * It should not harm and won't put any additional load on the AD since
291          * none of the dn components have a bitmask-attribute.
292          *
293          * Thanks to Ralf Haferkamp for input and testing - Guenther */
294
295         filter = talloc_asprintf(mem_ctx, "(&(objectCategory=group)(&(groupType:dn:%s:=%d)(!(groupType:dn:%s:=%d))))", 
296                                  ADS_LDAP_MATCHING_RULE_BIT_AND, GROUP_TYPE_SECURITY_ENABLED,
297                                  ADS_LDAP_MATCHING_RULE_BIT_AND, 
298                                  enum_dom_local_groups ? GROUP_TYPE_BUILTIN_LOCAL_GROUP : GROUP_TYPE_RESOURCE_GROUP);
299
300         if (filter == NULL) {
301                 status = NT_STATUS_NO_MEMORY;
302                 goto done;
303         }
304
305         ads = ads_cached_connection(domain);
306
307         if (!ads) {
308                 domain->last_status = NT_STATUS_SERVER_DISABLED;
309                 goto done;
310         }
311
312         rc = ads_search_retry(ads, &res, filter, attrs);
313         if (!ADS_ERR_OK(rc) || !res) {
314                 DEBUG(1,("enum_dom_groups ads_search: %s\n", ads_errstr(rc)));
315                 goto done;
316         }
317
318         count = ads_count_replies(ads, res);
319         if (count == 0) {
320                 DEBUG(1,("enum_dom_groups: No groups found\n"));
321                 goto done;
322         }
323
324         (*info) = TALLOC_ZERO_ARRAY(mem_ctx, struct acct_info, count);
325         if (!*info) {
326                 status = NT_STATUS_NO_MEMORY;
327                 goto done;
328         }
329
330         i = 0;
331         
332         for (msg = ads_first_entry(ads, res); msg; msg = ads_next_entry(ads, msg)) {
333                 char *name, *gecos;
334                 DOM_SID sid;
335                 uint32 rid;
336
337                 name = ads_pull_username(ads, mem_ctx, msg);
338                 gecos = ads_pull_string(ads, mem_ctx, msg, "name");
339                 if (!ads_pull_sid(ads, msg, "objectSid", &sid)) {
340                         DEBUG(1,("No sid for %s !?\n", name));
341                         continue;
342                 }
343
344                 if (!sid_peek_check_rid(&domain->sid, &sid, &rid)) {
345                         DEBUG(1,("No rid for %s !?\n", name));
346                         continue;
347                 }
348
349                 fstrcpy((*info)[i].acct_name, name);
350                 fstrcpy((*info)[i].acct_desc, gecos);
351                 (*info)[i].rid = rid;
352                 i++;
353         }
354
355         (*num_entries) = i;
356
357         status = NT_STATUS_OK;
358
359         DEBUG(3,("ads enum_dom_groups gave %d entries\n", (*num_entries)));
360
361 done:
362         if (res) 
363                 ads_msgfree(ads, res);
364
365         return status;
366 }
367
368 /* list all domain local groups */
369 static NTSTATUS enum_local_groups(struct winbindd_domain *domain,
370                                 TALLOC_CTX *mem_ctx,
371                                 uint32 *num_entries, 
372                                 struct acct_info **info)
373 {
374         /*
375          * This is a stub function only as we returned the domain 
376          * local groups in enum_dom_groups() if the domain->native field
377          * was true.  This is a simple performance optimization when
378          * using LDAP.
379          *
380          * if we ever need to enumerate domain local groups separately, 
381          * then this the optimization in enum_dom_groups() will need 
382          * to be split out
383          */
384         *num_entries = 0;
385         
386         return NT_STATUS_OK;
387 }
388
389 /* convert a DN to a name, SID and name type 
390    this might become a major speed bottleneck if groups have
391    lots of users, in which case we could cache the results
392 */
393 static BOOL dn_lookup(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
394                       const char *dn,
395                       char **name, uint32 *name_type, DOM_SID *sid)
396 {
397         void *res = NULL;
398         const char *attrs[] = {"userPrincipalName", "sAMAccountName",
399                                "objectSid", "sAMAccountType", NULL};
400         ADS_STATUS rc;
401         uint32 atype;
402         DEBUG(3,("ads: dn_lookup\n"));
403
404         rc = ads_search_retry_dn(ads, &res, dn, attrs);
405
406         if (!ADS_ERR_OK(rc) || !res) {
407                 goto failed;
408         }
409
410         (*name) = ads_pull_username(ads, mem_ctx, res);
411
412         if (!ads_pull_uint32(ads, res, "sAMAccountType", &atype)) {
413                 goto failed;
414         }
415         (*name_type) = ads_atype_map(atype);
416
417         if (!ads_pull_sid(ads, res, "objectSid", sid)) {
418                 goto failed;
419         }
420
421         if (res) 
422                 ads_msgfree(ads, res);
423
424         return True;
425
426 failed:
427         if (res) 
428                 ads_msgfree(ads, res);
429
430         return False;
431 }
432
433 /* Lookup user information from a rid */
434 static NTSTATUS query_user(struct winbindd_domain *domain, 
435                            TALLOC_CTX *mem_ctx, 
436                            const DOM_SID *sid, 
437                            WINBIND_USERINFO *info)
438 {
439         ADS_STRUCT *ads = NULL;
440         const char *attrs[] = {"userPrincipalName", 
441                                "sAMAccountName",
442                                "name", 
443                                "primaryGroupID", 
444                                ADS_ATTR_SFU_HOMEDIR_OID, 
445                                ADS_ATTR_SFU_SHELL_OID,
446                                ADS_ATTR_SFU_GECOS_OID,
447                                NULL};
448         ADS_STATUS rc;
449         int count;
450         void *msg = NULL;
451         char *ldap_exp;
452         char *sidstr;
453         uint32 group_rid;
454         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
455
456         DEBUG(3,("ads: query_user\n"));
457
458         ads = ads_cached_connection(domain);
459         
460         if (!ads) {
461                 domain->last_status = NT_STATUS_SERVER_DISABLED;
462                 goto done;
463         }
464
465         sidstr = sid_binstring(sid);
466         asprintf(&ldap_exp, "(objectSid=%s)", sidstr);
467         rc = ads_search_retry(ads, &msg, ldap_exp, attrs);
468         free(ldap_exp);
469         free(sidstr);
470         if (!ADS_ERR_OK(rc) || !msg) {
471                 DEBUG(1,("query_user(sid=%s) ads_search: %s\n",
472                          sid_string_static(sid), ads_errstr(rc)));
473                 goto done;
474         }
475
476         count = ads_count_replies(ads, msg);
477         if (count != 1) {
478                 DEBUG(1,("query_user(sid=%s): Not found\n",
479                          sid_string_static(sid)));
480                 goto done;
481         }
482
483         info->acct_name = ads_pull_username(ads, mem_ctx, msg);
484
485         if (use_nss_info("sfu")) {
486                 info->homedir   = ads_pull_string(ads, mem_ctx, msg, 
487                                                   ads->schema.sfu_homedir_attr);
488                 info->shell     = ads_pull_string(ads, mem_ctx, msg, 
489                                                   ads->schema.sfu_shell_attr);
490                 info->full_name = ads_pull_string(ads, mem_ctx, msg,
491                                                   ads->schema.sfu_gecos_attr);
492         }
493
494         if (info->full_name == NULL) {
495                 info->full_name = ads_pull_string(ads, mem_ctx, msg, "name");
496         }
497
498         if (!ads_pull_uint32(ads, msg, "primaryGroupID", &group_rid)) {
499                 DEBUG(1,("No primary group for %s !?\n",
500                          sid_string_static(sid)));
501                 goto done;
502         }
503
504         sid_copy(&info->user_sid, sid);
505         sid_compose(&info->group_sid, &domain->sid, group_rid);
506
507         status = NT_STATUS_OK;
508
509         DEBUG(3,("ads query_user gave %s\n", info->acct_name));
510 done:
511         if (msg) 
512                 ads_msgfree(ads, msg);
513
514         return status;
515 }
516
517 /* Lookup groups a user is a member of - alternate method, for when
518    tokenGroups are not available. */
519 static NTSTATUS lookup_usergroups_alt(struct winbindd_domain *domain,
520                                       TALLOC_CTX *mem_ctx,
521                                       const char *user_dn, 
522                                       DOM_SID *primary_group,
523                                       size_t *p_num_groups, DOM_SID **user_sids)
524 {
525         ADS_STATUS rc;
526         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
527         int count;
528         void *res = NULL;
529         void *msg = NULL;
530         char *ldap_exp;
531         ADS_STRUCT *ads;
532         const char *group_attrs[] = {"objectSid", NULL};
533         char *escaped_dn;
534         size_t num_groups = 0;
535
536         DEBUG(3,("ads: lookup_usergroups_alt\n"));
537
538         ads = ads_cached_connection(domain);
539
540         if (!ads) {
541                 domain->last_status = NT_STATUS_SERVER_DISABLED;
542                 goto done;
543         }
544
545         if (!(escaped_dn = escape_ldap_string_alloc(user_dn))) {
546                 status = NT_STATUS_NO_MEMORY;
547                 goto done;
548         }
549
550         /* buggy server, no tokenGroups.  Instead lookup what groups this user
551            is a member of by DN search on member*/
552
553         if (!(ldap_exp = talloc_asprintf(mem_ctx, "(&(member=%s)(objectClass=group))", escaped_dn))) {
554                 DEBUG(1,("lookup_usergroups(dn=%s) asprintf failed!\n", user_dn));
555                 SAFE_FREE(escaped_dn);
556                 status = NT_STATUS_NO_MEMORY;
557                 goto done;
558         }
559
560         SAFE_FREE(escaped_dn);
561
562         rc = ads_search_retry(ads, &res, ldap_exp, group_attrs);
563         
564         if (!ADS_ERR_OK(rc) || !res) {
565                 DEBUG(1,("lookup_usergroups ads_search member=%s: %s\n", user_dn, ads_errstr(rc)));
566                 return ads_ntstatus(rc);
567         }
568         
569         count = ads_count_replies(ads, res);
570         
571         *user_sids = NULL;
572         num_groups = 0;
573
574         /* always add the primary group to the sid array */
575         add_sid_to_array(mem_ctx, primary_group, user_sids, &num_groups);
576
577         if (count > 0) {
578                 for (msg = ads_first_entry(ads, res); msg;
579                      msg = ads_next_entry(ads, msg)) {
580                         DOM_SID group_sid;
581                 
582                         if (!ads_pull_sid(ads, msg, "objectSid", &group_sid)) {
583                                 DEBUG(1,("No sid for this group ?!?\n"));
584                                 continue;
585                         }
586
587                         add_sid_to_array(mem_ctx, &group_sid, user_sids,
588                                          &num_groups);
589                 }
590
591         }
592
593         *p_num_groups = num_groups;
594         status = (user_sids != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
595
596         DEBUG(3,("ads lookup_usergroups (alt) for dn=%s\n", user_dn));
597 done:
598         if (res) 
599                 ads_msgfree(ads, res);
600
601         return status;
602 }
603
604 /* Lookup groups a user is a member of. */
605 static NTSTATUS lookup_usergroups(struct winbindd_domain *domain,
606                                   TALLOC_CTX *mem_ctx,
607                                   const DOM_SID *sid, 
608                                   uint32 *p_num_groups, DOM_SID **user_sids)
609 {
610         ADS_STRUCT *ads = NULL;
611         const char *attrs[] = {"tokenGroups", "primaryGroupID", NULL};
612         ADS_STATUS rc;
613         int count;
614         LDAPMessage *msg = NULL;
615         char *user_dn;
616         DOM_SID *sids;
617         int i;
618         DOM_SID primary_group;
619         uint32 primary_group_rid;
620         fstring sid_string;
621         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
622         size_t num_groups = 0;
623
624         DEBUG(3,("ads: lookup_usergroups\n"));
625         *p_num_groups = 0;
626
627         ads = ads_cached_connection(domain);
628         
629         if (!ads) {
630                 domain->last_status = NT_STATUS_SERVER_DISABLED;
631                 status = NT_STATUS_SERVER_DISABLED;
632                 goto done;
633         }
634
635         rc = ads_sid_to_dn(ads, mem_ctx, sid, &user_dn);
636         if (!ADS_ERR_OK(rc)) {
637                 status = ads_ntstatus(rc);
638                 goto done;
639         }
640
641         rc = ads_search_retry_dn(ads, (void**)(void *)&msg, user_dn, attrs);
642         if (!ADS_ERR_OK(rc)) {
643                 status = ads_ntstatus(rc);
644                 DEBUG(1,("lookup_usergroups(sid=%s) ads_search tokenGroups: %s\n", 
645                          sid_to_string(sid_string, sid), ads_errstr(rc)));
646                 goto done;
647         }
648         
649         if (!msg) {
650                 DEBUG(1,("lookup_usergroups(sid=%s) ads_search tokenGroups: NULL msg\n", 
651                          sid_to_string(sid_string, sid)));
652                 status = NT_STATUS_UNSUCCESSFUL;
653                 goto done;
654         }
655
656         if (!ads_pull_uint32(ads, msg, "primaryGroupID", &primary_group_rid)) {
657                 DEBUG(1,("%s: No primary group for sid=%s !?\n", 
658                          domain->name, sid_to_string(sid_string, sid)));
659                 goto done;
660         }
661
662         sid_copy(&primary_group, &domain->sid);
663         sid_append_rid(&primary_group, primary_group_rid);
664
665         count = ads_pull_sids(ads, mem_ctx, msg, "tokenGroups", &sids);
666
667         if (msg) 
668                 ads_msgfree(ads, msg);
669
670         /* there must always be at least one group in the token, 
671            unless we are talking to a buggy Win2k server */
672         if (count == 0) {
673                 status = lookup_usergroups_alt(domain, mem_ctx, user_dn, 
674                                              &primary_group,
675                                              &num_groups, user_sids);
676                 *p_num_groups = (uint32)num_groups;
677                 return status;
678         }
679
680         *user_sids = NULL;
681         num_groups = 0;
682
683         add_sid_to_array(mem_ctx, &primary_group, user_sids, &num_groups);
684         
685         for (i=0;i<count;i++) {
686
687                 /* ignore Builtin groups from ADS - Guenther */
688                 if (sid_check_is_in_builtin(&sids[i])) {
689                         continue;
690                 }
691                                
692                 add_sid_to_array_unique(mem_ctx, &sids[i],
693                                         user_sids, &num_groups);
694         }
695
696         *p_num_groups = (uint32)num_groups;
697         status = (user_sids != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
698
699         DEBUG(3,("ads lookup_usergroups for sid=%s\n",
700                  sid_to_string(sid_string, sid)));
701 done:
702         return status;
703 }
704
705 /*
706   find the members of a group, given a group rid and domain
707  */
708 static NTSTATUS lookup_groupmem(struct winbindd_domain *domain,
709                                 TALLOC_CTX *mem_ctx,
710                                 const DOM_SID *group_sid, uint32 *num_names, 
711                                 DOM_SID **sid_mem, char ***names, 
712                                 uint32 **name_types)
713 {
714         ADS_STATUS rc;
715         int count;
716         void *res=NULL;
717         ADS_STRUCT *ads = NULL;
718         char *ldap_exp;
719         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
720         char *sidstr;
721         char **members;
722         int i;
723         size_t num_members;
724         fstring sid_string;
725         BOOL more_values;
726         const char **attrs;
727         uint32 first_usn;
728         uint32 current_usn;
729         int num_retries = 0;
730
731         DEBUG(10,("ads: lookup_groupmem %s sid=%s\n", domain->name, 
732                   sid_string_static(group_sid)));
733
734         *num_names = 0;
735
736         ads = ads_cached_connection(domain);
737         
738         if (!ads) {
739                 domain->last_status = NT_STATUS_SERVER_DISABLED;
740                 goto done;
741         }
742
743         sidstr = sid_binstring(group_sid);
744
745         /* search for all members of the group */
746         if (!(ldap_exp = talloc_asprintf(mem_ctx, "(objectSid=%s)",sidstr))) {
747                 SAFE_FREE(sidstr);
748                 DEBUG(1, ("ads: lookup_groupmem: tallloc_asprintf for ldap_exp failed!\n"));
749                 status = NT_STATUS_NO_MEMORY;
750                 goto done;
751         }
752         SAFE_FREE(sidstr);
753
754         members = NULL;
755         num_members = 0;
756
757         attrs = TALLOC_ARRAY(mem_ctx, const char *, 3);
758         attrs[1] = talloc_strdup(mem_ctx, "usnChanged");
759         attrs[2] = NULL;
760                 
761         do {
762                 if (num_members == 0) 
763                         attrs[0] = talloc_strdup(mem_ctx, "member");
764
765                 DEBUG(10, ("Searching for attrs[0] = %s, attrs[1] = %s\n", attrs[0], attrs[1]));
766
767                 rc = ads_search_retry(ads, &res, ldap_exp, attrs);
768
769                 if (!ADS_ERR_OK(rc) || !res) {
770                         DEBUG(1,("ads: lookup_groupmem ads_search: %s\n",
771                                  ads_errstr(rc)));
772                         status = ads_ntstatus(rc);
773                         goto done;
774                 }
775
776                 count = ads_count_replies(ads, res);
777                 if (count == 0)
778                         break;
779
780                 if (num_members == 0) {
781                         if (!ads_pull_uint32(ads, res, "usnChanged", &first_usn)) {
782                                 DEBUG(1, ("ads: lookup_groupmem could not pull usnChanged!\n"));
783                                 goto done;
784                         }
785                 }
786
787                 if (!ads_pull_uint32(ads, res, "usnChanged", &current_usn)) {
788                         DEBUG(1, ("ads: lookup_groupmem could not pull usnChanged!\n"));
789                         goto done;
790                 }
791
792                 if (first_usn != current_usn) {
793                         DEBUG(5, ("ads: lookup_groupmem USN on this record changed"
794                                   " - restarting search\n"));
795                         if (num_retries < 5) {
796                                 num_retries++;
797                                 num_members = 0;
798                                 continue;
799                         } else {
800                                 DEBUG(5, ("ads: lookup_groupmem USN on this record changed"
801                                           " - restarted search too many times, aborting!\n"));
802                                 status = NT_STATUS_UNSUCCESSFUL;
803                                 goto done;
804                         }
805                 }
806
807                 members = ads_pull_strings_range(ads, mem_ctx, res,
808                                                  "member",
809                                                  members,
810                                                  &attrs[0],
811                                                  &num_members,
812                                                  &more_values);
813
814                 if ((members == NULL) || (num_members == 0))
815                         break;
816
817         } while (more_values);
818                 
819         /* now we need to turn a list of members into rids, names and name types 
820            the problem is that the members are in the form of distinguised names
821         */
822
823         (*sid_mem) = TALLOC_ZERO_ARRAY(mem_ctx, DOM_SID, num_members);
824         (*name_types) = TALLOC_ZERO_ARRAY(mem_ctx, uint32, num_members);
825         (*names) = TALLOC_ZERO_ARRAY(mem_ctx, char *, num_members);
826
827         for (i=0;i<num_members;i++) {
828                 uint32 name_type;
829                 char *name;
830                 DOM_SID sid;
831
832                 if (dn_lookup(ads, mem_ctx, members[i], &name, &name_type, &sid)) {
833                     (*names)[*num_names] = name;
834                     (*name_types)[*num_names] = name_type;
835                     sid_copy(&(*sid_mem)[*num_names], &sid);
836                     (*num_names)++;
837                 }
838         }       
839
840         status = NT_STATUS_OK;
841         DEBUG(3,("ads lookup_groupmem for sid=%s\n", sid_to_string(sid_string, group_sid)));
842 done:
843
844         if (res) 
845                 ads_msgfree(ads, res);
846
847         return status;
848 }
849
850 /* find the sequence number for a domain */
851 static NTSTATUS sequence_number(struct winbindd_domain *domain, uint32 *seq)
852 {
853         ADS_STRUCT *ads = NULL;
854         ADS_STATUS rc;
855
856         DEBUG(3,("ads: fetch sequence_number for %s\n", domain->name));
857
858         *seq = DOM_SEQUENCE_NONE;
859
860         ads = ads_cached_connection(domain);
861         
862         if (!ads) {
863                 domain->last_status = NT_STATUS_SERVER_DISABLED;
864                 return NT_STATUS_UNSUCCESSFUL;
865         }
866
867         rc = ads_USN(ads, seq);
868         
869         if (!ADS_ERR_OK(rc)) {
870         
871                 /* its a dead connection ; don't destroy it 
872                    through since ads_USN() has already done 
873                    that indirectly */
874                    
875                 domain->private_data = NULL;
876         }
877         return ads_ntstatus(rc);
878 }
879
880 /* get a list of trusted domains */
881 static NTSTATUS trusted_domains(struct winbindd_domain *domain,
882                                 TALLOC_CTX *mem_ctx,
883                                 uint32 *num_domains,
884                                 char ***names,
885                                 char ***alt_names,
886                                 DOM_SID **dom_sids)
887 {
888         NTSTATUS                result = NT_STATUS_UNSUCCESSFUL;
889         struct ds_domain_trust  *domains = NULL;
890         int                     count = 0;
891         int                     i;
892                                 /* i think we only need our forest and downlevel trusted domains */
893         uint32                  flags = DS_DOMAIN_IN_FOREST | DS_DOMAIN_DIRECT_OUTBOUND;
894         struct rpc_pipe_client *cli;
895
896         DEBUG(3,("ads: trusted_domains\n"));
897
898         *num_domains = 0;
899         *alt_names   = NULL;
900         *names       = NULL;
901         *dom_sids    = NULL;
902
903         result = cm_connect_netlogon(domain, &cli);
904
905         if (!NT_STATUS_IS_OK(result)) {
906                 DEBUG(5, ("trusted_domains: Could not open a connection to %s "
907                           "for PIPE_NETLOGON (%s)\n", 
908                           domain->name, nt_errstr(result)));
909                 return NT_STATUS_UNSUCCESSFUL;
910         }
911         
912         if ( NT_STATUS_IS_OK(result) ) {
913                 result = rpccli_ds_enum_domain_trusts(cli, mem_ctx,
914                                                       cli->cli->desthost, 
915                                                       flags, &domains,
916                                                       (unsigned int *)&count);
917         }
918         
919         if ( NT_STATUS_IS_OK(result) && count) {
920         
921                 /* Allocate memory for trusted domain names and sids */
922
923                 if ( !(*names = TALLOC_ARRAY(mem_ctx, char *, count)) ) {
924                         DEBUG(0, ("trusted_domains: out of memory\n"));
925                         return NT_STATUS_NO_MEMORY;
926                 }
927
928                 if ( !(*alt_names = TALLOC_ARRAY(mem_ctx, char *, count)) ) {
929                         DEBUG(0, ("trusted_domains: out of memory\n"));
930                         return NT_STATUS_NO_MEMORY;
931                 }
932
933                 if ( !(*dom_sids = TALLOC_ARRAY(mem_ctx, DOM_SID, count)) ) {
934                         DEBUG(0, ("trusted_domains: out of memory\n"));
935                         return NT_STATUS_NO_MEMORY;
936                 }
937
938                 /* Copy across names and sids */
939
940                 for (i = 0; i < count; i++) {
941                         (*names)[i] = domains[i].netbios_domain;
942                         (*alt_names)[i] = domains[i].dns_domain;
943
944                         sid_copy(&(*dom_sids)[i], &domains[i].sid);
945                 }
946
947                 *num_domains = count;   
948         }
949
950         return result;
951 }
952
953 /* the ADS backend methods are exposed via this structure */
954 struct winbindd_methods ads_methods = {
955         True,
956         query_user_list,
957         enum_dom_groups,
958         enum_local_groups,
959         msrpc_name_to_sid,
960         msrpc_sid_to_name,
961         query_user,
962         lookup_usergroups,
963         msrpc_lookup_useraliases,
964         lookup_groupmem,
965         sequence_number,
966         trusted_domains,
967 };
968
969 #endif