s3:winbindd/idmap_ad.c: update my C
[rusty/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_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 0
863         if (ads) {
864                 DEBUG(10, ("nss_ad_get_info: using given ads connection and "
865                            "LDAP message (%p)\n", msg));
866
867                 *homedir = ads_pull_string( ads, mem_ctx, msg, ctx->ad_schema->posix_homedir_attr );
868                 *shell   = ads_pull_string( ads, mem_ctx, msg, ctx->ad_schema->posix_shell_attr );
869                 *gecos   = ads_pull_string( ads, mem_ctx, msg, ctx->ad_schema->posix_gecos_attr );
870
871                 if (gid) {
872                         if ( !ads_pull_uint32(ads, msg, ctx->ad_schema->posix_gidnumber_attr, gid ) )
873                                 *gid = (uint32)-1;
874                 }
875
876                 nt_status = NT_STATUS_OK;
877                 goto done;
878         }
879 #endif
880
881         /* Have to do our own query */
882
883         DEBUG(10, ("nss_ad_get_info: no ads connection given, doing our "
884                    "own query\n"));
885
886         attrs[0] = ctx->ad_schema->posix_homedir_attr;
887         attrs[1] = ctx->ad_schema->posix_shell_attr;
888         attrs[2] = ctx->ad_schema->posix_gecos_attr;
889         attrs[3] = ctx->ad_schema->posix_gidnumber_attr;
890
891         sidstr = ldap_encode_ndr_dom_sid(mem_ctx, sid);
892         filter = talloc_asprintf(mem_ctx, "(objectSid=%s)", sidstr);
893         TALLOC_FREE(sidstr);
894
895         if (!filter) {
896                 nt_status = NT_STATUS_NO_MEMORY;
897                 goto done;
898         }
899
900         ads_status = ads_search_retry(ctx->ads, &msg_internal, filter, attrs);
901         if (!ADS_ERR_OK(ads_status)) {
902                 nt_status = ads_ntstatus(ads_status);
903                 goto done;
904         }
905
906         *homedir = ads_pull_string(ctx->ads, mem_ctx, msg_internal, ctx->ad_schema->posix_homedir_attr);
907         *shell   = ads_pull_string(ctx->ads, mem_ctx, msg_internal, ctx->ad_schema->posix_shell_attr);
908         *gecos   = ads_pull_string(ctx->ads, mem_ctx, msg_internal, ctx->ad_schema->posix_gecos_attr);
909
910         if (gid) {
911                 if (!ads_pull_uint32(ctx->ads, msg_internal, ctx->ad_schema->posix_gidnumber_attr, gid))
912                         *gid = (uint32)-1;
913         }
914
915         nt_status = NT_STATUS_OK;
916
917 done:
918         if (msg_internal) {
919                 ads_msgfree(ctx->ads, msg_internal);
920         }
921
922         return nt_status;
923 }
924
925 /**********************************************************************
926  *********************************************************************/
927
928 static NTSTATUS nss_ad_map_to_alias(TALLOC_CTX *mem_ctx,
929                                     struct nss_domain_entry *e,
930                                     const char *name,
931                                     char **alias)
932 {
933         const char *attrs[] = {NULL, /* attr_uid */
934                                NULL };
935         char *filter = NULL;
936         LDAPMessage *msg = NULL;
937         ADS_STATUS ads_status = ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
938         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
939         struct idmap_domain *dom;
940         struct idmap_ad_context *ctx = NULL;
941
942         /* Check incoming parameters */
943
944         if ( !e || !e->domain || !name || !*alias) {
945                 nt_status = NT_STATUS_INVALID_PARAMETER;
946                 goto done;
947         }
948
949         /* Only do query if we are online */
950
951         if (idmap_is_offline()) {
952                 nt_status = NT_STATUS_FILE_IS_OFFLINE;
953                 goto done;
954         }
955
956         dom = talloc_get_type(e->state, struct idmap_domain);
957         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
958
959         ads_status = ad_idmap_cached_connection(dom);
960         if (!ADS_ERR_OK(ads_status)) {
961                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
962         }
963
964         if (!ctx->ad_schema) {
965                 nt_status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
966                 goto done;
967         }
968
969         attrs[0] = ctx->ad_schema->posix_uid_attr;
970
971         filter = talloc_asprintf(mem_ctx,
972                                  "(sAMAccountName=%s)",
973                                  name);
974         if (!filter) {
975                 nt_status = NT_STATUS_NO_MEMORY;
976                 goto done;
977         }
978
979         ads_status = ads_search_retry(ctx->ads, &msg, filter, attrs);
980         if (!ADS_ERR_OK(ads_status)) {
981                 nt_status = ads_ntstatus(ads_status);
982                 goto done;
983         }
984
985         *alias = ads_pull_string(ctx->ads, mem_ctx, msg, ctx->ad_schema->posix_uid_attr);
986
987         if (!*alias) {
988                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
989         }
990
991         nt_status = NT_STATUS_OK;
992
993 done:
994         if (filter) {
995                 talloc_destroy(filter);
996         }
997         if (msg) {
998                 ads_msgfree(ctx->ads, msg);
999         }
1000
1001         return nt_status;
1002 }
1003
1004 /**********************************************************************
1005  *********************************************************************/
1006
1007 static NTSTATUS nss_ad_map_from_alias( TALLOC_CTX *mem_ctx,
1008                                              struct nss_domain_entry *e,
1009                                              const char *alias,
1010                                              char **name )
1011 {
1012         const char *attrs[] = {"sAMAccountName",
1013                                NULL };
1014         char *filter = NULL;
1015         LDAPMessage *msg = NULL;
1016         ADS_STATUS ads_status = ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
1017         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
1018         char *username;
1019         struct idmap_domain *dom;
1020         struct idmap_ad_context *ctx = NULL;
1021
1022         /* Check incoming parameters */
1023
1024         if ( !alias || !name) {
1025                 nt_status = NT_STATUS_INVALID_PARAMETER;
1026                 goto done;
1027         }
1028
1029         /* Only do query if we are online */
1030
1031         if (idmap_is_offline()) {
1032                 nt_status = NT_STATUS_FILE_IS_OFFLINE;
1033                 goto done;
1034         }
1035
1036         dom = talloc_get_type(e->state, struct idmap_domain);
1037         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
1038
1039         ads_status = ad_idmap_cached_connection(dom);
1040         if (!ADS_ERR_OK(ads_status)) {
1041                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1042         }
1043
1044         if (!ctx->ad_schema) {
1045                 nt_status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
1046                 goto done;
1047         }
1048
1049         filter = talloc_asprintf(mem_ctx,
1050                                  "(%s=%s)",
1051                                  ctx->ad_schema->posix_uid_attr,
1052                                  alias);
1053         if (!filter) {
1054                 nt_status = NT_STATUS_NO_MEMORY;
1055                 goto done;
1056         }
1057
1058         ads_status = ads_search_retry(ctx->ads, &msg, filter, attrs);
1059         if (!ADS_ERR_OK(ads_status)) {
1060                 nt_status = ads_ntstatus(ads_status);
1061                 goto done;
1062         }
1063
1064         username = ads_pull_string(ctx->ads, mem_ctx, msg,
1065                                    "sAMAccountName");
1066         if (!username) {
1067                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1068         }
1069
1070         *name = talloc_asprintf(mem_ctx, "%s\\%s",
1071                                 lp_workgroup(),
1072                                 username);
1073         if (!*name) {
1074                 nt_status = NT_STATUS_NO_MEMORY;
1075                 goto done;
1076         }
1077
1078         nt_status = NT_STATUS_OK;
1079
1080 done:
1081         if (filter) {
1082                 talloc_destroy(filter);
1083         }
1084         if (msg) {
1085                 ads_msgfree(ctx->ads, msg);
1086         }
1087
1088         return nt_status;
1089 }
1090
1091
1092 /************************************************************************
1093  ***********************************************************************/
1094
1095 static NTSTATUS nss_ad_close( void )
1096 {
1097         /* nothing to do.  All memory is free()'d by the idmap close_fn() */
1098
1099         return NT_STATUS_OK;
1100 }
1101
1102 /************************************************************************
1103  Function dispatch tables for the idmap and nss plugins
1104  ***********************************************************************/
1105
1106 static struct idmap_methods ad_methods = {
1107         .init            = idmap_ad_initialize,
1108         .unixids_to_sids = idmap_ad_unixids_to_sids,
1109         .sids_to_unixids = idmap_ad_sids_to_unixids,
1110         .close_fn        = idmap_ad_close
1111 };
1112
1113 /* The SFU and RFC2307 NSS plugins share everything but the init
1114    function which sets the intended schema model to use */
1115   
1116 static struct nss_info_methods nss_rfc2307_methods = {
1117         .init           = nss_rfc2307_init,
1118         .get_nss_info   = nss_ad_get_info,
1119         .map_to_alias   = nss_ad_map_to_alias,
1120         .map_from_alias = nss_ad_map_from_alias,
1121         .close_fn       = nss_ad_close
1122 };
1123
1124 static struct nss_info_methods nss_sfu_methods = {
1125         .init           = nss_sfu_init,
1126         .get_nss_info   = nss_ad_get_info,
1127         .map_to_alias   = nss_ad_map_to_alias,
1128         .map_from_alias = nss_ad_map_from_alias,
1129         .close_fn       = nss_ad_close
1130 };
1131
1132 static struct nss_info_methods nss_sfu20_methods = {
1133         .init           = nss_sfu20_init,
1134         .get_nss_info   = nss_ad_get_info,
1135         .map_to_alias   = nss_ad_map_to_alias,
1136         .map_from_alias = nss_ad_map_from_alias,
1137         .close_fn       = nss_ad_close
1138 };
1139
1140
1141
1142 /************************************************************************
1143  Initialize the plugins
1144  ***********************************************************************/
1145
1146 NTSTATUS idmap_ad_init(void)
1147 {
1148         static NTSTATUS status_idmap_ad = NT_STATUS_UNSUCCESSFUL;
1149         static NTSTATUS status_nss_rfc2307 = NT_STATUS_UNSUCCESSFUL;
1150         static NTSTATUS status_nss_sfu = NT_STATUS_UNSUCCESSFUL;
1151         static NTSTATUS status_nss_sfu20 = NT_STATUS_UNSUCCESSFUL;
1152
1153         /* Always register the AD method first in order to get the
1154            idmap_domain interface called */
1155
1156         if ( !NT_STATUS_IS_OK(status_idmap_ad) ) {
1157                 status_idmap_ad = smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, 
1158                                                      "ad", &ad_methods);
1159                 if ( !NT_STATUS_IS_OK(status_idmap_ad) )
1160                         return status_idmap_ad;         
1161         }
1162         
1163         if ( !NT_STATUS_IS_OK( status_nss_rfc2307 ) ) {
1164                 status_nss_rfc2307 = smb_register_idmap_nss(SMB_NSS_INFO_INTERFACE_VERSION,
1165                                                             "rfc2307",  &nss_rfc2307_methods );         
1166                 if ( !NT_STATUS_IS_OK(status_nss_rfc2307) )
1167                         return status_nss_rfc2307;
1168         }
1169
1170         if ( !NT_STATUS_IS_OK( status_nss_sfu ) ) {
1171                 status_nss_sfu = smb_register_idmap_nss(SMB_NSS_INFO_INTERFACE_VERSION,
1172                                                         "sfu",  &nss_sfu_methods );             
1173                 if ( !NT_STATUS_IS_OK(status_nss_sfu) )
1174                         return status_nss_sfu;          
1175         }
1176
1177         if ( !NT_STATUS_IS_OK( status_nss_sfu20 ) ) {
1178                 status_nss_sfu20 = smb_register_idmap_nss(SMB_NSS_INFO_INTERFACE_VERSION,
1179                                                         "sfu20",  &nss_sfu20_methods );         
1180                 if ( !NT_STATUS_IS_OK(status_nss_sfu20) )
1181                         return status_nss_sfu20;                
1182         }
1183
1184         return NT_STATUS_OK;    
1185 }
1186