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