winbind: Save lines with talloc_asprintf_addbuf()
[samba.git] / source3 / winbindd / idmap_ad.c
1 /*
2  * idmap_ad: map between Active Directory and RFC 2307 accounts
3  *
4  * Copyright (C) Volker Lendecke 2015
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "includes.h"
21 #include "winbindd.h"
22 #include "libsmb/namequery.h"
23 #include "idmap.h"
24 #include "tldap_gensec_bind.h"
25 #include "tldap_util.h"
26 #include "passdb.h"
27 #include "lib/param/param.h"
28 #include "auth/gensec/gensec.h"
29 #include "librpc/gen_ndr/ndr_netlogon.h"
30 #include "libads/ldap_schema_oids.h"
31 #include "../libds/common/flags.h"
32 #include "libcli/ldap/ldap_ndr.h"
33 #include "libcli/security/dom_sid.h"
34 #include "source3/libads/sitename_cache.h"
35 #include "source3/libads/kerberos_proto.h"
36
37 struct idmap_ad_schema_names;
38
39 struct idmap_ad_context {
40         struct idmap_domain *dom;
41         struct tldap_context *ld;
42         struct idmap_ad_schema_names *schema;
43         const char *default_nc;
44
45         bool unix_primary_group;
46         bool unix_nss_info;
47 };
48
49 static NTSTATUS idmap_ad_get_context(struct idmap_domain *dom,
50                                      struct idmap_ad_context **pctx);
51
52 static char *get_schema_path(TALLOC_CTX *mem_ctx, struct tldap_context *ld)
53 {
54         struct tldap_message *rootdse;
55
56         rootdse = tldap_rootdse(ld);
57         if (rootdse == NULL) {
58                 return NULL;
59         }
60
61         return tldap_talloc_single_attribute(rootdse, "schemaNamingContext",
62                                              mem_ctx);
63 }
64
65 static char *get_default_nc(TALLOC_CTX *mem_ctx, struct tldap_context *ld)
66 {
67         struct tldap_message *rootdse;
68
69         rootdse = tldap_rootdse(ld);
70         if (rootdse == NULL) {
71                 return NULL;
72         }
73
74         return tldap_talloc_single_attribute(rootdse, "defaultNamingContext",
75                                              mem_ctx);
76 }
77
78 struct idmap_ad_schema_names {
79         char *name;
80         char *uid;
81         char *gid;
82         char *gecos;
83         char *dir;
84         char *shell;
85 };
86
87 static TLDAPRC get_attrnames_by_oids(struct tldap_context *ld,
88                                      TALLOC_CTX *mem_ctx,
89                                      const char *schema_path,
90                                      size_t num_oids,
91                                      const char **oids,
92                                      char **names)
93 {
94         char *filter;
95         const char *attrs[] = { "lDAPDisplayName", "attributeId" };
96         size_t i;
97         TLDAPRC rc;
98         struct tldap_message **msgs;
99         size_t num_msgs;
100
101         filter = talloc_strdup(mem_ctx, "(|");
102
103         for (i=0; i<num_oids; i++) {
104                 talloc_asprintf_addbuf(&filter, "(attributeId=%s)", oids[i]);
105         }
106         talloc_asprintf_addbuf(&filter, ")");
107
108         if (filter == NULL) {
109                 return TLDAP_NO_MEMORY;
110         }
111
112         rc = tldap_search(ld, schema_path, TLDAP_SCOPE_SUB, filter,
113                           attrs, ARRAY_SIZE(attrs), 0, NULL, 0, NULL, 0,
114                           0, 0, 0, mem_ctx, &msgs);;
115         TALLOC_FREE(filter);
116         if (!TLDAP_RC_IS_SUCCESS(rc)) {
117                 return rc;
118         }
119
120         for (i=0; i<num_oids; i++) {
121                 names[i] = NULL;
122         }
123
124         num_msgs = talloc_array_length(msgs);
125
126         for (i=0; i<num_msgs; i++) {
127                 struct tldap_message *msg = msgs[i];
128                 char *oid;
129                 size_t j;
130
131                 if (tldap_msg_type(msg) != TLDAP_RES_SEARCH_ENTRY) {
132                         /* Could be a TLDAP_RES_SEARCH_REFERENCE */
133                         continue;
134                 }
135
136                 oid = tldap_talloc_single_attribute(
137                         msg, "attributeId", msg);
138                 if (oid == NULL) {
139                         continue;
140                 }
141
142                 for (j=0; j<num_oids; j++) {
143                         if (strequal(oid, oids[j])) {
144                                 break;
145                         }
146                 }
147                 TALLOC_FREE(oid);
148
149                 if (j == num_oids) {
150                         /* not found */
151                         continue;
152                 }
153
154                 names[j] = tldap_talloc_single_attribute(
155                         msg, "lDAPDisplayName", mem_ctx);
156         }
157
158         TALLOC_FREE(msgs);
159         for (i=0; i<num_oids; i++) {
160                 if (names[i] == NULL) {
161                         DBG_ERR("Failed to retrieve schema name for "
162                                 "oid [%s]. Schema mode is incorrect "
163                                 "for this domain.\n", oids[i]);
164                         return TLDAP_FILTER_ERROR;
165                 }
166         }
167
168         return TLDAP_SUCCESS;
169 }
170
171 static TLDAPRC get_posix_schema_names(struct tldap_context *ld,
172                                       const char *schema_mode,
173                                       TALLOC_CTX *mem_ctx,
174                                       struct idmap_ad_schema_names **pschema)
175 {
176         char *schema_path;
177         struct idmap_ad_schema_names *schema;
178         char *names[6];
179         const char *oids_sfu[] = {
180                 ADS_ATTR_SFU_UIDNUMBER_OID,
181                 ADS_ATTR_SFU_GIDNUMBER_OID,
182                 ADS_ATTR_SFU_HOMEDIR_OID,
183                 ADS_ATTR_SFU_SHELL_OID,
184                 ADS_ATTR_SFU_GECOS_OID,
185                 ADS_ATTR_SFU_UID_OID
186         };
187         const char *oids_sfu20[] = {
188                 ADS_ATTR_SFU20_UIDNUMBER_OID,
189                 ADS_ATTR_SFU20_GIDNUMBER_OID,
190                 ADS_ATTR_SFU20_HOMEDIR_OID,
191                 ADS_ATTR_SFU20_SHELL_OID,
192                 ADS_ATTR_SFU20_GECOS_OID,
193                 ADS_ATTR_SFU20_UID_OID
194         };
195         const char *oids_rfc2307[] = {
196                 ADS_ATTR_RFC2307_UIDNUMBER_OID,
197                 ADS_ATTR_RFC2307_GIDNUMBER_OID,
198                 ADS_ATTR_RFC2307_HOMEDIR_OID,
199                 ADS_ATTR_RFC2307_SHELL_OID,
200                 ADS_ATTR_RFC2307_GECOS_OID,
201                 ADS_ATTR_RFC2307_UID_OID
202         };
203         const char **oids;
204
205         TLDAPRC rc;
206
207         schema = talloc(mem_ctx, struct idmap_ad_schema_names);
208         if (schema == NULL) {
209                 return TLDAP_NO_MEMORY;
210         }
211
212         schema_path = get_schema_path(schema, ld);
213         if (schema_path == NULL) {
214                 TALLOC_FREE(schema);
215                 return TLDAP_NO_MEMORY;
216         }
217
218         oids = oids_rfc2307;
219
220         if ((schema_mode != NULL) && (schema_mode[0] != '\0')) {
221                 if (strequal(schema_mode, "sfu")) {
222                         oids = oids_sfu;
223                 } else if (strequal(schema_mode, "sfu20")) {
224                         oids = oids_sfu20;
225                 } else if (strequal(schema_mode, "rfc2307" )) {
226                         oids = oids_rfc2307;
227                 } else {
228                         DBG_WARNING("Unknown schema mode %s\n", schema_mode);
229                 }
230         }
231
232         rc = get_attrnames_by_oids(ld, schema, schema_path, 6, oids, names);
233         TALLOC_FREE(schema_path);
234         if (!TLDAP_RC_IS_SUCCESS(rc)) {
235                 TALLOC_FREE(schema);
236                 return rc;
237         }
238
239         schema->uid = names[0];
240         schema->gid = names[1];
241         schema->dir = names[2];
242         schema->shell = names[3];
243         schema->gecos = names[4];
244         schema->name = names[5];
245
246         *pschema = schema;
247
248         return TLDAP_SUCCESS;
249 }
250
251 static void PRINTF_ATTRIBUTE(3, 0) idmap_ad_tldap_debug(
252         void *log_private,
253         enum tldap_debug_level level,
254         const char *fmt,
255         va_list ap)
256 {
257        int samba_level = -1;
258
259        switch (level) {
260        case TLDAP_DEBUG_FATAL:
261                samba_level = DBGLVL_ERR;
262                break;
263        case TLDAP_DEBUG_ERROR:
264                samba_level = DBGLVL_ERR;
265                break;
266        case TLDAP_DEBUG_WARNING:
267                samba_level = DBGLVL_WARNING;
268                break;
269        case TLDAP_DEBUG_TRACE:
270                samba_level = DBGLVL_DEBUG;
271                break;
272        }
273
274        if (CHECK_DEBUGLVL(samba_level)) {
275                char *s = NULL;
276                int ret;
277
278                ret = vasprintf(&s, fmt, ap);
279                if (ret == -1) {
280                        return;
281                }
282                DEBUG(samba_level, ("idmap_ad_tldap: %s", s));
283                free(s);
284        }
285 }
286
287 static uint32_t gensec_features_from_ldap_sasl_wrapping(void)
288 {
289         int wrap_flags;
290         uint32_t gensec_features = 0;
291
292         wrap_flags = lp_client_ldap_sasl_wrapping();
293         if (wrap_flags == -1) {
294                 wrap_flags = 0;
295         }
296
297         if (wrap_flags & ADS_AUTH_SASL_SEAL) {
298                 gensec_features |= GENSEC_FEATURE_SEAL;
299         }
300         if (wrap_flags & ADS_AUTH_SASL_SIGN) {
301                 gensec_features |= GENSEC_FEATURE_SIGN;
302         }
303
304         if (gensec_features != 0) {
305                 gensec_features |= GENSEC_FEATURE_LDAP_STYLE;
306         }
307
308         return gensec_features;
309 }
310
311 static NTSTATUS idmap_ad_get_tldap_ctx(TALLOC_CTX *mem_ctx,
312                                        const char *domname,
313                                        struct tldap_context **pld)
314 {
315         struct netr_DsRGetDCNameInfo *dcinfo;
316         struct sockaddr_storage dcaddr;
317         struct cli_credentials *creds;
318         struct loadparm_context *lp_ctx;
319         struct tldap_context *ld;
320         uint32_t gensec_features = gensec_features_from_ldap_sasl_wrapping();
321         char *sitename = NULL;
322         int fd;
323         NTSTATUS status;
324         bool ok;
325         TLDAPRC rc;
326
327         status = wb_dsgetdcname_gencache_get(mem_ctx, domname, &dcinfo);
328         if (!NT_STATUS_IS_OK(status)) {
329                 DBG_DEBUG("Could not get dcinfo for %s: %s\n", domname,
330                           nt_errstr(status));
331                 return status;
332         }
333
334         if (dcinfo->dc_unc == NULL) {
335                 TALLOC_FREE(dcinfo);
336                 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
337         }
338         if (dcinfo->dc_unc[0] == '\\') {
339                 dcinfo->dc_unc += 1;
340         }
341         if (dcinfo->dc_unc[0] == '\\') {
342                 dcinfo->dc_unc += 1;
343         }
344
345         ok = resolve_name(dcinfo->dc_unc, &dcaddr, 0x20, true);
346         if (!ok) {
347                 DBG_DEBUG("Could not resolve name %s\n", dcinfo->dc_unc);
348                 TALLOC_FREE(dcinfo);
349                 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
350         }
351
352         sitename = sitename_fetch(talloc_tos(), lp_realm());
353
354         /*
355          * create_local_private_krb5_conf_for_domain() can deal with
356          * sitename==NULL
357          */
358
359         ok = create_local_private_krb5_conf_for_domain(
360                 lp_realm(), lp_workgroup(), sitename, &dcaddr);
361         TALLOC_FREE(sitename);
362         if (!ok) {
363                 DBG_DEBUG("Could not create private krb5.conf\n");
364                 TALLOC_FREE(dcinfo);
365                 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
366         }
367
368         status = open_socket_out(&dcaddr, 389, 10000, &fd);
369         if (!NT_STATUS_IS_OK(status)) {
370                 DBG_DEBUG("open_socket_out failed: %s\n", nt_errstr(status));
371                 TALLOC_FREE(dcinfo);
372                 return status;
373         }
374
375         ld = tldap_context_create(dcinfo, fd);
376         if (ld == NULL) {
377                 DBG_DEBUG("tldap_context_create failed\n");
378                 close(fd);
379                 TALLOC_FREE(dcinfo);
380                 return NT_STATUS_NO_MEMORY;
381         }
382         tldap_set_debug(ld, idmap_ad_tldap_debug, NULL);
383
384         /*
385          * Here we use or own machine account as
386          * we run as domain member.
387          */
388         status = pdb_get_trust_credentials(lp_workgroup(),
389                                            lp_realm(),
390                                            dcinfo,
391                                            &creds);
392         if (!NT_STATUS_IS_OK(status)) {
393                 DBG_DEBUG("pdb_get_trust_credentials() failed - %s\n",
394                           nt_errstr(status));
395                 TALLOC_FREE(dcinfo);
396                 return status;
397         }
398
399         lp_ctx = loadparm_init_s3(dcinfo, loadparm_s3_helpers());
400         if (lp_ctx == NULL) {
401                 DBG_DEBUG("loadparm_init_s3 failed\n");
402                 TALLOC_FREE(dcinfo);
403                 return NT_STATUS_NO_MEMORY;
404         }
405
406         rc = tldap_gensec_bind(ld, creds, "ldap", dcinfo->dc_unc, NULL, lp_ctx,
407                                gensec_features);
408         if (!TLDAP_RC_IS_SUCCESS(rc)) {
409                 DBG_DEBUG("tldap_gensec_bind failed: %s\n",
410                           tldap_errstr(dcinfo, ld, rc));
411                 TALLOC_FREE(dcinfo);
412                 return NT_STATUS_LDAP(TLDAP_RC_V(rc));
413         }
414
415         rc = tldap_fetch_rootdse(ld);
416         if (!TLDAP_RC_IS_SUCCESS(rc)) {
417                 DBG_DEBUG("tldap_fetch_rootdse failed: %s\n",
418                           tldap_errstr(dcinfo, ld, rc));
419                 TALLOC_FREE(dcinfo);
420                 return NT_STATUS_LDAP(TLDAP_RC_V(rc));
421         }
422
423         *pld = talloc_move(mem_ctx, &ld);
424         TALLOC_FREE(dcinfo);
425         return NT_STATUS_OK;
426 }
427
428 static int idmap_ad_context_destructor(struct idmap_ad_context *ctx)
429 {
430         if ((ctx->dom != NULL) && (ctx->dom->private_data == ctx)) {
431                 ctx->dom->private_data = NULL;
432         }
433         return 0;
434 }
435
436 static NTSTATUS idmap_ad_context_create(TALLOC_CTX *mem_ctx,
437                                         struct idmap_domain *dom,
438                                         const char *domname,
439                                         struct idmap_ad_context **pctx)
440 {
441         struct idmap_ad_context *ctx;
442         const char *schema_mode;
443         NTSTATUS status;
444         TLDAPRC rc;
445
446         ctx = talloc(mem_ctx, struct idmap_ad_context);
447         if (ctx == NULL) {
448                 return NT_STATUS_NO_MEMORY;
449         }
450         ctx->dom = dom;
451
452         talloc_set_destructor(ctx, idmap_ad_context_destructor);
453
454         status = idmap_ad_get_tldap_ctx(ctx, domname, &ctx->ld);
455         if (!NT_STATUS_IS_OK(status)) {
456                 DBG_DEBUG("idmap_ad_get_tldap_ctx failed: %s\n",
457                           nt_errstr(status));
458                 TALLOC_FREE(ctx);
459                 return status;
460         }
461
462         ctx->default_nc = get_default_nc(ctx, ctx->ld);
463         if (ctx->default_nc == NULL) {
464                 DBG_DEBUG("No default nc\n");
465                 TALLOC_FREE(ctx);
466                 return status;
467         }
468
469         ctx->unix_primary_group = idmap_config_bool(
470                 domname, "unix_primary_group", false);
471         ctx->unix_nss_info = idmap_config_bool(
472                 domname, "unix_nss_info", false);
473
474         schema_mode = idmap_config_const_string(
475                 domname, "schema_mode", "rfc2307");
476
477         rc = get_posix_schema_names(ctx->ld, schema_mode, ctx, &ctx->schema);
478         if (!TLDAP_RC_IS_SUCCESS(rc)) {
479                 DBG_DEBUG("get_posix_schema_names failed: %s\n",
480                           tldap_errstr(ctx, ctx->ld, rc));
481                 TALLOC_FREE(ctx);
482                 return NT_STATUS_LDAP(TLDAP_RC_V(rc));
483         }
484
485         *pctx = ctx;
486         return NT_STATUS_OK;
487 }
488
489 static NTSTATUS idmap_ad_query_user(struct idmap_domain *domain,
490                                     struct wbint_userinfo *info)
491 {
492         struct idmap_ad_context *ctx;
493         TLDAPRC rc;
494         NTSTATUS status;
495         char *sidstr, *filter;
496         const char *attrs[4];
497         size_t i, num_msgs;
498         struct tldap_message **msgs;
499
500         status = idmap_ad_get_context(domain, &ctx);
501         if (!NT_STATUS_IS_OK(status)) {
502                 return status;
503         }
504
505         if (!(ctx->unix_primary_group || ctx->unix_nss_info)) {
506                 return NT_STATUS_OK;
507         }
508
509         attrs[0] = ctx->schema->gid;
510         attrs[1] = ctx->schema->gecos;
511         attrs[2] = ctx->schema->dir;
512         attrs[3] = ctx->schema->shell;
513
514         sidstr = ldap_encode_ndr_dom_sid(talloc_tos(), &info->user_sid);
515         if (sidstr == NULL) {
516                 return NT_STATUS_NO_MEMORY;
517         }
518
519         filter = talloc_asprintf(talloc_tos(), "(objectsid=%s)", sidstr);
520         TALLOC_FREE(sidstr);
521         if (filter == NULL) {
522                 return NT_STATUS_NO_MEMORY;
523         }
524
525         DBG_DEBUG("Filter: [%s]\n", filter);
526
527         rc = tldap_search(ctx->ld, ctx->default_nc, TLDAP_SCOPE_SUB, filter,
528                           attrs, ARRAY_SIZE(attrs), 0, NULL, 0, NULL, 0,
529                           0, 0, 0, talloc_tos(), &msgs);
530         if (!TLDAP_RC_IS_SUCCESS(rc)) {
531                 return NT_STATUS_LDAP(TLDAP_RC_V(rc));
532         }
533
534         TALLOC_FREE(filter);
535
536         num_msgs = talloc_array_length(msgs);
537
538         for (i=0; i<num_msgs; i++) {
539                 struct tldap_message *msg = msgs[i];
540
541                 if (tldap_msg_type(msg) != TLDAP_RES_SEARCH_ENTRY) {
542                         continue;
543                 }
544
545                 if (ctx->unix_primary_group) {
546                         bool ok;
547                         uint32_t gid;
548
549                         ok = tldap_pull_uint32(msg, ctx->schema->gid, &gid);
550                         if (ok) {
551                                 DBG_DEBUG("Setting primary group "
552                                           "to %"PRIu32" from attr %s\n",
553                                           gid, ctx->schema->gid);
554                                 info->primary_gid = gid;
555                         }
556                 }
557
558                 if (ctx->unix_nss_info) {
559                         char *attr;
560
561                         attr = tldap_talloc_single_attribute(
562                                 msg, ctx->schema->dir, talloc_tos());
563                         if (attr != NULL) {
564                                 info->homedir = talloc_move(info, &attr);
565                         }
566                         TALLOC_FREE(attr);
567
568                         attr = tldap_talloc_single_attribute(
569                                 msg, ctx->schema->shell, talloc_tos());
570                         if (attr != NULL) {
571                                 info->shell = talloc_move(info, &attr);
572                         }
573                         TALLOC_FREE(attr);
574
575                         attr = tldap_talloc_single_attribute(
576                                 msg, ctx->schema->gecos, talloc_tos());
577                         if (attr != NULL) {
578                                 info->full_name = talloc_move(info, &attr);
579                         }
580                         TALLOC_FREE(attr);
581                 }
582         }
583
584         return NT_STATUS_OK;
585 }
586
587 static NTSTATUS idmap_ad_query_user_retry(struct idmap_domain *domain,
588                                           struct wbint_userinfo *info)
589 {
590         const NTSTATUS status_server_down =
591                 NT_STATUS_LDAP(TLDAP_RC_V(TLDAP_SERVER_DOWN));
592         NTSTATUS status;
593
594         status = idmap_ad_query_user(domain, info);
595
596         if (NT_STATUS_EQUAL(status, status_server_down)) {
597                 TALLOC_FREE(domain->private_data);
598                 status = idmap_ad_query_user(domain, info);
599         }
600
601         return status;
602 }
603
604 static NTSTATUS idmap_ad_initialize(struct idmap_domain *dom)
605 {
606         dom->query_user = idmap_ad_query_user_retry;
607         dom->private_data = NULL;
608         return NT_STATUS_OK;
609 }
610
611 static NTSTATUS idmap_ad_get_context(struct idmap_domain *dom,
612                                      struct idmap_ad_context **pctx)
613 {
614         struct idmap_ad_context *ctx = NULL;
615         NTSTATUS status;
616
617         if (IS_AD_DC) {
618                 /*
619                  * Make sure we never try to use LDAP against
620                  * a trusted domain as AD_DC.
621                  *
622                  * This shouldn't be called currently,
623                  * but you never know what happens in future.
624                  */
625                 return NT_STATUS_REQUEST_NOT_ACCEPTED;
626         }
627
628         if (dom->private_data != NULL) {
629                 *pctx = talloc_get_type_abort(dom->private_data,
630                                               struct idmap_ad_context);
631                 return NT_STATUS_OK;
632         }
633
634         status = idmap_ad_context_create(dom, dom, dom->name, &ctx);
635         if (!NT_STATUS_IS_OK(status)) {
636                 DBG_DEBUG("idmap_ad_context_create failed: %s\n",
637                           nt_errstr(status));
638                 return status;
639         }
640
641         dom->private_data = ctx;
642         *pctx = ctx;
643         return NT_STATUS_OK;
644 }
645
646 static NTSTATUS idmap_ad_unixids_to_sids(struct idmap_domain *dom,
647                                          struct id_map **ids)
648 {
649         struct idmap_ad_context *ctx;
650         TLDAPRC rc;
651         NTSTATUS status;
652         struct tldap_message **msgs;
653
654         size_t i, num_msgs;
655         char *u_filter, *g_filter, *filter;
656
657         const char *attrs[] = {
658                 "sAMAccountType",
659                 "objectSid",
660                 NULL, /* attr_uidnumber */
661                 NULL, /* attr_gidnumber */
662         };
663
664         status = idmap_ad_get_context(dom, &ctx);
665         if (!NT_STATUS_IS_OK(status)) {
666                 return status;
667         }
668
669         attrs[2] = ctx->schema->uid;
670         attrs[3] = ctx->schema->gid;
671
672         u_filter = talloc_strdup(talloc_tos(), "");
673         if (u_filter == NULL) {
674                 return NT_STATUS_NO_MEMORY;
675         }
676
677         g_filter = talloc_strdup(talloc_tos(), "");
678         if (g_filter == NULL) {
679                 return NT_STATUS_NO_MEMORY;
680         }
681
682         for (i=0; ids[i] != NULL; i++) {
683                 struct id_map *id = ids[i];
684
685                 id->status = ID_UNKNOWN;
686
687                 switch (id->xid.type) {
688                     case ID_TYPE_UID: {
689                             u_filter = talloc_asprintf_append_buffer(
690                                     u_filter, "(%s=%ju)", ctx->schema->uid,
691                                     (uintmax_t)id->xid.id);
692                             if (u_filter == NULL) {
693                                     return NT_STATUS_NO_MEMORY;
694                             }
695                             break;
696                     }
697
698                     case ID_TYPE_GID: {
699                             g_filter = talloc_asprintf_append_buffer(
700                                     g_filter, "(%s=%ju)", ctx->schema->gid,
701                                     (uintmax_t)id->xid.id);
702                             if (g_filter == NULL) {
703                                     return NT_STATUS_NO_MEMORY;
704                             }
705                             break;
706                     }
707
708                     default:
709                             DBG_WARNING("Unknown id type: %u\n",
710                                         (unsigned)id->xid.type);
711                             break;
712                 }
713         }
714
715         filter = talloc_strdup(talloc_tos(), "(|");
716         if (filter == NULL) {
717                 return NT_STATUS_NO_MEMORY;
718         }
719
720         if (*u_filter != '\0') {
721                 filter = talloc_asprintf_append_buffer(
722                         filter,
723                         "(&(|(sAMAccountType=%d)(sAMAccountType=%d)"
724                         "(sAMAccountType=%d))(|%s))",
725                         ATYPE_NORMAL_ACCOUNT, ATYPE_WORKSTATION_TRUST,
726                         ATYPE_INTERDOMAIN_TRUST, u_filter);
727                 if (filter == NULL) {
728                         return NT_STATUS_NO_MEMORY;
729                 }
730         }
731         TALLOC_FREE(u_filter);
732
733         if (*g_filter != '\0') {
734                 filter = talloc_asprintf_append_buffer(
735                         filter,
736                         "(&(|(sAMAccountType=%d)(sAMAccountType=%d))(|%s))",
737                         ATYPE_SECURITY_GLOBAL_GROUP,
738                         ATYPE_SECURITY_LOCAL_GROUP,
739                         g_filter);
740                 if (filter == NULL) {
741                         return NT_STATUS_NO_MEMORY;
742                 }
743         }
744         TALLOC_FREE(g_filter);
745
746         filter = talloc_asprintf_append_buffer(filter, ")");
747         if (filter == NULL) {
748                 return NT_STATUS_NO_MEMORY;
749         }
750
751         DBG_DEBUG("Filter: [%s]\n", filter);
752
753         rc = tldap_search(ctx->ld, ctx->default_nc, TLDAP_SCOPE_SUB, filter,
754                           attrs, ARRAY_SIZE(attrs), 0, NULL, 0, NULL, 0,
755                           0, 0, 0, talloc_tos(), &msgs);
756         if (!TLDAP_RC_IS_SUCCESS(rc)) {
757                 return NT_STATUS_LDAP(TLDAP_RC_V(rc));
758         }
759
760         TALLOC_FREE(filter);
761
762         num_msgs = talloc_array_length(msgs);
763
764         for (i=0; i<num_msgs; i++) {
765                 struct tldap_message *msg = msgs[i];
766                 char *dn;
767                 struct id_map *map;
768                 struct dom_sid sid;
769                 size_t j;
770                 bool ok;
771                 uint32_t atype, xid;
772                 enum id_type type;
773                 struct dom_sid_buf sidbuf;
774
775                 if (tldap_msg_type(msg) != TLDAP_RES_SEARCH_ENTRY) {
776                         continue;
777                 }
778
779                 ok = tldap_entry_dn(msg, &dn);
780                 if (!ok) {
781                         DBG_DEBUG("No dn found in msg %zu\n", i);
782                         continue;
783                 }
784
785                 ok = tldap_pull_uint32(msg, "sAMAccountType", &atype);
786                 if (!ok) {
787                         DBG_DEBUG("No atype in object %s\n", dn);
788                         continue;
789                 }
790
791                 switch (atype & 0xF0000000) {
792                     case ATYPE_SECURITY_GLOBAL_GROUP:
793                     case ATYPE_SECURITY_LOCAL_GROUP:
794                             type = ID_TYPE_GID;
795                             break;
796                     case ATYPE_NORMAL_ACCOUNT:
797                     case ATYPE_WORKSTATION_TRUST:
798                     case ATYPE_INTERDOMAIN_TRUST:
799                             type = ID_TYPE_UID;
800                             break;
801                     default:
802                             DBG_WARNING("unrecognized SAM account type %08x\n",
803                                         atype);
804                         continue;
805                 }
806
807                 ok = tldap_pull_uint32(msg, (type == ID_TYPE_UID) ?
808                                        ctx->schema->uid : ctx->schema->gid,
809                                        &xid);
810                 if (!ok) {
811                         DBG_WARNING("No unix id in object %s\n", dn);
812                         continue;
813                 }
814
815                 ok = tldap_pull_binsid(msg, "objectSid", &sid);
816                 if (!ok) {
817                         DBG_DEBUG("No objectSid in object %s\n", dn);
818                         continue;
819                 }
820
821                 map = NULL;
822                 for (j=0; ids[j]; j++) {
823                         if ((type == ids[j]->xid.type) &&
824                             (xid == ids[j]->xid.id)) {
825                                 map = ids[j];
826                                 break;
827                         }
828                 }
829                 if (map == NULL) {
830                         DBG_DEBUG("Got unexpected sid %s from object %s\n",
831                                   dom_sid_str_buf(&sid, &sidbuf),
832                                   dn);
833                         continue;
834                 }
835
836                 sid_copy(map->sid, &sid);
837                 map->status = ID_MAPPED;
838
839                 DBG_DEBUG("Mapped %s -> %ju (%d)\n",
840                           dom_sid_str_buf(map->sid, &sidbuf),
841                           (uintmax_t)map->xid.id, map->xid.type);
842         }
843
844         TALLOC_FREE(msgs);
845
846         return NT_STATUS_OK;
847 }
848
849 static NTSTATUS idmap_ad_sids_to_unixids(struct idmap_domain *dom,
850                                          struct id_map **ids)
851 {
852         struct idmap_ad_context *ctx;
853         TLDAPRC rc;
854         NTSTATUS status;
855         struct tldap_message **msgs;
856
857         char *filter;
858         size_t i, num_msgs;
859
860         const char *attrs[] = {
861                 "sAMAccountType",
862                 "objectSid",
863                 NULL, /* attr_uidnumber */
864                 NULL, /* attr_gidnumber */
865         };
866
867         status = idmap_ad_get_context(dom, &ctx);
868         if (!NT_STATUS_IS_OK(status)) {
869                 return status;
870         }
871
872         attrs[2] = ctx->schema->uid;
873         attrs[3] = ctx->schema->gid;
874
875         filter = talloc_asprintf(
876                 talloc_tos(),
877                 "(&(|(sAMAccountType=%d)(sAMAccountType=%d)(sAMAccountType=%d)"
878                 "(sAMAccountType=%d)(sAMAccountType=%d))(|",
879                 ATYPE_NORMAL_ACCOUNT, ATYPE_WORKSTATION_TRUST,
880                 ATYPE_INTERDOMAIN_TRUST, ATYPE_SECURITY_GLOBAL_GROUP,
881                 ATYPE_SECURITY_LOCAL_GROUP);
882         if (filter == NULL) {
883                 return NT_STATUS_NO_MEMORY;
884         }
885
886         for (i=0; ids[i]; i++) {
887                 char *sidstr;
888
889                 ids[i]->status = ID_UNKNOWN;
890
891                 sidstr = ldap_encode_ndr_dom_sid(talloc_tos(), ids[i]->sid);
892                 if (sidstr == NULL) {
893                         return NT_STATUS_NO_MEMORY;
894                 }
895
896                 filter = talloc_asprintf_append_buffer(
897                         filter, "(objectSid=%s)", sidstr);
898                 TALLOC_FREE(sidstr);
899                 if (filter == NULL) {
900                         return NT_STATUS_NO_MEMORY;
901                 }
902         }
903
904         filter = talloc_asprintf_append_buffer(filter, "))");
905         if (filter == NULL) {
906                 return NT_STATUS_NO_MEMORY;
907         }
908
909         DBG_DEBUG("Filter: [%s]\n", filter);
910
911         rc = tldap_search(ctx->ld, ctx->default_nc, TLDAP_SCOPE_SUB, filter,
912                           attrs, ARRAY_SIZE(attrs), 0, NULL, 0, NULL, 0,
913                           0, 0, 0, talloc_tos(), &msgs);
914         if (!TLDAP_RC_IS_SUCCESS(rc)) {
915                 return NT_STATUS_LDAP(TLDAP_RC_V(rc));
916         }
917
918         TALLOC_FREE(filter);
919
920         num_msgs = talloc_array_length(msgs);
921
922         for (i=0; i<num_msgs; i++) {
923                 struct tldap_message *msg = msgs[i];
924                 char *dn;
925                 struct id_map *map;
926                 struct dom_sid sid;
927                 size_t j;
928                 bool ok;
929                 uint64_t account_type, xid;
930                 enum id_type type;
931                 struct dom_sid_buf buf;
932
933                 if (tldap_msg_type(msg) != TLDAP_RES_SEARCH_ENTRY) {
934                         continue;
935                 }
936
937                 ok = tldap_entry_dn(msg, &dn);
938                 if (!ok) {
939                         DBG_DEBUG("No dn found in msg %zu\n", i);
940                         continue;
941                 }
942
943                 ok = tldap_pull_binsid(msg, "objectSid", &sid);
944                 if (!ok) {
945                         DBG_DEBUG("No objectSid in object %s\n", dn);
946                         continue;
947                 }
948
949                 map = NULL;
950                 for (j=0; ids[j]; j++) {
951                         if (dom_sid_equal(&sid, ids[j]->sid)) {
952                                 map = ids[j];
953                                 break;
954                         }
955                 }
956                 if (map == NULL) {
957                         DBG_DEBUG("Got unexpected sid %s from object %s\n",
958                                   dom_sid_str_buf(&sid, &buf),
959                                   dn);
960                         continue;
961                 }
962
963                 ok = tldap_pull_uint64(msg, "sAMAccountType", &account_type);
964                 if (!ok) {
965                         DBG_DEBUG("No sAMAccountType in %s\n", dn);
966                         continue;
967                 }
968
969                 switch (account_type & 0xF0000000) {
970                 case ATYPE_SECURITY_GLOBAL_GROUP:
971                 case ATYPE_SECURITY_LOCAL_GROUP:
972                         type = ID_TYPE_GID;
973                         break;
974                 case ATYPE_NORMAL_ACCOUNT:
975                 case ATYPE_WORKSTATION_TRUST:
976                 case ATYPE_INTERDOMAIN_TRUST:
977                         type = ID_TYPE_UID;
978                         break;
979                 default:
980                         DBG_WARNING("unrecognized SAM account type %"PRIu64"\n",
981                                     account_type);
982                         continue;
983                 }
984
985                 ok = tldap_pull_uint64(msg,
986                                        type == ID_TYPE_UID ?
987                                        ctx->schema->uid : ctx->schema->gid,
988                                        &xid);
989                 if (!ok) {
990                         DBG_DEBUG("No xid in %s\n", dn);
991                         continue;
992                 }
993
994                 /* mapped */
995                 map->xid.type = type;
996                 map->xid.id = xid;
997                 map->status = ID_MAPPED;
998
999                 DEBUG(10, ("Mapped %s -> %lu (%d)\n",
1000                            dom_sid_str_buf(map->sid, &buf),
1001                            (unsigned long)map->xid.id, map->xid.type));
1002         }
1003
1004         TALLOC_FREE(msgs);
1005
1006         return NT_STATUS_OK;
1007 }
1008
1009 static NTSTATUS idmap_ad_unixids_to_sids_retry(struct idmap_domain *dom,
1010                                                struct id_map **ids)
1011 {
1012         const NTSTATUS status_server_down =
1013                 NT_STATUS_LDAP(TLDAP_RC_V(TLDAP_SERVER_DOWN));
1014         NTSTATUS status;
1015
1016         status = idmap_ad_unixids_to_sids(dom, ids);
1017
1018         if (NT_STATUS_EQUAL(status, status_server_down)) {
1019                 TALLOC_FREE(dom->private_data);
1020                 status = idmap_ad_unixids_to_sids(dom, ids);
1021         }
1022
1023         return status;
1024 }
1025
1026 static NTSTATUS idmap_ad_sids_to_unixids_retry(struct idmap_domain *dom,
1027                                                struct id_map **ids)
1028 {
1029         const NTSTATUS status_server_down =
1030                 NT_STATUS_LDAP(TLDAP_RC_V(TLDAP_SERVER_DOWN));
1031         NTSTATUS status;
1032
1033         status = idmap_ad_sids_to_unixids(dom, ids);
1034
1035         if (NT_STATUS_EQUAL(status, status_server_down)) {
1036                 TALLOC_FREE(dom->private_data);
1037                 status = idmap_ad_sids_to_unixids(dom, ids);
1038         }
1039
1040         return status;
1041 }
1042
1043 static const struct idmap_methods ad_methods = {
1044         .init            = idmap_ad_initialize,
1045         .unixids_to_sids = idmap_ad_unixids_to_sids_retry,
1046         .sids_to_unixids = idmap_ad_sids_to_unixids_retry,
1047 };
1048
1049 static_decl_idmap;
1050 NTSTATUS idmap_ad_init(TALLOC_CTX *ctx)
1051 {
1052         NTSTATUS status;
1053
1054         status = smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION,
1055                                     "ad", &ad_methods);
1056         if (!NT_STATUS_IS_OK(status)) {
1057                 return status;
1058         }
1059
1060         status = idmap_ad_nss_init(ctx);
1061         if (!NT_STATUS_IS_OK(status)) {
1062                 return status;
1063         }
1064
1065         return NT_STATUS_OK;
1066 }