s3: Fix a debug message
[samba.git] / source3 / winbindd / idmap_ad.c
1 /*
2  *  idmap_ad: map between Active Directory and RFC 2307 or "Services for Unix" (SFU) Accounts
3  *
4  * Unix SMB/CIFS implementation.
5  *
6  * Winbind ADS backend functions
7  *
8  * Copyright (C) Andrew Tridgell 2001
9  * Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003
10  * Copyright (C) Gerald (Jerry) Carter 2004-2007
11  * Copyright (C) Luke Howard 2001-2004
12  * Copyright (C) Michael Adam 2008,2010
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 3 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, see <http://www.gnu.org/licenses/>.
26  */
27
28 #include "includes.h"
29 #include "winbindd.h"
30 #include "../libds/common/flags.h"
31 #include "ads.h"
32 #include "libads/ldap_schema.h"
33 #include "nss_info.h"
34 #include "secrets.h"
35 #include "idmap.h"
36 #include "../libcli/ldap/ldap_ndr.h"
37 #include "../libcli/security/security.h"
38
39 #undef DBGC_CLASS
40 #define DBGC_CLASS DBGC_IDMAP
41
42 #define WINBIND_CCACHE_NAME "MEMORY:winbind_ccache"
43
44 #define IDMAP_AD_MAX_IDS 30
45 #define CHECK_ALLOC_DONE(mem) do { \
46      if (!mem) { \
47            DEBUG(0, ("Out of memory!\n")); \
48            ret = NT_STATUS_NO_MEMORY; \
49            goto done; \
50       } \
51 } while (0)
52
53 struct idmap_ad_context {
54         ADS_STRUCT *ads;
55         struct posix_schema *ad_schema;
56         enum wb_posix_mapping ad_map_type; /* WB_POSIX_MAP_UNKNOWN */
57 };
58
59 NTSTATUS init_module(void);
60
61 /************************************************************************
62  ***********************************************************************/
63
64 static ADS_STATUS ad_idmap_cached_connection_internal(struct idmap_domain *dom)
65 {
66         ADS_STRUCT *ads;
67         ADS_STATUS status;
68         bool local = False;
69         fstring dc_name;
70         struct sockaddr_storage dc_ip;
71         struct idmap_ad_context *ctx;
72         char *ldap_server = NULL;
73         char *realm = NULL;
74         struct winbindd_domain *wb_dom;
75
76         DEBUG(10, ("ad_idmap_cached_connection: called for domain '%s'\n",
77                    dom->name));
78
79         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
80
81         if (ctx->ads != NULL) {
82
83                 time_t expire;
84                 time_t now = time(NULL);
85
86                 ads = ctx->ads;
87
88                 expire = MIN(ads->auth.tgt_expire, ads->auth.tgs_expire);
89
90                 /* check for a valid structure */
91                 DEBUG(7, ("Current tickets expire in %d seconds (at %d, time is now %d)\n",
92                           (uint32)expire-(uint32)now, (uint32) expire, (uint32) now));
93
94                 if ( ads->config.realm && (expire > time(NULL))) {
95                         return ADS_SUCCESS;
96                 } else {
97                         /* we own this ADS_STRUCT so make sure it goes away */
98                         DEBUG(7,("Deleting expired krb5 credential cache\n"));
99                         ads->is_mine = True;
100                         ads_destroy( &ads );
101                         ads_kdestroy(WINBIND_CCACHE_NAME);
102                         ctx->ads = NULL;
103                         TALLOC_FREE( ctx->ad_schema );
104                 }
105         }
106
107         if (!local) {
108                 /* we don't want this to affect the users ccache */
109                 setenv("KRB5CCNAME", WINBIND_CCACHE_NAME, 1);
110         }
111
112         /*
113          * At this point we only have the NetBIOS domain name.
114          * Check if we can get server nam and realm from SAF cache
115          * and the domain list.
116          */
117         ldap_server = saf_fetch(dom->name);
118         DEBUG(10, ("ldap_server from saf cache: '%s'\n", ldap_server?ldap_server:""));
119
120         wb_dom = find_domain_from_name_noinit(dom->name);
121         if (wb_dom == NULL) {
122                 DEBUG(10, ("find_domain_from_name_noinit did not find domain '%s'\n",
123                            dom->name));
124                 realm = NULL;
125         } else {
126                 DEBUG(10, ("find_domain_from_name_noinit found realm '%s' for "
127                           " domain '%s'\n", wb_dom->alt_name, dom->name));
128                 realm = wb_dom->alt_name;
129         }
130
131         if ( (ads = ads_init(realm, dom->name, ldap_server)) == NULL ) {
132                 DEBUG(1,("ads_init failed\n"));
133                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
134         }
135
136         /* the machine acct password might have change - fetch it every time */
137         SAFE_FREE(ads->auth.password);
138         ads->auth.password = secrets_fetch_machine_password(lp_workgroup(), NULL, NULL);
139
140         SAFE_FREE(ads->auth.realm);
141         ads->auth.realm = SMB_STRDUP(lp_realm());
142
143         /* setup server affinity */
144
145         get_dc_name(dom->name, realm, dc_name, &dc_ip );
146
147         status = ads_connect(ads);
148         if (!ADS_ERR_OK(status)) {
149                 DEBUG(1, ("ad_idmap_cached_connection_internal: failed to "
150                           "connect to AD\n"));
151                 ads_destroy(&ads);
152                 return status;
153         }
154
155         ads->is_mine = False;
156
157         ctx->ads = ads;
158
159         return ADS_SUCCESS;
160 }
161
162 /************************************************************************
163  ***********************************************************************/
164
165 static ADS_STATUS ad_idmap_cached_connection(struct idmap_domain *dom)
166 {
167         ADS_STATUS status;
168         struct idmap_ad_context * ctx;
169
170         status = ad_idmap_cached_connection_internal(dom);
171         if (!ADS_ERR_OK(status)) {
172                 return status;
173         }
174
175         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
176
177         /* if we have a valid ADS_STRUCT and the schema model is
178            defined, then we can return here. */
179
180         if ( ctx->ad_schema ) {
181                 return ADS_SUCCESS;
182         }
183
184         /* Otherwise, set the schema model */
185
186         if ( (ctx->ad_map_type ==  WB_POSIX_MAP_SFU) ||
187              (ctx->ad_map_type ==  WB_POSIX_MAP_SFU20) ||
188              (ctx->ad_map_type ==  WB_POSIX_MAP_RFC2307) )
189         {
190                 status = ads_check_posix_schema_mapping(NULL, ctx->ads, ctx->ad_map_type, &ctx->ad_schema);
191                 if ( !ADS_ERR_OK(status) ) {
192                         DEBUG(2,("ad_idmap_cached_connection: Failed to obtain schema details!\n"));
193                 }
194         }
195         
196         return status;
197 }
198
199 /************************************************************************
200  ***********************************************************************/
201
202 static NTSTATUS idmap_ad_initialize(struct idmap_domain *dom,
203                                     const char *params)
204 {
205         struct idmap_ad_context *ctx;
206         char *config_option;
207         const char *schema_mode = NULL; 
208
209         ctx = TALLOC_ZERO_P(dom, struct idmap_ad_context);
210         if (ctx == NULL) {
211                 DEBUG(0, ("Out of memory!\n"));
212                 return NT_STATUS_NO_MEMORY;
213         }
214
215         config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
216         if (config_option == NULL) {
217                 DEBUG(0, ("Out of memory!\n"));
218                 talloc_free(ctx);
219                 return NT_STATUS_NO_MEMORY;
220         }
221
222         /* default map type */
223         ctx->ad_map_type = WB_POSIX_MAP_RFC2307;
224
225         /* schema mode */
226         schema_mode = lp_parm_const_string(-1, config_option, "schema_mode", NULL);
227         if ( schema_mode && schema_mode[0] ) {
228                 if ( strequal(schema_mode, "sfu") )
229                         ctx->ad_map_type = WB_POSIX_MAP_SFU;
230                 else if ( strequal(schema_mode, "sfu20" ) )
231                         ctx->ad_map_type = WB_POSIX_MAP_SFU20;
232                 else if ( strequal(schema_mode, "rfc2307" ) )
233                         ctx->ad_map_type = WB_POSIX_MAP_RFC2307;
234                 else
235                         DEBUG(0,("idmap_ad_initialize: Unknown schema_mode (%s)\n",
236                                  schema_mode));
237         }
238
239         dom->private_data = ctx;
240
241         talloc_free(config_option);
242
243         return NT_STATUS_OK;
244 }
245
246 /************************************************************************
247  Search up to IDMAP_AD_MAX_IDS entries in maps for a match.
248  ***********************************************************************/
249
250 static struct id_map *find_map_by_id(struct id_map **maps, enum id_type type, uint32_t id)
251 {
252         int i;
253
254         for (i = 0; maps[i] && i<IDMAP_AD_MAX_IDS; i++) {
255                 if ((maps[i]->xid.type == type) && (maps[i]->xid.id == id)) {
256                         return maps[i];
257                 }
258         }
259
260         return NULL;    
261 }
262
263 /************************************************************************
264  Search up to IDMAP_AD_MAX_IDS entries in maps for a match
265  ***********************************************************************/
266
267 static struct id_map *find_map_by_sid(struct id_map **maps, struct dom_sid *sid)
268 {
269         int i;
270
271         for (i = 0; maps[i] && i<IDMAP_AD_MAX_IDS; i++) {
272                 if (dom_sid_equal(maps[i]->sid, sid)) {
273                         return maps[i];
274                 }
275         }
276
277         return NULL;    
278 }
279
280 /************************************************************************
281  ***********************************************************************/
282
283 static NTSTATUS idmap_ad_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
284 {
285         NTSTATUS ret;
286         TALLOC_CTX *memctx;
287         struct idmap_ad_context *ctx;
288         ADS_STATUS rc;
289         const char *attrs[] = { "sAMAccountType", 
290                                 "objectSid",
291                                 NULL, /* uidnumber */
292                                 NULL, /* gidnumber */
293                                 NULL };
294         LDAPMessage *res = NULL;
295         LDAPMessage *entry = NULL;
296         char *filter = NULL;
297         int idx = 0;
298         int bidx = 0;
299         int count;
300         int i;
301         char *u_filter = NULL;
302         char *g_filter = NULL;
303
304         /* initialize the status to avoid suprise */
305         for (i = 0; ids[i]; i++) {
306                 ids[i]->status = ID_UNKNOWN;
307         }
308         
309         /* Only do query if we are online */
310         if (idmap_is_offline()) {
311                 return NT_STATUS_FILE_IS_OFFLINE;
312         }
313
314         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
315
316         if ( (memctx = talloc_new(ctx)) == NULL ) {
317                 DEBUG(0, ("Out of memory!\n"));
318                 return NT_STATUS_NO_MEMORY;
319         }
320
321         rc = ad_idmap_cached_connection(dom);
322         if (!ADS_ERR_OK(rc)) {
323                 DEBUG(1, ("ADS uninitialized: %s\n", ads_errstr(rc)));
324                 ret = NT_STATUS_UNSUCCESSFUL;
325                 /* ret = ads_ntstatus(rc); */
326                 goto done;
327         }
328
329         attrs[2] = ctx->ad_schema->posix_uidnumber_attr;
330         attrs[3] = ctx->ad_schema->posix_gidnumber_attr;
331
332 again:
333         bidx = idx;
334         for (i = 0; (i < IDMAP_AD_MAX_IDS) && ids[idx]; i++, idx++) {
335                 switch (ids[idx]->xid.type) {
336                 case ID_TYPE_UID:     
337                         if ( ! u_filter) {
338                                 u_filter = talloc_asprintf(memctx, "(&(|"
339                                                            "(sAMAccountType=%d)"
340                                                            "(sAMAccountType=%d)"
341                                                            "(sAMAccountType=%d))(|",
342                                                            ATYPE_NORMAL_ACCOUNT,
343                                                            ATYPE_WORKSTATION_TRUST,
344                                                            ATYPE_INTERDOMAIN_TRUST);
345                         }
346                         u_filter = talloc_asprintf_append_buffer(u_filter, "(%s=%lu)",
347                                                           ctx->ad_schema->posix_uidnumber_attr,
348                                                           (unsigned long)ids[idx]->xid.id);
349                         CHECK_ALLOC_DONE(u_filter);
350                         break;
351                                 
352                 case ID_TYPE_GID:
353                         if ( ! g_filter) {
354                                 g_filter = talloc_asprintf(memctx, "(&(|"
355                                                            "(sAMAccountType=%d)"
356                                                            "(sAMAccountType=%d))(|",
357                                                            ATYPE_SECURITY_GLOBAL_GROUP,
358                                                            ATYPE_SECURITY_LOCAL_GROUP);
359                         }
360                         g_filter = talloc_asprintf_append_buffer(g_filter, "(%s=%lu)",
361                                                           ctx->ad_schema->posix_gidnumber_attr,
362                                                           (unsigned long)ids[idx]->xid.id);
363                         CHECK_ALLOC_DONE(g_filter);
364                         break;
365
366                 default:
367                         DEBUG(3, ("Error: mapping requested but Unknown ID type\n"));
368                         ids[idx]->status = ID_UNKNOWN;
369                         continue;
370                 }
371         }
372         filter = talloc_asprintf(memctx, "(|");
373         CHECK_ALLOC_DONE(filter);
374         if ( u_filter) {
375                 filter = talloc_asprintf_append_buffer(filter, "%s))", u_filter);
376                 CHECK_ALLOC_DONE(filter);
377                         TALLOC_FREE(u_filter);
378         }
379         if ( g_filter) {
380                 filter = talloc_asprintf_append_buffer(filter, "%s))", g_filter);
381                 CHECK_ALLOC_DONE(filter);
382                 TALLOC_FREE(g_filter);
383         }
384         filter = talloc_asprintf_append_buffer(filter, ")");
385         CHECK_ALLOC_DONE(filter);
386
387         rc = ads_search_retry(ctx->ads, &res, filter, attrs);
388         if (!ADS_ERR_OK(rc)) {
389                 DEBUG(1, ("ERROR: ads search returned: %s\n", ads_errstr(rc)));
390                 ret = NT_STATUS_UNSUCCESSFUL;
391                 goto done;
392         }
393
394         if ( (count = ads_count_replies(ctx->ads, res)) == 0 ) {
395                 DEBUG(10, ("No IDs found\n"));
396         }
397
398         entry = res;
399         for (i = 0; (i < count) && entry; i++) {
400                 struct dom_sid sid;
401                 enum id_type type;
402                 struct id_map *map;
403                 uint32_t id;
404                 uint32_t atype;
405
406                 if (i == 0) { /* first entry */
407                         entry = ads_first_entry(ctx->ads, entry);
408                 } else { /* following ones */
409                         entry = ads_next_entry(ctx->ads, entry);
410                 }
411
412                 if ( !entry ) {
413                         DEBUG(2, ("ERROR: Unable to fetch ldap entries from results\n"));
414                         break;
415                 }
416
417                 /* first check if the SID is present */
418                 if (!ads_pull_sid(ctx->ads, entry, "objectSid", &sid)) {
419                         DEBUG(2, ("Could not retrieve SID from entry\n"));
420                         continue;
421                 }
422
423                 /* get type */
424                 if (!ads_pull_uint32(ctx->ads, entry, "sAMAccountType", &atype)) {
425                         DEBUG(1, ("could not get SAM account type\n"));
426                         continue;
427                 }
428
429                 switch (atype & 0xF0000000) {
430                 case ATYPE_SECURITY_GLOBAL_GROUP:
431                 case ATYPE_SECURITY_LOCAL_GROUP:
432                         type = ID_TYPE_GID;
433                         break;
434                 case ATYPE_NORMAL_ACCOUNT:
435                 case ATYPE_WORKSTATION_TRUST:
436                 case ATYPE_INTERDOMAIN_TRUST:
437                         type = ID_TYPE_UID;
438                         break;
439                 default:
440                         DEBUG(1, ("unrecognized SAM account type %08x\n", atype));
441                         continue;
442                 }
443
444                 if (!ads_pull_uint32(ctx->ads, entry, (type==ID_TYPE_UID) ?
445                                                  ctx->ad_schema->posix_uidnumber_attr :
446                                                  ctx->ad_schema->posix_gidnumber_attr,
447                                      &id)) 
448                 {
449                         DEBUG(1, ("Could not get unix ID\n"));
450                         continue;
451                 }
452
453                 if (!idmap_unix_id_is_in_range(id, dom)) {
454                         DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
455                                 id, dom->low_id, dom->high_id));
456                         continue;
457                 }
458
459                 map = find_map_by_id(&ids[bidx], type, id);
460                 if (!map) {
461                         DEBUG(2, ("WARNING: couldn't match result with requested ID\n"));
462                         continue;
463                 }
464
465                 sid_copy(map->sid, &sid);
466
467                 /* mapped */
468                 map->status = ID_MAPPED;
469
470                 DEBUG(10, ("Mapped %s -> %lu (%d)\n", sid_string_dbg(map->sid),
471                            (unsigned long)map->xid.id,
472                            map->xid.type));
473         }
474
475         if (res) {
476                 ads_msgfree(ctx->ads, res);
477         }
478
479         if (ids[idx]) { /* still some values to map */
480                 goto again;
481         }
482
483         ret = NT_STATUS_OK;
484
485         /* mark all unknown/expired ones as unmapped */
486         for (i = 0; ids[i]; i++) {
487                 if (ids[i]->status != ID_MAPPED) 
488                         ids[i]->status = ID_UNMAPPED;
489         }
490
491 done:
492         talloc_free(memctx);
493         return ret;
494 }
495
496 /************************************************************************
497  ***********************************************************************/
498
499 static NTSTATUS idmap_ad_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
500 {
501         NTSTATUS ret;
502         TALLOC_CTX *memctx;
503         struct idmap_ad_context *ctx;
504         ADS_STATUS rc;
505         const char *attrs[] = { "sAMAccountType", 
506                                 "objectSid",
507                                 NULL, /* attr_uidnumber */
508                                 NULL, /* attr_gidnumber */
509                                 NULL };
510         LDAPMessage *res = NULL;
511         LDAPMessage *entry = NULL;
512         char *filter = NULL;
513         int idx = 0;
514         int bidx = 0;
515         int count;
516         int i;
517         char *sidstr;
518
519         /* initialize the status to avoid suprise */
520         for (i = 0; ids[i]; i++) {
521                 ids[i]->status = ID_UNKNOWN;
522         }
523
524         /* Only do query if we are online */
525         if (idmap_is_offline()) {
526                 return NT_STATUS_FILE_IS_OFFLINE;
527         }
528
529         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);      
530
531         if ( (memctx = talloc_new(ctx)) == NULL ) {             
532                 DEBUG(0, ("Out of memory!\n"));
533                 return NT_STATUS_NO_MEMORY;
534         }
535
536         rc = ad_idmap_cached_connection(dom);
537         if (!ADS_ERR_OK(rc)) {
538                 DEBUG(1, ("ADS uninitialized: %s\n", ads_errstr(rc)));
539                 ret = NT_STATUS_UNSUCCESSFUL;
540                 /* ret = ads_ntstatus(rc); */
541                 goto done;
542         }
543
544         if (ctx->ad_schema == NULL) {
545                 DEBUG(0, ("haven't got ctx->ad_schema ! \n"));
546                 ret = NT_STATUS_UNSUCCESSFUL;
547                 goto done;
548         }
549
550         attrs[2] = ctx->ad_schema->posix_uidnumber_attr;
551         attrs[3] = ctx->ad_schema->posix_gidnumber_attr;
552
553 again:
554         filter = talloc_asprintf(memctx, "(&(|"
555                                  "(sAMAccountType=%d)(sAMAccountType=%d)(sAMAccountType=%d)" /* user account types */
556                                  "(sAMAccountType=%d)(sAMAccountType=%d)" /* group account types */
557                                  ")(|",
558                                  ATYPE_NORMAL_ACCOUNT, ATYPE_WORKSTATION_TRUST, ATYPE_INTERDOMAIN_TRUST,
559                                  ATYPE_SECURITY_GLOBAL_GROUP, ATYPE_SECURITY_LOCAL_GROUP);
560                 
561         CHECK_ALLOC_DONE(filter);
562
563         bidx = idx;
564         for (i = 0; (i < IDMAP_AD_MAX_IDS) && ids[idx]; i++, idx++) {
565
566                 ids[idx]->status = ID_UNKNOWN;
567
568                 sidstr = ldap_encode_ndr_dom_sid(talloc_tos(), ids[idx]->sid);
569                 filter = talloc_asprintf_append_buffer(filter, "(objectSid=%s)", sidstr);
570                         
571                 TALLOC_FREE(sidstr);
572                 CHECK_ALLOC_DONE(filter);
573         }
574         filter = talloc_asprintf_append_buffer(filter, "))");
575         CHECK_ALLOC_DONE(filter);
576         DEBUG(10, ("Filter: [%s]\n", filter));
577
578         rc = ads_search_retry(ctx->ads, &res, filter, attrs);
579         if (!ADS_ERR_OK(rc)) {
580                 DEBUG(1, ("ERROR: ads search returned: %s\n", ads_errstr(rc)));
581                 ret = NT_STATUS_UNSUCCESSFUL;
582                 goto done;
583         }
584
585         if ( (count = ads_count_replies(ctx->ads, res)) == 0 ) {
586                 DEBUG(10, ("No IDs found\n"));
587         }
588
589         entry = res;    
590         for (i = 0; (i < count) && entry; i++) {
591                 struct dom_sid sid;
592                 enum id_type type;
593                 struct id_map *map;
594                 uint32_t id;
595                 uint32_t atype;
596
597                 if (i == 0) { /* first entry */
598                         entry = ads_first_entry(ctx->ads, entry);
599                 } else { /* following ones */
600                         entry = ads_next_entry(ctx->ads, entry);
601                 }
602
603                 if ( !entry ) {
604                         DEBUG(2, ("ERROR: Unable to fetch ldap entries from results\n"));
605                         break;
606                 }
607
608                 /* first check if the SID is present */
609                 if (!ads_pull_sid(ctx->ads, entry, "objectSid", &sid)) {
610                         DEBUG(2, ("Could not retrieve SID from entry\n"));
611                         continue;
612                 }
613
614                 map = find_map_by_sid(&ids[bidx], &sid);
615                 if (!map) {
616                         DEBUG(2, ("WARNING: couldn't match result with requested SID\n"));
617                         continue;
618                 }
619
620                 /* get type */
621                 if (!ads_pull_uint32(ctx->ads, entry, "sAMAccountType", &atype)) {
622                         DEBUG(1, ("could not get SAM account type\n"));
623                         continue;
624                 }
625
626                 switch (atype & 0xF0000000) {
627                 case ATYPE_SECURITY_GLOBAL_GROUP:
628                 case ATYPE_SECURITY_LOCAL_GROUP:
629                         type = ID_TYPE_GID;
630                         break;
631                 case ATYPE_NORMAL_ACCOUNT:
632                 case ATYPE_WORKSTATION_TRUST:
633                 case ATYPE_INTERDOMAIN_TRUST:
634                         type = ID_TYPE_UID;
635                         break;
636                 default:
637                         DEBUG(1, ("unrecognized SAM account type %08x\n", atype));
638                         continue;
639                 }
640
641                 if (!ads_pull_uint32(ctx->ads, entry, (type==ID_TYPE_UID) ?
642                                                  ctx->ad_schema->posix_uidnumber_attr :
643                                                  ctx->ad_schema->posix_gidnumber_attr,
644                                      &id)) 
645                 {
646                         DEBUG(1, ("Could not get unix ID\n"));
647                         continue;
648                 }
649                 if (!idmap_unix_id_is_in_range(id, dom)) {
650                         DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
651                                 id, dom->low_id, dom->high_id));
652                         continue;
653                 }
654
655                 /* mapped */
656                 map->xid.type = type;
657                 map->xid.id = id;
658                 map->status = ID_MAPPED;
659
660                 DEBUG(10, ("Mapped %s -> %lu (%d)\n", sid_string_dbg(map->sid),
661                            (unsigned long)map->xid.id,
662                            map->xid.type));
663         }
664
665         if (res) {
666                 ads_msgfree(ctx->ads, res);
667         }
668
669         if (ids[idx]) { /* still some values to map */
670                 goto again;
671         }
672
673         ret = NT_STATUS_OK;
674
675         /* mark all unknwoni/expired ones as unmapped */
676         for (i = 0; ids[i]; i++) {
677                 if (ids[i]->status != ID_MAPPED) 
678                         ids[i]->status = ID_UNMAPPED;
679         }
680
681 done:
682         talloc_free(memctx);
683         return ret;
684 }
685
686 /************************************************************************
687  ***********************************************************************/
688
689 static NTSTATUS idmap_ad_close(struct idmap_domain *dom)
690 {
691         struct idmap_ad_context * ctx;
692
693         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
694
695         if (ctx->ads != NULL) {
696                 /* we own this ADS_STRUCT so make sure it goes away */
697                 ctx->ads->is_mine = True;
698                 ads_destroy( &ctx->ads );
699                 ctx->ads = NULL;
700         }
701
702         TALLOC_FREE( ctx->ad_schema );
703         
704         return NT_STATUS_OK;
705 }
706
707 /*
708  * nss_info_{sfu,sfu20,rfc2307}
709  */
710
711 /************************************************************************
712  Initialize the {sfu,sfu20,rfc2307} state
713  ***********************************************************************/
714
715 static const char *wb_posix_map_unknown_string = "WB_POSIX_MAP_UNKNOWN";
716 static const char *wb_posix_map_template_string = "WB_POSIX_MAP_TEMPLATE";
717 static const char *wb_posix_map_sfu_string = "WB_POSIX_MAP_SFU";
718 static const char *wb_posix_map_sfu20_string = "WB_POSIX_MAP_SFU20";
719 static const char *wb_posix_map_rfc2307_string = "WB_POSIX_MAP_RFC2307";
720 static const char *wb_posix_map_unixinfo_string = "WB_POSIX_MAP_UNIXINFO";
721
722 static const char *ad_map_type_string(enum wb_posix_mapping map_type)
723 {
724         switch (map_type) {
725                 case WB_POSIX_MAP_TEMPLATE:
726                         return wb_posix_map_template_string;
727                 case WB_POSIX_MAP_SFU:
728                         return wb_posix_map_sfu_string;
729                 case WB_POSIX_MAP_SFU20:
730                         return wb_posix_map_sfu20_string;
731                 case WB_POSIX_MAP_RFC2307:
732                         return wb_posix_map_rfc2307_string;
733                 case WB_POSIX_MAP_UNIXINFO:
734                         return wb_posix_map_unixinfo_string;
735                 default:
736                         return wb_posix_map_unknown_string;
737         }
738 }
739
740 static NTSTATUS nss_ad_generic_init(struct nss_domain_entry *e,
741                                     enum wb_posix_mapping new_ad_map_type)
742 {
743         struct idmap_domain *dom;
744         struct idmap_ad_context *ctx;
745
746         if (e->state != NULL) {
747                 dom = talloc_get_type(e->state, struct idmap_domain);
748         } else {
749                 dom = TALLOC_ZERO_P(e, struct idmap_domain);
750                 if (dom == NULL) {
751                         DEBUG(0, ("Out of memory!\n"));
752                         return NT_STATUS_NO_MEMORY;
753                 }
754                 e->state = dom;
755         }
756
757         if (e->domain != NULL) {
758                 dom->name = talloc_strdup(dom, e->domain);
759                 if (dom->name == NULL) {
760                         DEBUG(0, ("Out of memory!\n"));
761                         return NT_STATUS_NO_MEMORY;
762                 }
763         }
764
765         if (dom->private_data != NULL) {
766                 ctx = talloc_get_type(dom->private_data,
767                                       struct idmap_ad_context);
768         } else {
769                 ctx = TALLOC_ZERO_P(dom, struct idmap_ad_context);
770                 if (ctx == NULL) {
771                         DEBUG(0, ("Out of memory!\n"));
772                         return NT_STATUS_NO_MEMORY;
773                 }
774                 ctx->ad_map_type = WB_POSIX_MAP_RFC2307;
775                 dom->private_data = ctx;
776         }
777
778         if ((ctx->ad_map_type != WB_POSIX_MAP_UNKNOWN) &&
779             (ctx->ad_map_type != new_ad_map_type))
780         {
781                 DEBUG(2, ("nss_ad_generic_init: "
782                           "Warning: overriding previously set posix map type "
783                           "%s for domain %s with map type %s.\n",
784                           ad_map_type_string(ctx->ad_map_type),
785                           dom->name,
786                           ad_map_type_string(new_ad_map_type)));
787         }
788
789         ctx->ad_map_type = new_ad_map_type;
790
791         return NT_STATUS_OK;
792 }
793
794 static NTSTATUS nss_sfu_init( struct nss_domain_entry *e )
795 {
796         return nss_ad_generic_init(e, WB_POSIX_MAP_SFU);
797 }
798
799 static NTSTATUS nss_sfu20_init( struct nss_domain_entry *e )
800 {
801         return nss_ad_generic_init(e, WB_POSIX_MAP_SFU20);
802 }
803
804 static NTSTATUS nss_rfc2307_init( struct nss_domain_entry *e )
805 {
806         return nss_ad_generic_init(e, WB_POSIX_MAP_RFC2307);
807 }
808
809
810 /************************************************************************
811  ***********************************************************************/
812
813 static NTSTATUS nss_ad_get_info( struct nss_domain_entry *e, 
814                                   const struct dom_sid *sid,
815                                   TALLOC_CTX *mem_ctx,
816                                   ADS_STRUCT *ads, 
817                                   LDAPMessage *msg,
818                                   const char **homedir,
819                                   const char **shell,
820                                   const char **gecos,
821                                   uint32 *gid )
822 {
823         const char *attrs[] = {NULL, /* attr_homedir */
824                                NULL, /* attr_shell */
825                                NULL, /* attr_gecos */
826                                NULL, /* attr_gidnumber */
827                                NULL };
828         char *filter = NULL;
829         LDAPMessage *msg_internal = NULL;
830         ADS_STATUS ads_status = ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
831         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
832         char *sidstr = NULL;
833         struct idmap_domain *dom;
834         struct idmap_ad_context *ctx;
835
836         DEBUG(10, ("nss_ad_get_info called for sid [%s] in domain '%s'\n",
837                    sid_string_dbg(sid), e->domain?e->domain:"NULL"));
838
839         /* Only do query if we are online */
840         if (idmap_is_offline()) {
841                 return NT_STATUS_FILE_IS_OFFLINE;
842         }
843
844         dom = talloc_get_type(e->state, struct idmap_domain);
845         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
846
847         ads_status = ad_idmap_cached_connection(dom);
848         if (!ADS_ERR_OK(ads_status)) {
849                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
850         }
851
852         if (!ctx->ad_schema) {
853                 DEBUG(10, ("nss_ad_get_info: no ad_schema configured!\n"));
854                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
855         }
856
857         if (!sid || !homedir || !shell || !gecos) {
858                 return NT_STATUS_INVALID_PARAMETER;
859         }
860
861         /* See if we can use the ADS connection struct swe were given */
862
863 #if 0
864         if (ads) {
865                 DEBUG(10, ("nss_ad_get_info: using given ads connection and "
866                            "LDAP message (%p)\n", msg));
867
868                 *homedir = ads_pull_string( ads, mem_ctx, msg, ctx->ad_schema->posix_homedir_attr );
869                 *shell   = ads_pull_string( ads, mem_ctx, msg, ctx->ad_schema->posix_shell_attr );
870                 *gecos   = ads_pull_string( ads, mem_ctx, msg, ctx->ad_schema->posix_gecos_attr );
871
872                 if (gid) {
873                         if ( !ads_pull_uint32(ads, msg, ctx->ad_schema->posix_gidnumber_attr, gid ) )
874                                 *gid = (uint32)-1;
875                 }
876
877                 nt_status = NT_STATUS_OK;
878                 goto done;
879         }
880 #endif
881
882         /* Have to do our own query */
883
884         DEBUG(10, ("nss_ad_get_info: no ads connection given, doing our "
885                    "own query\n"));
886
887         attrs[0] = ctx->ad_schema->posix_homedir_attr;
888         attrs[1] = ctx->ad_schema->posix_shell_attr;
889         attrs[2] = ctx->ad_schema->posix_gecos_attr;
890         attrs[3] = ctx->ad_schema->posix_gidnumber_attr;
891
892         sidstr = ldap_encode_ndr_dom_sid(mem_ctx, sid);
893         filter = talloc_asprintf(mem_ctx, "(objectSid=%s)", sidstr);
894         TALLOC_FREE(sidstr);
895
896         if (!filter) {
897                 nt_status = NT_STATUS_NO_MEMORY;
898                 goto done;
899         }
900
901         ads_status = ads_search_retry(ctx->ads, &msg_internal, filter, attrs);
902         if (!ADS_ERR_OK(ads_status)) {
903                 nt_status = ads_ntstatus(ads_status);
904                 goto done;
905         }
906
907         *homedir = ads_pull_string(ctx->ads, mem_ctx, msg_internal, ctx->ad_schema->posix_homedir_attr);
908         *shell   = ads_pull_string(ctx->ads, mem_ctx, msg_internal, ctx->ad_schema->posix_shell_attr);
909         *gecos   = ads_pull_string(ctx->ads, mem_ctx, msg_internal, ctx->ad_schema->posix_gecos_attr);
910
911         if (gid) {
912                 if (!ads_pull_uint32(ctx->ads, msg_internal, ctx->ad_schema->posix_gidnumber_attr, gid))
913                         *gid = (uint32)-1;
914         }
915
916         nt_status = NT_STATUS_OK;
917
918 done:
919         if (msg_internal) {
920                 ads_msgfree(ctx->ads, msg_internal);
921         }
922
923         return nt_status;
924 }
925
926 /**********************************************************************
927  *********************************************************************/
928
929 static NTSTATUS nss_ad_map_to_alias(TALLOC_CTX *mem_ctx,
930                                     struct nss_domain_entry *e,
931                                     const char *name,
932                                     char **alias)
933 {
934         const char *attrs[] = {NULL, /* attr_uid */
935                                NULL };
936         char *filter = NULL;
937         LDAPMessage *msg = NULL;
938         ADS_STATUS ads_status = ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
939         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
940         struct idmap_domain *dom;
941         struct idmap_ad_context *ctx = NULL;
942
943         /* Check incoming parameters */
944
945         if ( !e || !e->domain || !name || !*alias) {
946                 nt_status = NT_STATUS_INVALID_PARAMETER;
947                 goto done;
948         }
949
950         /* Only do query if we are online */
951
952         if (idmap_is_offline()) {
953                 nt_status = NT_STATUS_FILE_IS_OFFLINE;
954                 goto done;
955         }
956
957         dom = talloc_get_type(e->state, struct idmap_domain);
958         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
959
960         ads_status = ad_idmap_cached_connection(dom);
961         if (!ADS_ERR_OK(ads_status)) {
962                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
963         }
964
965         if (!ctx->ad_schema) {
966                 nt_status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
967                 goto done;
968         }
969
970         attrs[0] = ctx->ad_schema->posix_uid_attr;
971
972         filter = talloc_asprintf(mem_ctx,
973                                  "(sAMAccountName=%s)",
974                                  name);
975         if (!filter) {
976                 nt_status = NT_STATUS_NO_MEMORY;
977                 goto done;
978         }
979
980         ads_status = ads_search_retry(ctx->ads, &msg, filter, attrs);
981         if (!ADS_ERR_OK(ads_status)) {
982                 nt_status = ads_ntstatus(ads_status);
983                 goto done;
984         }
985
986         *alias = ads_pull_string(ctx->ads, mem_ctx, msg, ctx->ad_schema->posix_uid_attr);
987
988         if (!*alias) {
989                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
990         }
991
992         nt_status = NT_STATUS_OK;
993
994 done:
995         if (filter) {
996                 talloc_destroy(filter);
997         }
998         if (msg) {
999                 ads_msgfree(ctx->ads, msg);
1000         }
1001
1002         return nt_status;
1003 }
1004
1005 /**********************************************************************
1006  *********************************************************************/
1007
1008 static NTSTATUS nss_ad_map_from_alias( TALLOC_CTX *mem_ctx,
1009                                              struct nss_domain_entry *e,
1010                                              const char *alias,
1011                                              char **name )
1012 {
1013         const char *attrs[] = {"sAMAccountName",
1014                                NULL };
1015         char *filter = NULL;
1016         LDAPMessage *msg = NULL;
1017         ADS_STATUS ads_status = ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
1018         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
1019         char *username;
1020         struct idmap_domain *dom;
1021         struct idmap_ad_context *ctx = NULL;
1022
1023         /* Check incoming parameters */
1024
1025         if ( !alias || !name) {
1026                 nt_status = NT_STATUS_INVALID_PARAMETER;
1027                 goto done;
1028         }
1029
1030         /* Only do query if we are online */
1031
1032         if (idmap_is_offline()) {
1033                 nt_status = NT_STATUS_FILE_IS_OFFLINE;
1034                 goto done;
1035         }
1036
1037         dom = talloc_get_type(e->state, struct idmap_domain);
1038         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
1039
1040         ads_status = ad_idmap_cached_connection(dom);
1041         if (!ADS_ERR_OK(ads_status)) {
1042                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1043         }
1044
1045         if (!ctx->ad_schema) {
1046                 nt_status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
1047                 goto done;
1048         }
1049
1050         filter = talloc_asprintf(mem_ctx,
1051                                  "(%s=%s)",
1052                                  ctx->ad_schema->posix_uid_attr,
1053                                  alias);
1054         if (!filter) {
1055                 nt_status = NT_STATUS_NO_MEMORY;
1056                 goto done;
1057         }
1058
1059         ads_status = ads_search_retry(ctx->ads, &msg, filter, attrs);
1060         if (!ADS_ERR_OK(ads_status)) {
1061                 nt_status = ads_ntstatus(ads_status);
1062                 goto done;
1063         }
1064
1065         username = ads_pull_string(ctx->ads, mem_ctx, msg,
1066                                    "sAMAccountName");
1067         if (!username) {
1068                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1069         }
1070
1071         *name = talloc_asprintf(mem_ctx, "%s\\%s",
1072                                 lp_workgroup(),
1073                                 username);
1074         if (!*name) {
1075                 nt_status = NT_STATUS_NO_MEMORY;
1076                 goto done;
1077         }
1078
1079         nt_status = NT_STATUS_OK;
1080
1081 done:
1082         if (filter) {
1083                 talloc_destroy(filter);
1084         }
1085         if (msg) {
1086                 ads_msgfree(ctx->ads, msg);
1087         }
1088
1089         return nt_status;
1090 }
1091
1092
1093 /************************************************************************
1094  ***********************************************************************/
1095
1096 static NTSTATUS nss_ad_close( void )
1097 {
1098         /* nothing to do.  All memory is free()'d by the idmap close_fn() */
1099
1100         return NT_STATUS_OK;
1101 }
1102
1103 /************************************************************************
1104  Function dispatch tables for the idmap and nss plugins
1105  ***********************************************************************/
1106
1107 static struct idmap_methods ad_methods = {
1108         .init            = idmap_ad_initialize,
1109         .unixids_to_sids = idmap_ad_unixids_to_sids,
1110         .sids_to_unixids = idmap_ad_sids_to_unixids,
1111         .close_fn        = idmap_ad_close
1112 };
1113
1114 /* The SFU and RFC2307 NSS plugins share everything but the init
1115    function which sets the intended schema model to use */
1116   
1117 static struct nss_info_methods nss_rfc2307_methods = {
1118         .init           = nss_rfc2307_init,
1119         .get_nss_info   = nss_ad_get_info,
1120         .map_to_alias   = nss_ad_map_to_alias,
1121         .map_from_alias = nss_ad_map_from_alias,
1122         .close_fn       = nss_ad_close
1123 };
1124
1125 static struct nss_info_methods nss_sfu_methods = {
1126         .init           = nss_sfu_init,
1127         .get_nss_info   = nss_ad_get_info,
1128         .map_to_alias   = nss_ad_map_to_alias,
1129         .map_from_alias = nss_ad_map_from_alias,
1130         .close_fn       = nss_ad_close
1131 };
1132
1133 static struct nss_info_methods nss_sfu20_methods = {
1134         .init           = nss_sfu20_init,
1135         .get_nss_info   = nss_ad_get_info,
1136         .map_to_alias   = nss_ad_map_to_alias,
1137         .map_from_alias = nss_ad_map_from_alias,
1138         .close_fn       = nss_ad_close
1139 };
1140
1141
1142
1143 /************************************************************************
1144  Initialize the plugins
1145  ***********************************************************************/
1146
1147 NTSTATUS idmap_ad_init(void)
1148 {
1149         static NTSTATUS status_idmap_ad = NT_STATUS_UNSUCCESSFUL;
1150         static NTSTATUS status_nss_rfc2307 = NT_STATUS_UNSUCCESSFUL;
1151         static NTSTATUS status_nss_sfu = NT_STATUS_UNSUCCESSFUL;
1152         static NTSTATUS status_nss_sfu20 = NT_STATUS_UNSUCCESSFUL;
1153
1154         /* Always register the AD method first in order to get the
1155            idmap_domain interface called */
1156
1157         if ( !NT_STATUS_IS_OK(status_idmap_ad) ) {
1158                 status_idmap_ad = smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, 
1159                                                      "ad", &ad_methods);
1160                 if ( !NT_STATUS_IS_OK(status_idmap_ad) )
1161                         return status_idmap_ad;         
1162         }
1163         
1164         if ( !NT_STATUS_IS_OK( status_nss_rfc2307 ) ) {
1165                 status_nss_rfc2307 = smb_register_idmap_nss(SMB_NSS_INFO_INTERFACE_VERSION,
1166                                                             "rfc2307",  &nss_rfc2307_methods );         
1167                 if ( !NT_STATUS_IS_OK(status_nss_rfc2307) )
1168                         return status_nss_rfc2307;
1169         }
1170
1171         if ( !NT_STATUS_IS_OK( status_nss_sfu ) ) {
1172                 status_nss_sfu = smb_register_idmap_nss(SMB_NSS_INFO_INTERFACE_VERSION,
1173                                                         "sfu",  &nss_sfu_methods );             
1174                 if ( !NT_STATUS_IS_OK(status_nss_sfu) )
1175                         return status_nss_sfu;          
1176         }
1177
1178         if ( !NT_STATUS_IS_OK( status_nss_sfu20 ) ) {
1179                 status_nss_sfu20 = smb_register_idmap_nss(SMB_NSS_INFO_INTERFACE_VERSION,
1180                                                         "sfu20",  &nss_sfu20_methods );         
1181                 if ( !NT_STATUS_IS_OK(status_nss_sfu20) )
1182                         return status_nss_sfu20;                
1183         }
1184
1185         return NT_STATUS_OK;    
1186 }
1187