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