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