dsdb-cracknames: Always use talloc_zero()
[metze/samba/wip.git] / source4 / dsdb / samdb / cracknames.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    crachnames implementation for the drsuapi pipe
5    DsCrackNames()
6
7    Copyright (C) Stefan Metzmacher 2004
8    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005
9    Copyright (C) Matthieu Patou <mat@matws.net> 2012
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "librpc/gen_ndr/drsuapi.h"
27 #include "lib/events/events.h"
28 #include <ldb.h>
29 #include <ldb_errors.h>
30 #include "auth/kerberos/kerberos.h"
31 #include "libcli/ldap/ldap_ndr.h"
32 #include "libcli/security/security.h"
33 #include "auth/auth.h"
34 #include "../lib/util/util_ldb.h"
35 #include "dsdb/samdb/samdb.h"
36 #include "dsdb/common/util.h"
37 #include "param/param.h"
38
39 static WERROR DsCrackNameOneFilter(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
40                                    struct smb_krb5_context *smb_krb5_context,
41                                    uint32_t format_flags, enum drsuapi_DsNameFormat format_offered,
42                                    enum drsuapi_DsNameFormat format_desired,
43                                    struct ldb_dn *name_dn, const char *name, 
44                                    const char *domain_filter, const char *result_filter, 
45                                    struct drsuapi_DsNameInfo1 *info1, int scope, struct ldb_dn *search_dn);
46 static WERROR DsCrackNameOneSyntactical(TALLOC_CTX *mem_ctx,
47                                         enum drsuapi_DsNameFormat format_offered,
48                                         enum drsuapi_DsNameFormat format_desired,
49                                         struct ldb_dn *name_dn, const char *name, 
50                                         struct drsuapi_DsNameInfo1 *info1);
51
52 static WERROR dns_domain_from_principal(TALLOC_CTX *mem_ctx, struct smb_krb5_context *smb_krb5_context, 
53                                         const char *name, 
54                                         struct drsuapi_DsNameInfo1 *info1) 
55 {
56         krb5_error_code ret;
57         krb5_principal principal;
58         /* perhaps it's a principal with a realm, so return the right 'domain only' response */
59         const char *realm;
60         ret = krb5_parse_name_flags(smb_krb5_context->krb5_context, name, 
61                                     KRB5_PRINCIPAL_PARSE_REQUIRE_REALM, &principal);
62         if (ret) {
63                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
64                 return WERR_OK;
65         }
66
67         /* This isn't an allocation assignemnt, so it is free'ed with the krb5_free_principal */
68         realm = smb_krb5_principal_get_realm(smb_krb5_context->krb5_context, principal);
69
70         info1->dns_domain_name  = talloc_strdup(mem_ctx, realm);
71         krb5_free_principal(smb_krb5_context->krb5_context, principal);
72
73         W_ERROR_HAVE_NO_MEMORY(info1->dns_domain_name);
74
75         info1->status = DRSUAPI_DS_NAME_STATUS_DOMAIN_ONLY;
76         return WERR_OK;
77 }               
78
79 static enum drsuapi_DsNameStatus LDB_lookup_spn_alias(krb5_context context, struct ldb_context *ldb_ctx, 
80                                                       TALLOC_CTX *mem_ctx,
81                                                       const char *alias_from,
82                                                       char **alias_to)
83 {
84         unsigned int i;
85         int ret;
86         struct ldb_result *res;
87         struct ldb_message_element *spnmappings;
88         TALLOC_CTX *tmp_ctx;
89         struct ldb_dn *service_dn;
90         char *service_dn_str;
91
92         const char *directory_attrs[] = {
93                 "sPNMappings", 
94                 NULL
95         };
96
97         tmp_ctx = talloc_new(mem_ctx);
98         if (!tmp_ctx) {
99                 return DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
100         }
101
102         service_dn = ldb_dn_new(tmp_ctx, ldb_ctx, "CN=Directory Service,CN=Windows NT,CN=Services");
103         if ( ! ldb_dn_add_base(service_dn, ldb_get_config_basedn(ldb_ctx))) {
104                 return DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
105         }
106         service_dn_str = ldb_dn_alloc_linearized(tmp_ctx, service_dn);
107         if ( ! service_dn_str) {
108                 return DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
109         }
110
111         ret = ldb_search(ldb_ctx, tmp_ctx, &res, service_dn, LDB_SCOPE_BASE,
112                          directory_attrs, "(objectClass=nTDSService)");
113
114         if (ret != LDB_SUCCESS && ret != LDB_ERR_NO_SUCH_OBJECT) {
115                 DEBUG(1, ("ldb_search: dn: %s not found: %s\n", service_dn_str, ldb_errstring(ldb_ctx)));
116                 return DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
117         } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
118                 DEBUG(1, ("ldb_search: dn: %s not found\n", service_dn_str));
119                 return DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
120         } else if (res->count != 1) {
121                 talloc_free(res);
122                 DEBUG(1, ("ldb_search: dn: %s not found\n", service_dn_str));
123                 return DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
124         }
125
126         spnmappings = ldb_msg_find_element(res->msgs[0], "sPNMappings");
127         if (!spnmappings || spnmappings->num_values == 0) {
128                 DEBUG(1, ("ldb_search: dn: %s no sPNMappings attribute\n", service_dn_str));
129                 talloc_free(tmp_ctx);
130                 return DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
131         }
132
133         for (i = 0; i < spnmappings->num_values; i++) {
134                 char *mapping, *p, *str;
135                 mapping = talloc_strdup(tmp_ctx, 
136                                         (const char *)spnmappings->values[i].data);
137                 if (!mapping) {
138                         DEBUG(1, ("LDB_lookup_spn_alias: ldb_search: dn: %s did not have an sPNMapping\n", service_dn_str));
139                         talloc_free(tmp_ctx);
140                         return DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
141                 }
142
143                 /* C string manipulation sucks */
144
145                 p = strchr(mapping, '=');
146                 if (!p) {
147                         DEBUG(1, ("ldb_search: dn: %s sPNMapping malformed: %s\n", 
148                                   service_dn_str, mapping));
149                         talloc_free(tmp_ctx);
150                         return DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
151                 }
152                 p[0] = '\0';
153                 p++;
154                 do {
155                         str = p;
156                         p = strchr(p, ',');
157                         if (p) {
158                                 p[0] = '\0';
159                                 p++;
160                         }
161                         if (strcasecmp(str, alias_from) == 0) {
162                                 *alias_to = mapping;
163                                 talloc_steal(mem_ctx, mapping);
164                                 talloc_free(tmp_ctx);
165                                 return DRSUAPI_DS_NAME_STATUS_OK;
166                         }
167                 } while (p);
168         }
169         DEBUG(4, ("LDB_lookup_spn_alias: no alias for service %s applicable\n", alias_from));
170         talloc_free(tmp_ctx);
171         return DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
172 }
173
174 /* When cracking a ServicePrincipalName, many services may be served
175  * by the host/ servicePrincipalName.  The incoming query is for cifs/
176  * but we translate it here, and search on host/.  This is done after
177  * the cifs/ entry has been searched for, making this a fallback */
178
179 static WERROR DsCrackNameSPNAlias(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
180                                   struct smb_krb5_context *smb_krb5_context,
181                                   uint32_t format_flags, enum drsuapi_DsNameFormat format_offered,
182                                   enum drsuapi_DsNameFormat format_desired,
183                                   const char *name, struct drsuapi_DsNameInfo1 *info1)
184 {
185         WERROR wret;
186         krb5_error_code ret;
187         krb5_principal principal;
188         const krb5_data *component;
189         const char *service, *dns_name;
190         char *new_service;
191         char *new_princ;
192         enum drsuapi_DsNameStatus namestatus;
193
194         /* parse principal */
195         ret = krb5_parse_name_flags(smb_krb5_context->krb5_context, 
196                                     name, KRB5_PRINCIPAL_PARSE_NO_REALM, &principal);
197         if (ret) {
198                 DEBUG(2, ("Could not parse principal: %s: %s\n",
199                           name, smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
200                                                            ret, mem_ctx)));
201                 return WERR_NOMEM;
202         }
203
204         /* grab cifs/, http/ etc */
205
206         /* This is checked for in callers, but be safe */
207         if (krb5_princ_size(smb_krb5_context->krb5_context, principal) < 2) {
208                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
209                 krb5_free_principal(smb_krb5_context->krb5_context, principal);
210                 return WERR_OK;
211         }
212         component = krb5_princ_component(smb_krb5_context->krb5_context,
213                                          principal, 0);
214         service = (const char *)component->data;
215         component = krb5_princ_component(smb_krb5_context->krb5_context,
216                                          principal, 1);
217         dns_name = (const char *)component->data;
218
219         /* MAP it */
220         namestatus = LDB_lookup_spn_alias(smb_krb5_context->krb5_context, 
221                                           sam_ctx, mem_ctx, 
222                                           service, &new_service);
223
224         if (namestatus == DRSUAPI_DS_NAME_STATUS_NOT_FOUND) {
225                 wret = WERR_OK;
226                 info1->status           = DRSUAPI_DS_NAME_STATUS_DOMAIN_ONLY;
227                 info1->dns_domain_name  = talloc_strdup(mem_ctx, dns_name);
228                 if (!info1->dns_domain_name) {
229                         wret = WERR_NOMEM;
230                 }
231                 krb5_free_principal(smb_krb5_context->krb5_context, principal);
232                 return wret;
233         } else if (namestatus != DRSUAPI_DS_NAME_STATUS_OK) {
234                 info1->status = namestatus;
235                 krb5_free_principal(smb_krb5_context->krb5_context, principal);
236                 return WERR_OK;
237         }
238
239         /* reform principal */
240         new_princ = talloc_asprintf(mem_ctx, "%s/%s", new_service, dns_name);
241         if (!new_princ) {
242                 krb5_free_principal(smb_krb5_context->krb5_context, principal);
243                 return WERR_NOMEM;
244         }
245
246         wret = DsCrackNameOneName(sam_ctx, mem_ctx, format_flags, format_offered, format_desired,
247                                   new_princ, info1);
248         talloc_free(new_princ);
249         if (W_ERROR_IS_OK(wret) && (info1->status == DRSUAPI_DS_NAME_STATUS_NOT_FOUND)) {
250                 info1->status           = DRSUAPI_DS_NAME_STATUS_DOMAIN_ONLY;
251                 info1->dns_domain_name  = talloc_strdup(mem_ctx, dns_name);
252                 if (!info1->dns_domain_name) {
253                         wret = WERR_NOMEM;
254                 }
255         }
256         krb5_free_principal(smb_krb5_context->krb5_context, principal);
257         return wret;
258 }
259
260 /* Subcase of CrackNames, for the userPrincipalName */
261
262 static WERROR DsCrackNameUPN(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
263                              struct smb_krb5_context *smb_krb5_context,
264                              uint32_t format_flags, enum drsuapi_DsNameFormat format_offered,
265                              enum drsuapi_DsNameFormat format_desired,
266                              const char *name, struct drsuapi_DsNameInfo1 *info1)
267 {
268         int ldb_ret;
269         WERROR status;
270         const char *domain_filter = NULL;
271         const char *result_filter = NULL;
272         krb5_error_code ret;
273         krb5_principal principal;
274         const char *realm;
275         char *unparsed_name_short;
276         const char *domain_attrs[] = { NULL };
277         struct ldb_result *domain_res = NULL;
278
279         /* Prevent recursion */
280         if (!name) {
281                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
282                 return WERR_OK;
283         }
284
285         ret = krb5_parse_name_flags(smb_krb5_context->krb5_context, name, 
286                                     KRB5_PRINCIPAL_PARSE_REQUIRE_REALM, &principal);
287         if (ret) {
288                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
289                 return WERR_OK;
290         }
291
292         realm = smb_krb5_principal_get_realm(smb_krb5_context->krb5_context,
293                                              principal);
294
295         ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res,
296                              samdb_partitions_dn(sam_ctx, mem_ctx),
297                              LDB_SCOPE_ONELEVEL,
298                              domain_attrs,
299                              "(&(objectClass=crossRef)(|(dnsRoot=%s)(netbiosName=%s))(systemFlags:%s:=%u))",
300                              ldb_binary_encode_string(mem_ctx, realm),
301                              ldb_binary_encode_string(mem_ctx, realm),
302                              LDB_OID_COMPARATOR_AND,
303                              SYSTEM_FLAG_CR_NTDS_DOMAIN);
304
305         if (ldb_ret != LDB_SUCCESS) {
306                 DEBUG(2, ("DsCrackNameUPN domain ref search failed: %s\n", ldb_errstring(sam_ctx)));
307                 info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
308                 krb5_free_principal(smb_krb5_context->krb5_context, principal);
309                 return WERR_OK;
310         }
311
312         switch (domain_res->count) {
313         case 1:
314                 break;
315         case 0:
316                 krb5_free_principal(smb_krb5_context->krb5_context, principal);
317                 return dns_domain_from_principal(mem_ctx, smb_krb5_context, 
318                                                  name, info1);
319         default:
320                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE;
321                 krb5_free_principal(smb_krb5_context->krb5_context, principal);
322                 return WERR_OK;
323         }
324
325         ret = krb5_unparse_name_flags(smb_krb5_context->krb5_context, principal, 
326                                       KRB5_PRINCIPAL_UNPARSE_NO_REALM, &unparsed_name_short);
327         krb5_free_principal(smb_krb5_context->krb5_context, principal);
328
329         if (ret) {
330                 free(unparsed_name_short);
331                 return WERR_NOMEM;
332         }
333
334         /* This may need to be extended for more userPrincipalName variations */
335         result_filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
336                                         ldb_binary_encode_string(mem_ctx, unparsed_name_short));
337
338         domain_filter = talloc_asprintf(mem_ctx, "(distinguishedName=%s)", ldb_dn_get_linearized(domain_res->msgs[0]->dn));
339
340         if (!result_filter || !domain_filter) {
341                 free(unparsed_name_short);
342                 return WERR_NOMEM;
343         }
344         status = DsCrackNameOneFilter(sam_ctx, mem_ctx, 
345                                       smb_krb5_context, 
346                                       format_flags, format_offered, format_desired, 
347                                       NULL, unparsed_name_short, domain_filter, result_filter, 
348                                       info1, LDB_SCOPE_SUBTREE, NULL);
349         free(unparsed_name_short);
350
351         return status;
352 }
353
354 /*
355  * This function will workout the filtering parameter in order to be able to do
356  * the adapted search when the incomming format is format_functional.
357  * This boils down to defining the search_dn (passed as pointer to ldb_dn *) and the
358  * ldap filter request.
359  * Main input parameters are:
360  * * name, which is the portion of the functional name after the
361  * first '/'.
362  * * domain_filter, which is a ldap search filter used to find the NC DN given the
363  * function name to crack.
364  */
365 static WERROR get_format_functional_filtering_param(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
366                         char *name, struct drsuapi_DsNameInfo1 *info1,
367                         struct ldb_dn **psearch_dn, const char *domain_filter, const char **presult_filter)
368 {
369         struct ldb_result *domain_res = NULL;
370         const char * const domain_attrs[] = {"ncName", NULL};
371         struct ldb_dn *partitions_basedn = samdb_partitions_dn(sam_ctx, mem_ctx);
372         int ldb_ret;
373         char *account,  *s, *result_filter = NULL;
374         struct ldb_dn *search_dn = NULL;
375
376         *psearch_dn = NULL;
377         *presult_filter = NULL;
378
379         ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res,
380                                 partitions_basedn,
381                                 LDB_SCOPE_ONELEVEL,
382                                 domain_attrs,
383                                 "%s", domain_filter);
384
385         if (ldb_ret != LDB_SUCCESS) {
386                 DEBUG(2, ("DsCrackNameOne domain ref search failed: %s\n", ldb_errstring(sam_ctx)));
387                 info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
388                 return WERR_FOOBAR;
389         }
390
391         if (domain_res->count == 1) {
392                 struct ldb_dn *tmp_dn = samdb_result_dn(sam_ctx, mem_ctx, domain_res->msgs[0], "ncName", NULL);
393                 const char * const name_attrs[] = {"name", NULL};
394
395                 account = name;
396                 s = strchr(account, '/');
397                 while(s) {
398                         s[0] = '\0';
399                         s++;
400                         talloc_free(domain_res);
401
402                         ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res,
403                                                 tmp_dn,
404                                                 LDB_SCOPE_ONELEVEL,
405                                                 name_attrs,
406                                                 "name=%s", account);
407
408                         if (ldb_ret != LDB_SUCCESS) {
409                                 DEBUG(2, ("DsCrackNameOne domain ref search failed: %s\n", ldb_errstring(sam_ctx)));
410                                 info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
411                                 return WERR_OK;
412                         }
413                         switch (domain_res->count) {
414                         case 1:
415                                 break;
416                         case 0:
417                                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
418                                 return WERR_OK;
419                         default:
420                                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE;
421                                 return WERR_OK;
422                         }
423
424                         talloc_free(tmp_dn);
425                         tmp_dn = talloc_steal(mem_ctx, domain_res->msgs[0]->dn);
426                         talloc_free(domain_res);
427                         search_dn = tmp_dn;
428                         account = s;
429                         s = strchr(account, '/');
430                 }
431                 account = ldb_binary_encode_string(mem_ctx, account);
432                 W_ERROR_HAVE_NO_MEMORY(account);
433                 result_filter = talloc_asprintf(mem_ctx, "(name=%s)",
434                                                 account);
435                 W_ERROR_HAVE_NO_MEMORY(result_filter);
436         }
437         *psearch_dn = search_dn;
438         *presult_filter = result_filter;
439         return WERR_OK;
440 }
441
442 /* Crack a single 'name', from format_offered into format_desired, returning the result in info1 */
443
444 WERROR DsCrackNameOneName(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
445                           uint32_t format_flags, enum drsuapi_DsNameFormat format_offered,
446                           enum drsuapi_DsNameFormat format_desired,
447                           const char *name, struct drsuapi_DsNameInfo1 *info1)
448 {
449         krb5_error_code ret;
450         const char *domain_filter = NULL;
451         const char *result_filter = NULL;
452         struct ldb_dn *name_dn = NULL;
453         struct ldb_dn *search_dn = NULL;
454
455         struct smb_krb5_context *smb_krb5_context = NULL;
456         int scope = LDB_SCOPE_SUBTREE;
457
458         info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
459         info1->dns_domain_name = NULL;
460         info1->result_name = NULL;
461
462         if (!name) {
463                 return WERR_INVALID_PARAM;
464         }
465
466         /* TODO: - fill the correct names in all cases!
467          *       - handle format_flags
468          */
469
470         /* here we need to set the domain_filter and/or the result_filter */
471         switch (format_offered) {
472         case DRSUAPI_DS_NAME_FORMAT_UNKNOWN:
473         {
474                 unsigned int i;
475                 enum drsuapi_DsNameFormat formats[] = {
476                         DRSUAPI_DS_NAME_FORMAT_FQDN_1779, DRSUAPI_DS_NAME_FORMAT_USER_PRINCIPAL,
477                         DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT, DRSUAPI_DS_NAME_FORMAT_CANONICAL,
478                         DRSUAPI_DS_NAME_FORMAT_GUID, DRSUAPI_DS_NAME_FORMAT_DISPLAY,
479                         DRSUAPI_DS_NAME_FORMAT_SERVICE_PRINCIPAL,
480                         DRSUAPI_DS_NAME_FORMAT_SID_OR_SID_HISTORY,
481                         DRSUAPI_DS_NAME_FORMAT_CANONICAL_EX
482                 };
483                 WERROR werr;
484                 for (i=0; i < ARRAY_SIZE(formats); i++) {
485                         werr = DsCrackNameOneName(sam_ctx, mem_ctx, format_flags, formats[i], format_desired, name, info1);
486                         if (!W_ERROR_IS_OK(werr)) {
487                                 return werr;
488                         }
489                         if (info1->status != DRSUAPI_DS_NAME_STATUS_NOT_FOUND) {
490                                 return werr;
491                         }
492                 }
493                 return werr;
494         }
495
496         case DRSUAPI_DS_NAME_FORMAT_CANONICAL:
497         case DRSUAPI_DS_NAME_FORMAT_CANONICAL_EX:
498         {
499                 char *str, *s, *account;
500                 scope = LDB_SCOPE_ONELEVEL;
501
502                 if (strlen(name) == 0) {
503                         info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
504                         return WERR_OK;
505                 }
506
507                 str = talloc_strdup(mem_ctx, name);
508                 W_ERROR_HAVE_NO_MEMORY(str);
509
510                 if (format_offered == DRSUAPI_DS_NAME_FORMAT_CANONICAL_EX) {
511                         /* Look backwards for the \n, and replace it with / */
512                         s = strrchr(str, '\n');
513                         if (!s) {
514                                 info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
515                                 return WERR_OK;
516                         }
517                         s[0] = '/';
518                 }
519
520                 s = strchr(str, '/');
521                 if (!s) {
522                         /* there must be at least one / */
523                         info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
524                         return WERR_OK;
525                 }
526
527                 s[0] = '\0';
528                 s++;
529
530                 domain_filter = talloc_asprintf(mem_ctx, "(&(objectClass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))",
531                                                 ldb_binary_encode_string(mem_ctx, str),
532                                                 LDB_OID_COMPARATOR_AND,
533                                                 SYSTEM_FLAG_CR_NTDS_DOMAIN);
534                 W_ERROR_HAVE_NO_MEMORY(domain_filter);
535
536                 /* There may not be anything after the domain component (search for the domain itself) */
537                 account = s;
538                 if (account && *account) {
539                         WERROR werr = get_format_functional_filtering_param(sam_ctx,
540                                                                                 mem_ctx,
541                                                                                 account,
542                                                                                 info1,
543                                                                                 &search_dn,
544                                                                                 domain_filter,
545                                                                                 &result_filter);
546                         if (!W_ERROR_IS_OK(werr)) {
547                                 return werr;
548                         }
549                         if (info1->status != DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR)
550                                 return WERR_OK;
551                 }
552                 break;
553         }
554         case DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT: {
555                 char *p;
556                 char *domain;
557                 const char *account = NULL;
558
559                 domain = talloc_strdup(mem_ctx, name);
560                 W_ERROR_HAVE_NO_MEMORY(domain);
561
562                 p = strchr(domain, '\\');
563                 if (!p) {
564                         /* invalid input format */
565                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
566                         return WERR_OK;
567                 }
568                 p[0] = '\0';
569
570                 if (p[1]) {
571                         account = &p[1];
572                 }
573
574                 domain_filter = talloc_asprintf(mem_ctx, 
575                                                 "(&(objectClass=crossRef)(|(dnsRoot=%s)(netbiosName=%s))(systemFlags:%s:=%u))",
576                                                 ldb_binary_encode_string(mem_ctx, domain),
577                                                 ldb_binary_encode_string(mem_ctx, domain),
578                                                 LDB_OID_COMPARATOR_AND,
579                                                 SYSTEM_FLAG_CR_NTDS_DOMAIN);
580                 W_ERROR_HAVE_NO_MEMORY(domain_filter);
581                 if (account) {
582                         result_filter = talloc_asprintf(mem_ctx, "(sAMAccountName=%s)",
583                                                         ldb_binary_encode_string(mem_ctx, account));
584                         W_ERROR_HAVE_NO_MEMORY(result_filter);
585                 }
586
587                 talloc_free(domain);
588                 break;
589         }
590
591                 /* A LDAP DN as a string */
592         case DRSUAPI_DS_NAME_FORMAT_FQDN_1779: {
593                 domain_filter = NULL;
594                 name_dn = ldb_dn_new(mem_ctx, sam_ctx, name);
595                 if (! ldb_dn_validate(name_dn)) {
596                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
597                         return WERR_OK;
598                 }
599                 break;
600         }
601
602                 /* A GUID as a string */
603         case DRSUAPI_DS_NAME_FORMAT_GUID: {
604                 struct GUID guid;
605                 char *ldap_guid;
606                 NTSTATUS nt_status;
607                 domain_filter = NULL;
608
609                 nt_status = GUID_from_string(name, &guid);
610                 if (!NT_STATUS_IS_OK(nt_status)) {
611                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
612                         return WERR_OK;
613                 }
614
615                 ldap_guid = ldap_encode_ndr_GUID(mem_ctx, &guid);
616                 if (!ldap_guid) {
617                         return WERR_NOMEM;
618                 }
619                 result_filter = talloc_asprintf(mem_ctx, "(objectGUID=%s)",
620                                                 ldap_guid);
621                 W_ERROR_HAVE_NO_MEMORY(result_filter);
622                 break;
623         }
624         case DRSUAPI_DS_NAME_FORMAT_DISPLAY: {
625                 domain_filter = NULL;
626
627                 result_filter = talloc_asprintf(mem_ctx, "(|(displayName=%s)(samAccountName=%s))",
628                                                 ldb_binary_encode_string(mem_ctx, name), 
629                                                 ldb_binary_encode_string(mem_ctx, name));
630                 W_ERROR_HAVE_NO_MEMORY(result_filter);
631                 break;
632         }
633
634                 /* A S-1234-5678 style string */
635         case DRSUAPI_DS_NAME_FORMAT_SID_OR_SID_HISTORY: {
636                 struct dom_sid *sid = dom_sid_parse_talloc(mem_ctx, name);
637                 char *ldap_sid;
638
639                 domain_filter = NULL;
640                 if (!sid) {
641                         info1->dns_domain_name = NULL;
642                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
643                         return WERR_OK;
644                 }
645                 ldap_sid = ldap_encode_ndr_dom_sid(mem_ctx, 
646                                                    sid);
647                 if (!ldap_sid) {
648                         return WERR_NOMEM;
649                 }
650                 result_filter = talloc_asprintf(mem_ctx, "(objectSid=%s)",
651                                                 ldap_sid);
652                 W_ERROR_HAVE_NO_MEMORY(result_filter);
653                 break;
654         }
655         case DRSUAPI_DS_NAME_FORMAT_USER_PRINCIPAL: {
656                 krb5_principal principal;
657                 char *unparsed_name;
658
659                 ret = smb_krb5_init_context(mem_ctx, 
660                                             ldb_get_event_context(sam_ctx),
661                                             (struct loadparm_context *)ldb_get_opaque(sam_ctx, "loadparm"), 
662                                             &smb_krb5_context);
663
664                 if (ret) {
665                         return WERR_NOMEM;
666                 }
667
668                 /* Ensure we reject compleate junk first */
669                 ret = krb5_parse_name(smb_krb5_context->krb5_context, name, &principal);
670                 if (ret) {
671                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
672                         return WERR_OK;
673                 }
674
675                 domain_filter = NULL;
676
677                 /* By getting the unparsed name here, we ensure the escaping is correct (and trust the client less) */
678                 ret = krb5_unparse_name(smb_krb5_context->krb5_context, principal, &unparsed_name);
679                 if (ret) {
680                         krb5_free_principal(smb_krb5_context->krb5_context, principal);
681                         return WERR_NOMEM;
682                 }
683
684                 krb5_free_principal(smb_krb5_context->krb5_context, principal);
685
686                 /* The ldb_binary_encode_string() here avoid LDAP filter injection attacks */
687                 result_filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(userPrincipalName=%s))", 
688                                                 ldb_binary_encode_string(mem_ctx, unparsed_name));
689
690                 free(unparsed_name);
691                 W_ERROR_HAVE_NO_MEMORY(result_filter);
692                 break;
693         }
694         case DRSUAPI_DS_NAME_FORMAT_SERVICE_PRINCIPAL: {
695                 krb5_principal principal;
696                 char *unparsed_name_short;
697                 const krb5_data *component;
698                 char *service;
699
700                 ret = smb_krb5_init_context(mem_ctx, 
701                                             ldb_get_event_context(sam_ctx),
702                                             (struct loadparm_context *)ldb_get_opaque(sam_ctx, "loadparm"), 
703                                             &smb_krb5_context);
704
705                 if (ret) {
706                         return WERR_NOMEM;
707                 }
708
709                 ret = krb5_parse_name(smb_krb5_context->krb5_context, name, &principal);
710                 if (ret == 0 &&
711                     krb5_princ_size(smb_krb5_context->krb5_context,
712                                                         principal) < 2) {
713                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
714                         krb5_free_principal(smb_krb5_context->krb5_context, principal);
715                         return WERR_OK;
716                 } else if (ret == 0) {
717                         krb5_free_principal(smb_krb5_context->krb5_context, principal);
718                 }
719                 ret = krb5_parse_name_flags(smb_krb5_context->krb5_context, name, 
720                                             KRB5_PRINCIPAL_PARSE_NO_REALM, &principal);
721                 if (ret) {
722                         return dns_domain_from_principal(mem_ctx, smb_krb5_context,
723                                                          name, info1);
724                 }
725
726                 domain_filter = NULL;
727
728                 ret = krb5_unparse_name_flags(smb_krb5_context->krb5_context, principal, 
729                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM, &unparsed_name_short);
730                 if (ret) {
731                         krb5_free_principal(smb_krb5_context->krb5_context, principal);
732                         return WERR_NOMEM;
733                 }
734
735                 component = krb5_princ_component(smb_krb5_context->krb5_context,
736                                                  principal, 0);
737                 service = (char *)component->data;
738                 if ((krb5_princ_size(smb_krb5_context->krb5_context,
739                                                         principal) == 2) &&
740                         (strcasecmp(service, "host") == 0)) {
741                         /* the 'cn' attribute is just the leading part of the name */
742                         char *computer_name;
743                         component = krb5_princ_component(
744                                                 smb_krb5_context->krb5_context,
745                                                 principal, 1);
746                         computer_name = talloc_strndup(mem_ctx, (char *)component->data,
747                                                         strcspn((char *)component->data, "."));
748                         if (computer_name == NULL) {
749                                 krb5_free_principal(smb_krb5_context->krb5_context, principal);
750                                 free(unparsed_name_short);
751                                 return WERR_NOMEM;
752                         }
753
754                         result_filter = talloc_asprintf(mem_ctx, "(|(&(servicePrincipalName=%s)(objectClass=user))(&(cn=%s)(objectClass=computer)))", 
755                                                         ldb_binary_encode_string(mem_ctx, unparsed_name_short), 
756                                                         ldb_binary_encode_string(mem_ctx, computer_name));
757                 } else {
758                         result_filter = talloc_asprintf(mem_ctx, "(&(servicePrincipalName=%s)(objectClass=user))",
759                                                         ldb_binary_encode_string(mem_ctx, unparsed_name_short));
760                 }
761                 krb5_free_principal(smb_krb5_context->krb5_context, principal);
762                 free(unparsed_name_short);
763                 W_ERROR_HAVE_NO_MEMORY(result_filter);
764
765                 break;
766         }
767         default: {
768                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
769                 return WERR_OK;
770         }
771         }
772
773         if (format_flags & DRSUAPI_DS_NAME_FLAG_SYNTACTICAL_ONLY) {
774                 return DsCrackNameOneSyntactical(mem_ctx, format_offered, format_desired,
775                                                  name_dn, name, info1);
776         }
777
778         return DsCrackNameOneFilter(sam_ctx, mem_ctx, 
779                                     smb_krb5_context, 
780                                     format_flags, format_offered, format_desired, 
781                                     name_dn, name, 
782                                     domain_filter, result_filter, 
783                                     info1, scope, search_dn);
784 }
785
786 /* Subcase of CrackNames.  It is possible to translate a LDAP-style DN
787  * (FQDN_1779) into a canoical name without actually searching the
788  * database */
789
790 static WERROR DsCrackNameOneSyntactical(TALLOC_CTX *mem_ctx,
791                                         enum drsuapi_DsNameFormat format_offered,
792                                         enum drsuapi_DsNameFormat format_desired,
793                                         struct ldb_dn *name_dn, const char *name, 
794                                         struct drsuapi_DsNameInfo1 *info1)
795 {
796         char *cracked;
797         if (format_offered != DRSUAPI_DS_NAME_FORMAT_FQDN_1779) {
798                 info1->status = DRSUAPI_DS_NAME_STATUS_NO_SYNTACTICAL_MAPPING;
799                 return WERR_OK;
800         }
801
802         switch (format_desired) {
803         case DRSUAPI_DS_NAME_FORMAT_CANONICAL: 
804                 cracked = ldb_dn_canonical_string(mem_ctx, name_dn);
805                 break;
806         case DRSUAPI_DS_NAME_FORMAT_CANONICAL_EX:
807                 cracked = ldb_dn_canonical_ex_string(mem_ctx, name_dn);
808                 break;
809         default:
810                 info1->status = DRSUAPI_DS_NAME_STATUS_NO_SYNTACTICAL_MAPPING;
811                 return WERR_OK;
812         }
813         info1->status = DRSUAPI_DS_NAME_STATUS_OK;
814         info1->result_name      = cracked;
815         if (!cracked) {
816                 return WERR_NOMEM;
817         }
818
819         return WERR_OK; 
820 }
821
822 /* Given a filter for the domain, and one for the result, perform the
823  * ldb search. The format offered and desired flags change the
824  * behaviours, including what attributes to return.
825  *
826  * The smb_krb5_context is required because we use the krb5 libs for principal parsing
827  */
828
829 static WERROR DsCrackNameOneFilter(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
830                                    struct smb_krb5_context *smb_krb5_context,
831                                    uint32_t format_flags, enum drsuapi_DsNameFormat format_offered,
832                                    enum drsuapi_DsNameFormat format_desired,
833                                    struct ldb_dn *name_dn, const char *name, 
834                                    const char *domain_filter, const char *result_filter, 
835                                    struct drsuapi_DsNameInfo1 *info1,
836                                    int scope, struct ldb_dn *search_dn)
837 {
838         int ldb_ret;
839         struct ldb_result *domain_res = NULL;
840         const char * const *domain_attrs;
841         const char * const *result_attrs;
842         struct ldb_message **result_res = NULL;
843         struct ldb_message *result = NULL;
844         int i;
845         char *p;
846         struct ldb_dn *partitions_basedn = samdb_partitions_dn(sam_ctx, mem_ctx);
847
848         const char * const _domain_attrs_1779[] = { "ncName", "dnsRoot", NULL};
849         const char * const _result_attrs_null[] = { NULL };
850
851         const char * const _domain_attrs_canonical[] = { "ncName", "dnsRoot", NULL};
852         const char * const _result_attrs_canonical[] = { "canonicalName", NULL };
853
854         const char * const _domain_attrs_nt4[] = { "ncName", "dnsRoot", "nETBIOSName", NULL};
855         const char * const _result_attrs_nt4[] = { "sAMAccountName", "objectSid", "objectClass", NULL};
856
857         const char * const _domain_attrs_guid[] = { "ncName", "dnsRoot", NULL};
858         const char * const _result_attrs_guid[] = { "objectGUID", NULL};
859
860         const char * const _domain_attrs_display[] = { "ncName", "dnsRoot", NULL};
861         const char * const _result_attrs_display[] = { "displayName", "samAccountName", NULL};
862
863         const char * const _domain_attrs_none[] = { "ncName", "dnsRoot" , NULL};
864         const char * const _result_attrs_none[] = { NULL};
865
866         /* here we need to set the attrs lists for domain and result lookups */
867         switch (format_desired) {
868         case DRSUAPI_DS_NAME_FORMAT_FQDN_1779:
869         case DRSUAPI_DS_NAME_FORMAT_CANONICAL_EX:
870                 domain_attrs = _domain_attrs_1779;
871                 result_attrs = _result_attrs_null;
872                 break;
873         case DRSUAPI_DS_NAME_FORMAT_CANONICAL:
874                 domain_attrs = _domain_attrs_canonical;
875                 result_attrs = _result_attrs_canonical;
876                 break;
877         case DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT:
878                 domain_attrs = _domain_attrs_nt4;
879                 result_attrs = _result_attrs_nt4;
880                 break;
881         case DRSUAPI_DS_NAME_FORMAT_GUID:               
882                 domain_attrs = _domain_attrs_guid;
883                 result_attrs = _result_attrs_guid;
884                 break;
885         case DRSUAPI_DS_NAME_FORMAT_DISPLAY:            
886                 domain_attrs = _domain_attrs_display;
887                 result_attrs = _result_attrs_display;
888                 break;
889         default:
890                 domain_attrs = _domain_attrs_none;
891                 result_attrs = _result_attrs_none;
892                 break;
893         }
894
895         if (domain_filter) {
896                 /* if we have a domain_filter look it up and set the result_basedn and the dns_domain_name */
897                 ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res,
898                                              partitions_basedn,
899                                              LDB_SCOPE_ONELEVEL,
900                                              domain_attrs,
901                                              "%s", domain_filter);
902
903                 if (ldb_ret != LDB_SUCCESS) {
904                         DEBUG(2, ("DsCrackNameOneFilter domain ref search failed: %s\n", ldb_errstring(sam_ctx)));
905                         info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
906                         return WERR_OK;
907                 }
908
909                 switch (domain_res->count) {
910                 case 1:
911                         break;
912                 case 0:
913                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
914                         return WERR_OK;
915                 default:
916                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE;
917                         return WERR_OK;
918                 }
919
920                 info1->dns_domain_name  = ldb_msg_find_attr_as_string(domain_res->msgs[0], "dnsRoot", NULL);
921                 W_ERROR_HAVE_NO_MEMORY(info1->dns_domain_name);
922                 info1->status           = DRSUAPI_DS_NAME_STATUS_DOMAIN_ONLY;
923         } else {
924                 info1->dns_domain_name  = NULL;
925                 info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
926         }
927
928         if (result_filter) {
929                 int ret;
930                 struct ldb_result *res;
931                 uint32_t dsdb_flags = 0;
932                 struct ldb_dn *real_search_dn;
933
934                 if (domain_res) {
935                         if (!search_dn) {
936                                 struct ldb_dn *tmp_dn = samdb_result_dn(sam_ctx, mem_ctx, domain_res->msgs[0], "ncName", NULL);
937                                 real_search_dn = tmp_dn;
938                         } else {
939                                 real_search_dn = search_dn;
940                         }
941                 } else {
942                         dsdb_flags = DSDB_SEARCH_SEARCH_ALL_PARTITIONS;
943                         real_search_dn = NULL;
944                 }
945                 if (format_desired == DRSUAPI_DS_NAME_FORMAT_GUID){
946                          dsdb_flags = dsdb_flags| DSDB_SEARCH_SHOW_DELETED;
947                 }
948
949                 /* search with the 'phantom root' flag */
950                 ret = dsdb_search(sam_ctx, mem_ctx, &res,
951                                   real_search_dn,
952                                   scope,
953                                   result_attrs,
954                                   dsdb_flags,
955                                   "%s", result_filter);
956                 if (ret != LDB_SUCCESS) {
957                         DEBUG(2, ("DsCrackNameOneFilter phantom root search failed: %s\n",
958                                   ldb_errstring(sam_ctx)));
959                         info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
960                         return WERR_OK;
961                 }
962
963                 ldb_ret = res->count;
964                 result_res = res->msgs;
965         } else if (format_offered == DRSUAPI_DS_NAME_FORMAT_FQDN_1779) {
966                 ldb_ret = gendb_search_dn(sam_ctx, mem_ctx, name_dn, &result_res,
967                                           result_attrs);
968         } else if (domain_res) {
969                 name_dn = samdb_result_dn(sam_ctx, mem_ctx, domain_res->msgs[0], "ncName", NULL);
970                 ldb_ret = gendb_search_dn(sam_ctx, mem_ctx, name_dn, &result_res,
971                                           result_attrs);
972         } else {
973                 /* Can't happen */
974                 DEBUG(0, ("LOGIC ERROR: DsCrackNameOneFilter domain ref search not available: This can't happen...\n"));
975                 info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
976                 return WERR_OK;
977         }
978
979         switch (ldb_ret) {
980         case 1:
981                 result = result_res[0];
982                 break;
983         case 0:
984                 switch (format_offered) {
985                 case DRSUAPI_DS_NAME_FORMAT_SERVICE_PRINCIPAL: 
986                         return DsCrackNameSPNAlias(sam_ctx, mem_ctx, 
987                                                    smb_krb5_context, 
988                                                    format_flags, format_offered, format_desired,
989                                                    name, info1);
990
991                 case DRSUAPI_DS_NAME_FORMAT_USER_PRINCIPAL:
992                         return DsCrackNameUPN(sam_ctx, mem_ctx, smb_krb5_context, 
993                                               format_flags, format_offered, format_desired,
994                                               name, info1);
995                 default:
996                         break;
997                 }
998                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
999                 return WERR_OK;
1000         case -1:
1001                 DEBUG(2, ("DsCrackNameOneFilter result search failed: %s\n", ldb_errstring(sam_ctx)));
1002                 info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
1003                 return WERR_OK;
1004         default:
1005                 switch (format_offered) {
1006                 case DRSUAPI_DS_NAME_FORMAT_CANONICAL:
1007                 case DRSUAPI_DS_NAME_FORMAT_CANONICAL_EX:
1008                 {
1009                         const char *canonical_name = NULL; /* Not required, but we get warnings... */
1010                         /* We may need to manually filter further */
1011                         for (i = 0; i < ldb_ret; i++) {
1012                                 switch (format_offered) {
1013                                 case DRSUAPI_DS_NAME_FORMAT_CANONICAL:
1014                                         canonical_name = ldb_dn_canonical_string(mem_ctx, result_res[i]->dn);
1015                                         break;
1016                                 case DRSUAPI_DS_NAME_FORMAT_CANONICAL_EX:
1017                                         canonical_name = ldb_dn_canonical_ex_string(mem_ctx, result_res[i]->dn);
1018                                         break;
1019                                 default:
1020                                         break;
1021                                 }
1022                                 if (strcasecmp_m(canonical_name, name) == 0) {
1023                                         result = result_res[i];
1024                                         break;
1025                                 }
1026                         }
1027                         if (!result) {
1028                                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
1029                                 return WERR_OK;
1030                         }
1031                 }
1032                 default:
1033                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE;
1034                         return WERR_OK;
1035                 }
1036         }
1037
1038         info1->dns_domain_name = ldb_dn_canonical_string(mem_ctx, result->dn);
1039         W_ERROR_HAVE_NO_MEMORY(info1->dns_domain_name);
1040         p = strchr(info1->dns_domain_name, '/');
1041         if (p) {
1042                 p[0] = '\0';
1043         }
1044
1045         /* here we can use result and domain_res[0] */
1046         switch (format_desired) {
1047         case DRSUAPI_DS_NAME_FORMAT_FQDN_1779: {
1048                 info1->result_name      = ldb_dn_alloc_linearized(mem_ctx, result->dn);
1049                 W_ERROR_HAVE_NO_MEMORY(info1->result_name);
1050
1051                 info1->status           = DRSUAPI_DS_NAME_STATUS_OK;
1052                 return WERR_OK;
1053         }
1054         case DRSUAPI_DS_NAME_FORMAT_CANONICAL: {
1055                 info1->result_name      = ldb_msg_find_attr_as_string(result, "canonicalName", NULL);
1056                 info1->status           = DRSUAPI_DS_NAME_STATUS_OK;
1057                 return WERR_OK;
1058         }
1059         case DRSUAPI_DS_NAME_FORMAT_CANONICAL_EX: {
1060                 /* Not in the virtual ldb attribute */
1061                 return DsCrackNameOneSyntactical(mem_ctx, 
1062                                                  DRSUAPI_DS_NAME_FORMAT_FQDN_1779, 
1063                                                  DRSUAPI_DS_NAME_FORMAT_CANONICAL_EX,
1064                                                  result->dn, name, info1);
1065         }
1066         case DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT: {
1067
1068                 const struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, result, "objectSid");
1069                 const char *_acc = "", *_dom = "";
1070
1071                 if (samdb_find_attribute(sam_ctx, result, "objectClass", "domain")) {
1072
1073                         ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res,
1074                                                      partitions_basedn,
1075                                                      LDB_SCOPE_ONELEVEL,
1076                                                      domain_attrs,
1077                                                      "(ncName=%s)", ldb_dn_get_linearized(result->dn));
1078
1079                         if (ldb_ret != LDB_SUCCESS) {
1080                                 DEBUG(2, ("DsCrackNameOneFilter domain ref search failed: %s\n", ldb_errstring(sam_ctx)));
1081                                 info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
1082                                 return WERR_OK;
1083                         }
1084
1085                         switch (domain_res->count) {
1086                         case 1:
1087                                 break;
1088                         case 0:
1089                                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
1090                                 return WERR_OK;
1091                         default:
1092                                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE;
1093                                 return WERR_OK;
1094                         }
1095                         _dom = ldb_msg_find_attr_as_string(domain_res->msgs[0], "nETBIOSName", NULL);
1096                         W_ERROR_HAVE_NO_MEMORY(_dom);
1097                 } else {
1098                         _acc = ldb_msg_find_attr_as_string(result, "sAMAccountName", NULL);
1099                         if (!_acc) {
1100                                 info1->status = DRSUAPI_DS_NAME_STATUS_NO_MAPPING;
1101                                 return WERR_OK;
1102                         }
1103                         if (dom_sid_in_domain(dom_sid_parse_talloc(mem_ctx, SID_BUILTIN), sid)) {
1104                                 _dom = "BUILTIN";
1105                         } else {
1106                                 const char *attrs[] = { NULL };
1107                                 struct ldb_result *domain_res2;
1108                                 struct dom_sid *dom_sid = dom_sid_dup(mem_ctx, sid);
1109                                 if (!dom_sid) {
1110                                         return WERR_OK;
1111                                 }
1112                                 dom_sid->num_auths--;
1113                                 ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res,
1114                                                              NULL,
1115                                                              LDB_SCOPE_BASE,
1116                                                              attrs,
1117                                                              "(&(objectSid=%s)(objectClass=domain))", 
1118                                                              ldap_encode_ndr_dom_sid(mem_ctx, dom_sid));
1119
1120                                 if (ldb_ret != LDB_SUCCESS) {
1121                                         DEBUG(2, ("DsCrackNameOneFilter domain search failed: %s\n", ldb_errstring(sam_ctx)));
1122                                         info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
1123                                         return WERR_OK;
1124                                 }
1125
1126                                 switch (domain_res->count) {
1127                                 case 1:
1128                                         break;
1129                                 case 0:
1130                                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
1131                                         return WERR_OK;
1132                                 default:
1133                                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE;
1134                                         return WERR_OK;
1135                                 }
1136
1137                                 ldb_ret = ldb_search(sam_ctx, mem_ctx, &domain_res2,
1138                                                              partitions_basedn,
1139                                                              LDB_SCOPE_ONELEVEL,
1140                                                              domain_attrs,
1141                                                              "(ncName=%s)", ldb_dn_get_linearized(domain_res->msgs[0]->dn));
1142
1143                                 if (ldb_ret != LDB_SUCCESS) {
1144                                         DEBUG(2, ("DsCrackNameOneFilter domain ref search failed: %s\n", ldb_errstring(sam_ctx)));
1145                                         info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
1146                                         return WERR_OK;
1147                                 }
1148
1149                                 switch (domain_res2->count) {
1150                                 case 1:
1151                                         break;
1152                                 case 0:
1153                                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
1154                                         return WERR_OK;
1155                                 default:
1156                                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE;
1157                                         return WERR_OK;
1158                                 }
1159                                 _dom = ldb_msg_find_attr_as_string(domain_res2->msgs[0], "nETBIOSName", NULL);
1160                                 W_ERROR_HAVE_NO_MEMORY(_dom);
1161                         }
1162                 }
1163
1164                 info1->result_name      = talloc_asprintf(mem_ctx, "%s\\%s", _dom, _acc);
1165                 W_ERROR_HAVE_NO_MEMORY(info1->result_name);
1166
1167                 info1->status           = DRSUAPI_DS_NAME_STATUS_OK;
1168                 return WERR_OK;
1169         }
1170         case DRSUAPI_DS_NAME_FORMAT_GUID: {
1171                 struct GUID guid;
1172
1173                 guid = samdb_result_guid(result, "objectGUID");
1174
1175                 info1->result_name      = GUID_string2(mem_ctx, &guid);
1176                 W_ERROR_HAVE_NO_MEMORY(info1->result_name);
1177
1178                 info1->status           = DRSUAPI_DS_NAME_STATUS_OK;
1179                 return WERR_OK;
1180         }
1181         case DRSUAPI_DS_NAME_FORMAT_DISPLAY: {
1182                 info1->result_name      = ldb_msg_find_attr_as_string(result, "displayName", NULL);
1183                 if (!info1->result_name) {
1184                         info1->result_name      = ldb_msg_find_attr_as_string(result, "sAMAccountName", NULL);
1185                 } 
1186                 if (!info1->result_name) {
1187                         info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
1188                 } else {
1189                         info1->status = DRSUAPI_DS_NAME_STATUS_OK;
1190                 }
1191                 return WERR_OK;
1192         }
1193         case DRSUAPI_DS_NAME_FORMAT_SERVICE_PRINCIPAL: {
1194                 info1->status = DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE;
1195                 return WERR_OK;
1196         }
1197         case DRSUAPI_DS_NAME_FORMAT_DNS_DOMAIN: 
1198         case DRSUAPI_DS_NAME_FORMAT_SID_OR_SID_HISTORY: {
1199                 info1->dns_domain_name = NULL;
1200                 info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
1201                 return WERR_OK;
1202         }
1203         default:
1204                 info1->status = DRSUAPI_DS_NAME_STATUS_NO_MAPPING;
1205                 return WERR_OK;
1206         }
1207 }
1208
1209 /* Given a user Principal Name (such as foo@bar.com),
1210  * return the user and domain DNs.  This is used in the KDC to then
1211  * return the Keys and evaluate policy */
1212
1213 NTSTATUS crack_user_principal_name(struct ldb_context *sam_ctx, 
1214                                    TALLOC_CTX *mem_ctx, 
1215                                    const char *user_principal_name, 
1216                                    struct ldb_dn **user_dn,
1217                                    struct ldb_dn **domain_dn) 
1218 {
1219         WERROR werr;
1220         struct drsuapi_DsNameInfo1 info1;
1221         werr = DsCrackNameOneName(sam_ctx, mem_ctx, 0,
1222                                   DRSUAPI_DS_NAME_FORMAT_USER_PRINCIPAL,
1223                                   DRSUAPI_DS_NAME_FORMAT_FQDN_1779, 
1224                                   user_principal_name,
1225                                   &info1);
1226         if (!W_ERROR_IS_OK(werr)) {
1227                 return werror_to_ntstatus(werr);
1228         }
1229         switch (info1.status) {
1230         case DRSUAPI_DS_NAME_STATUS_OK:
1231                 break;
1232         case DRSUAPI_DS_NAME_STATUS_NOT_FOUND:
1233         case DRSUAPI_DS_NAME_STATUS_DOMAIN_ONLY:
1234         case DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE:
1235                 return NT_STATUS_NO_SUCH_USER;
1236         case DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR:
1237         default:
1238                 return NT_STATUS_UNSUCCESSFUL;
1239         }
1240
1241         *user_dn = ldb_dn_new(mem_ctx, sam_ctx, info1.result_name);
1242
1243         if (domain_dn) {
1244                 werr = DsCrackNameOneName(sam_ctx, mem_ctx, 0,
1245                                           DRSUAPI_DS_NAME_FORMAT_CANONICAL,
1246                                           DRSUAPI_DS_NAME_FORMAT_FQDN_1779, 
1247                                           talloc_asprintf(mem_ctx, "%s/", 
1248                                                           info1.dns_domain_name),
1249                                           &info1);
1250                 if (!W_ERROR_IS_OK(werr)) {
1251                         return werror_to_ntstatus(werr);
1252                 }
1253                 switch (info1.status) {
1254                 case DRSUAPI_DS_NAME_STATUS_OK:
1255                         break;
1256                 case DRSUAPI_DS_NAME_STATUS_NOT_FOUND:
1257                 case DRSUAPI_DS_NAME_STATUS_DOMAIN_ONLY:
1258                 case DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE:
1259                         return NT_STATUS_NO_SUCH_USER;
1260                 case DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR:
1261                 default:
1262                         return NT_STATUS_UNSUCCESSFUL;
1263                 }
1264
1265                 *domain_dn = ldb_dn_new(mem_ctx, sam_ctx, info1.result_name);
1266         }
1267
1268         return NT_STATUS_OK;
1269 }
1270
1271 /* Given a Service Principal Name (such as host/foo.bar.com@BAR.COM),
1272  * return the user and domain DNs.  This is used in the KDC to then
1273  * return the Keys and evaluate policy */
1274
1275 NTSTATUS crack_service_principal_name(struct ldb_context *sam_ctx, 
1276                                       TALLOC_CTX *mem_ctx, 
1277                                       const char *service_principal_name, 
1278                                       struct ldb_dn **user_dn,
1279                                       struct ldb_dn **domain_dn) 
1280 {
1281         WERROR werr;
1282         struct drsuapi_DsNameInfo1 info1;
1283         werr = DsCrackNameOneName(sam_ctx, mem_ctx, 0,
1284                                   DRSUAPI_DS_NAME_FORMAT_SERVICE_PRINCIPAL,
1285                                   DRSUAPI_DS_NAME_FORMAT_FQDN_1779, 
1286                                   service_principal_name,
1287                                   &info1);
1288         if (!W_ERROR_IS_OK(werr)) {
1289                 return werror_to_ntstatus(werr);
1290         }
1291         switch (info1.status) {
1292         case DRSUAPI_DS_NAME_STATUS_OK:
1293                 break;
1294         case DRSUAPI_DS_NAME_STATUS_NOT_FOUND:
1295         case DRSUAPI_DS_NAME_STATUS_DOMAIN_ONLY:
1296         case DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE:
1297                 return NT_STATUS_NO_SUCH_USER;
1298         case DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR:
1299         default:
1300                 return NT_STATUS_UNSUCCESSFUL;
1301         }
1302
1303         *user_dn = ldb_dn_new(mem_ctx, sam_ctx, info1.result_name);
1304
1305         if (domain_dn) {
1306                 werr = DsCrackNameOneName(sam_ctx, mem_ctx, 0,
1307                                           DRSUAPI_DS_NAME_FORMAT_CANONICAL,
1308                                           DRSUAPI_DS_NAME_FORMAT_FQDN_1779, 
1309                                           talloc_asprintf(mem_ctx, "%s/", 
1310                                                           info1.dns_domain_name),
1311                                           &info1);
1312                 if (!W_ERROR_IS_OK(werr)) {
1313                         return werror_to_ntstatus(werr);
1314                 }
1315                 switch (info1.status) {
1316                 case DRSUAPI_DS_NAME_STATUS_OK:
1317                         break;
1318                 case DRSUAPI_DS_NAME_STATUS_NOT_FOUND:
1319                 case DRSUAPI_DS_NAME_STATUS_DOMAIN_ONLY:
1320                 case DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE:
1321                         return NT_STATUS_NO_SUCH_USER;
1322                 case DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR:
1323                 default:
1324                         return NT_STATUS_UNSUCCESSFUL;
1325                 }
1326
1327                 *domain_dn = ldb_dn_new(mem_ctx, sam_ctx, info1.result_name);
1328         }
1329
1330         return NT_STATUS_OK;
1331 }
1332
1333 NTSTATUS crack_name_to_nt4_name(TALLOC_CTX *mem_ctx, 
1334                                 struct tevent_context *ev_ctx, 
1335                                 struct loadparm_context *lp_ctx,
1336                                 enum drsuapi_DsNameFormat format_offered,
1337                                 const char *name, 
1338                                 const char **nt4_domain, const char **nt4_account)
1339 {
1340         WERROR werr;
1341         struct drsuapi_DsNameInfo1 info1;
1342         struct ldb_context *ldb;
1343         char *p;
1344
1345         /* Handle anonymous bind */
1346         if (!name || !*name) {
1347                 *nt4_domain = "";
1348                 *nt4_account = "";
1349                 return NT_STATUS_OK;
1350         }
1351
1352         ldb = samdb_connect(mem_ctx, ev_ctx, lp_ctx, system_session(lp_ctx), 0);
1353         if (ldb == NULL) {
1354                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1355         }
1356
1357         werr = DsCrackNameOneName(ldb, mem_ctx, 0,
1358                                   format_offered, 
1359                                   DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT,
1360                                   name,
1361                                   &info1);
1362         if (!W_ERROR_IS_OK(werr)) {
1363                 return werror_to_ntstatus(werr);
1364         }
1365         switch (info1.status) {
1366         case DRSUAPI_DS_NAME_STATUS_OK:
1367                 break;
1368         case DRSUAPI_DS_NAME_STATUS_NOT_FOUND:
1369         case DRSUAPI_DS_NAME_STATUS_DOMAIN_ONLY:
1370         case DRSUAPI_DS_NAME_STATUS_NOT_UNIQUE:
1371                 return NT_STATUS_NO_SUCH_USER;
1372         case DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR:
1373         default:
1374                 return NT_STATUS_UNSUCCESSFUL;
1375         }
1376
1377         *nt4_domain = talloc_strdup(mem_ctx, info1.result_name);
1378         if (*nt4_domain == NULL) {
1379                 return NT_STATUS_NO_MEMORY;
1380         }
1381
1382         p = strchr(*nt4_domain, '\\');
1383         if (!p) {
1384                 return NT_STATUS_INVALID_PARAMETER;
1385         }
1386         p[0] = '\0';
1387
1388         *nt4_account = talloc_strdup(mem_ctx, &p[1]);
1389         if (*nt4_account == NULL) {
1390                 return NT_STATUS_NO_MEMORY;
1391         }
1392
1393         return NT_STATUS_OK;
1394 }
1395
1396 NTSTATUS crack_auto_name_to_nt4_name(TALLOC_CTX *mem_ctx,
1397                                      struct tevent_context *ev_ctx, 
1398                                      struct loadparm_context *lp_ctx,
1399                                      const char *name,
1400                                      const char **nt4_domain,
1401                                      const char **nt4_account)
1402 {
1403         enum drsuapi_DsNameFormat format_offered = DRSUAPI_DS_NAME_FORMAT_UNKNOWN;
1404
1405         /* Handle anonymous bind */
1406         if (!name || !*name) {
1407                 *nt4_domain = "";
1408                 *nt4_account = "";
1409                 return NT_STATUS_OK;
1410         }
1411
1412         if (strchr_m(name, '=')) {
1413                 format_offered = DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
1414         } else if (strchr_m(name, '@')) {
1415                 format_offered = DRSUAPI_DS_NAME_FORMAT_USER_PRINCIPAL;
1416         } else if (strchr_m(name, '\\')) {
1417                 format_offered = DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT;
1418         } else if (strchr_m(name, '/')) {
1419                 format_offered = DRSUAPI_DS_NAME_FORMAT_CANONICAL;
1420         } else {
1421                 return NT_STATUS_NO_SUCH_USER;
1422         }
1423
1424         return crack_name_to_nt4_name(mem_ctx, ev_ctx, lp_ctx, format_offered, name, nt4_domain, nt4_account);
1425 }
1426
1427
1428 WERROR dcesrv_drsuapi_ListRoles(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
1429                                 const struct drsuapi_DsNameRequest1 *req1,
1430                                 struct drsuapi_DsNameCtr1 **ctr1)
1431 {
1432         struct drsuapi_DsNameInfo1 *names;
1433         uint32_t i;
1434         uint32_t count = 5;/*number of fsmo role owners we are going to return*/
1435
1436         *ctr1 = talloc(mem_ctx, struct drsuapi_DsNameCtr1);
1437         W_ERROR_HAVE_NO_MEMORY(*ctr1);
1438         names = talloc_array(mem_ctx, struct drsuapi_DsNameInfo1, count);
1439         W_ERROR_HAVE_NO_MEMORY(names);
1440
1441         for (i = 0; i < count; i++) {
1442                 WERROR werr;
1443                 struct ldb_dn *role_owner_dn, *fsmo_role_dn, *server_dn;
1444                 werr = dsdb_get_fsmo_role_info(mem_ctx, sam_ctx, i,
1445                                                &fsmo_role_dn, &role_owner_dn);
1446                 if(!W_ERROR_IS_OK(werr)) {
1447                         return werr;
1448                 }
1449                 server_dn = ldb_dn_copy(mem_ctx, role_owner_dn);
1450                 ldb_dn_remove_child_components(server_dn, 1);
1451                 names[i].status = DRSUAPI_DS_NAME_STATUS_OK;
1452                 names[i].dns_domain_name = samdb_dn_to_dnshostname(sam_ctx, mem_ctx,
1453                                                                    server_dn);
1454                 if(!names[i].dns_domain_name) {
1455                         DEBUG(4, ("list_roles: Failed to find dNSHostName for server %s\n",
1456                                   ldb_dn_get_linearized(server_dn)));
1457                 }
1458                 names[i].result_name = talloc_strdup(mem_ctx, ldb_dn_get_linearized(role_owner_dn));
1459         }
1460
1461         (*ctr1)->count = count;
1462         (*ctr1)->array = names;
1463
1464         return WERR_OK;
1465 }
1466
1467 WERROR dcesrv_drsuapi_CrackNamesByNameFormat(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
1468                                              const struct drsuapi_DsNameRequest1 *req1,
1469                                              struct drsuapi_DsNameCtr1 **ctr1)
1470 {
1471         struct drsuapi_DsNameInfo1 *names;
1472         uint32_t i, count;
1473         WERROR status;
1474
1475         *ctr1 = talloc_zero(mem_ctx, struct drsuapi_DsNameCtr1);
1476         W_ERROR_HAVE_NO_MEMORY(*ctr1);
1477
1478         count = req1->count;
1479         names = talloc_array(mem_ctx, struct drsuapi_DsNameInfo1, count);
1480         W_ERROR_HAVE_NO_MEMORY(names);
1481
1482         for (i=0; i < count; i++) {
1483                 status = DsCrackNameOneName(sam_ctx, mem_ctx,
1484                                             req1->format_flags,
1485                                             req1->format_offered,
1486                                             req1->format_desired,
1487                                             req1->names[i].str,
1488                                             &names[i]);
1489                 if (!W_ERROR_IS_OK(status)) {
1490                         return status;
1491                 }
1492         }
1493
1494         (*ctr1)->count = count;
1495         (*ctr1)->array = names;
1496
1497         return WERR_OK;
1498 }
1499
1500 WERROR dcesrv_drsuapi_ListInfoServer(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
1501                                      const struct drsuapi_DsNameRequest1 *req1,
1502                                      struct drsuapi_DsNameCtr1 **_ctr1)
1503 {
1504         struct drsuapi_DsNameInfo1 *names;
1505         struct ldb_result *res;
1506         struct ldb_dn *server_dn, *dn;
1507         struct drsuapi_DsNameCtr1 *ctr1;
1508         int ret, i;
1509         const char *str;
1510         const char *attrs[] = {
1511                 "dn",
1512                 "dNSHostName",
1513                 "serverReference",
1514                 NULL
1515         };
1516
1517         *_ctr1 = NULL;
1518
1519         ctr1 = talloc_zero(mem_ctx, struct drsuapi_DsNameCtr1);
1520         W_ERROR_HAVE_NO_MEMORY(ctr1);
1521
1522         /*
1523          * No magic value here, we have to return 3 entries according to the
1524          * MS-DRSR.pdf
1525          */
1526         ctr1->count = 3;
1527         names = talloc_zero_array(ctr1, struct drsuapi_DsNameInfo1,
1528                                   ctr1->count);
1529         W_ERROR_HAVE_NO_MEMORY(names);
1530         ctr1->array = names;
1531
1532         for (i=0; i < ctr1->count; i++) {
1533                 names[i].status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
1534         }
1535         *_ctr1 = ctr1;
1536
1537         if (req1->count != 1) {
1538                 DEBUG(1, ("Expected a count of 1 for the ListInfoServer crackname \n"));
1539                 return WERR_OK;
1540         }
1541
1542         if (req1->names[0].str == NULL) {
1543                 return WERR_OK;
1544         }
1545
1546         server_dn = ldb_dn_new(mem_ctx, sam_ctx, req1->names[0].str);
1547         W_ERROR_HAVE_NO_MEMORY(server_dn);
1548
1549         ret = ldb_search(sam_ctx, mem_ctx, &res, server_dn, LDB_SCOPE_ONELEVEL,
1550                          NULL, "(objectClass=nTDSDSA)");
1551
1552         if (ret != LDB_SUCCESS) {
1553                 DEBUG(1, ("Search for objectClass=nTDSDSA "
1554                           "returned less than 1 objects\n"));
1555                 return WERR_OK;
1556         }
1557
1558         if (res->count != 1) {
1559                 DEBUG(1, ("Search for objectClass=nTDSDSA "
1560                           "returned less than 1 objects\n"));
1561                 return WERR_OK;
1562         }
1563
1564         if (res->msgs[0]->dn) {
1565                 names[0].result_name = ldb_dn_alloc_linearized(names, res->msgs[0]->dn);
1566                 W_ERROR_HAVE_NO_MEMORY(names[0].result_name);
1567                 names[0].status = DRSUAPI_DS_NAME_STATUS_OK;
1568         }
1569
1570         talloc_free(res);
1571
1572         ret = ldb_search(sam_ctx, mem_ctx, &res, server_dn, LDB_SCOPE_BASE,
1573                          attrs, "(objectClass=*)");
1574         if (ret != LDB_SUCCESS) {
1575                 DEBUG(1, ("Search for objectClass=* on dn %s"
1576                           "returned %s\n", req1->names[0].str,
1577                           ldb_strerror(ret)));
1578                 return WERR_OK;
1579         }
1580
1581         if (res->count != 1) {
1582                 DEBUG(1, ("Search for objectClass=* on dn %s"
1583                           "returned less than 1 objects\n", req1->names[0].str));
1584                 return WERR_OK;
1585         }
1586
1587         str = ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
1588         if (str != NULL) {
1589                 names[1].result_name = talloc_strdup(names, str);
1590                 W_ERROR_HAVE_NO_MEMORY(names[1].result_name);
1591                 names[1].status = DRSUAPI_DS_NAME_STATUS_OK;
1592         }
1593
1594         dn = ldb_msg_find_attr_as_dn(sam_ctx, mem_ctx, res->msgs[0], "serverReference");
1595         if (dn != NULL) {
1596                 names[2].result_name = ldb_dn_alloc_linearized(names, dn);
1597                 W_ERROR_HAVE_NO_MEMORY(names[2].result_name);
1598                 names[2].status = DRSUAPI_DS_NAME_STATUS_OK;
1599         }
1600
1601         talloc_free(dn);
1602         talloc_free(res);
1603
1604         return WERR_OK;
1605 }