69a049556ddd0dbcd9906a60988710dac98de6a1
[bbaumbach/samba-autobuild/.git] / source3 / winbindd / winbindd_msrpc.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind rpc backend functions
5
6    Copyright (C) Tim Potter 2000-2001,2003
7    Copyright (C) Andrew Tridgell 2001
8    Copyright (C) Volker Lendecke 2005
9    Copyright (C) Guenther Deschner 2008 (pidl conversion)
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 "winbindd.h"
27 #include "winbindd_rpc.h"
28
29 #include "../librpc/gen_ndr/ndr_samr_c.h"
30 #include "rpc_client/cli_pipe.h"
31 #include "rpc_client/cli_samr.h"
32 #include "rpc_client/cli_lsarpc.h"
33 #include "../libcli/security/security.h"
34 #include "libsmb/samlogon_cache.h"
35
36 #undef DBGC_CLASS
37 #define DBGC_CLASS DBGC_WINBIND
38
39 static NTSTATUS winbindd_lookup_names(TALLOC_CTX *mem_ctx,
40                                       struct winbindd_domain *domain,
41                                       uint32_t num_names,
42                                       const char **names,
43                                       const char ***domains,
44                                       struct dom_sid **sids,
45                                       enum lsa_SidType **types);
46
47 /* Query display info for a domain.  This returns enough information plus a
48    bit extra to give an overview of domain users for the User Manager
49    application. */
50 static NTSTATUS msrpc_query_user_list(struct winbindd_domain *domain,
51                                       TALLOC_CTX *mem_ctx,
52                                       uint32_t **prids)
53 {
54         struct rpc_pipe_client *samr_pipe = NULL;
55         struct policy_handle dom_pol;
56         uint32_t *rids = NULL;
57         TALLOC_CTX *tmp_ctx;
58         NTSTATUS status;
59
60         DEBUG(3, ("msrpc_query_user_list\n"));
61
62         tmp_ctx = talloc_stackframe();
63         if (tmp_ctx == NULL) {
64                 return NT_STATUS_NO_MEMORY;
65         }
66
67         if ( !winbindd_can_contact_domain( domain ) ) {
68                 DEBUG(10,("query_user_list: No incoming trust for domain %s\n",
69                           domain->name));
70                 status = NT_STATUS_OK;
71                 goto done;
72         }
73
74         status = cm_connect_sam(domain, tmp_ctx, false, &samr_pipe, &dom_pol);
75         if (!NT_STATUS_IS_OK(status)) {
76                 goto done;
77         }
78
79         status = rpc_query_user_list(tmp_ctx,
80                                      samr_pipe,
81                                      &dom_pol,
82                                      &domain->sid,
83                                      &rids);
84         if (!NT_STATUS_IS_OK(status)) {
85                 goto done;
86         }
87
88         if (prids) {
89                 *prids = talloc_move(mem_ctx, &rids);
90         }
91
92 done:
93         TALLOC_FREE(rids);
94         TALLOC_FREE(tmp_ctx);
95         return status;
96 }
97
98 /* list all domain groups */
99 static NTSTATUS msrpc_enum_dom_groups(struct winbindd_domain *domain,
100                                       TALLOC_CTX *mem_ctx,
101                                       uint32_t *pnum_info,
102                                       struct wb_acct_info **pinfo)
103 {
104         struct rpc_pipe_client *samr_pipe;
105         struct policy_handle dom_pol;
106         struct wb_acct_info *info = NULL;
107         uint32_t num_info = 0;
108         TALLOC_CTX *tmp_ctx;
109         NTSTATUS status;
110
111         DEBUG(3,("msrpc_enum_dom_groups\n"));
112
113         if (pnum_info) {
114                 *pnum_info = 0;
115         }
116
117         tmp_ctx = talloc_stackframe();
118         if (tmp_ctx == NULL) {
119                 return NT_STATUS_NO_MEMORY;
120         }
121
122         if ( !winbindd_can_contact_domain( domain ) ) {
123                 DEBUG(10,("enum_domain_groups: No incoming trust for domain %s\n",
124                           domain->name));
125                 status = NT_STATUS_OK;
126                 goto done;
127         }
128
129         status = cm_connect_sam(domain, tmp_ctx, false, &samr_pipe, &dom_pol);
130         if (!NT_STATUS_IS_OK(status)) {
131                 goto done;
132         }
133
134         status = rpc_enum_dom_groups(tmp_ctx,
135                                      samr_pipe,
136                                      &dom_pol,
137                                      &num_info,
138                                      &info);
139         if (!NT_STATUS_IS_OK(status)) {
140                 goto done;
141         }
142
143         if (pnum_info) {
144                 *pnum_info = num_info;
145         }
146
147         if (pinfo) {
148                 *pinfo = talloc_move(mem_ctx, &info);
149         }
150
151 done:
152         TALLOC_FREE(tmp_ctx);
153         return status;
154 }
155
156 /* List all domain groups */
157
158 static NTSTATUS msrpc_enum_local_groups(struct winbindd_domain *domain,
159                                         TALLOC_CTX *mem_ctx,
160                                         uint32_t *pnum_info,
161                                         struct wb_acct_info **pinfo)
162 {
163         struct rpc_pipe_client *samr_pipe;
164         struct policy_handle dom_pol;
165         struct wb_acct_info *info = NULL;
166         uint32_t num_info = 0;
167         TALLOC_CTX *tmp_ctx;
168         NTSTATUS status;
169
170         DEBUG(3,("msrpc_enum_local_groups\n"));
171
172         if (pnum_info) {
173                 *pnum_info = 0;
174         }
175
176         tmp_ctx = talloc_stackframe();
177         if (tmp_ctx == NULL) {
178                 return NT_STATUS_NO_MEMORY;
179         }
180
181         if ( !winbindd_can_contact_domain( domain ) ) {
182                 DEBUG(10,("enum_local_groups: No incoming trust for domain %s\n",
183                           domain->name));
184                 status = NT_STATUS_OK;
185                 goto done;
186         }
187
188         status = cm_connect_sam(domain, tmp_ctx, false, &samr_pipe, &dom_pol);
189         if (!NT_STATUS_IS_OK(status)) {
190                 goto done;
191         }
192
193         status = rpc_enum_local_groups(mem_ctx,
194                                        samr_pipe,
195                                        &dom_pol,
196                                        &num_info,
197                                        &info);
198         if (!NT_STATUS_IS_OK(status)) {
199                 goto done;
200         }
201
202         if (pnum_info) {
203                 *pnum_info = num_info;
204         }
205
206         if (pinfo) {
207                 *pinfo = talloc_move(mem_ctx, &info);
208         }
209
210 done:
211         TALLOC_FREE(tmp_ctx);
212         return status;
213 }
214
215 /* convert a single name to a sid in a domain */
216 static NTSTATUS msrpc_name_to_sid(struct winbindd_domain *domain,
217                                   TALLOC_CTX *mem_ctx,
218                                   const char *domain_name,
219                                   const char *name,
220                                   uint32_t flags,
221                                   struct dom_sid *sid,
222                                   enum lsa_SidType *type)
223 {
224         NTSTATUS result;
225         struct dom_sid *sids = NULL;
226         enum lsa_SidType *types = NULL;
227         char *full_name = NULL;
228         const char *names[1];
229         const char **domains;
230         NTSTATUS name_map_status = NT_STATUS_UNSUCCESSFUL;
231         char *mapped_name = NULL;
232
233         if (name == NULL || *name=='\0') {
234                 full_name = talloc_asprintf(mem_ctx, "%s", domain_name);
235         } else if (domain_name == NULL || *domain_name == '\0') {
236                 full_name = talloc_asprintf(mem_ctx, "%s", name);
237         } else {
238                 full_name = talloc_asprintf(mem_ctx, "%s\\%s", domain_name, name);
239         }
240         if (!full_name) {
241                 DEBUG(0, ("talloc_asprintf failed!\n"));
242                 return NT_STATUS_NO_MEMORY;
243         }
244
245         DEBUG(3, ("msrpc_name_to_sid: name=%s\n", full_name));
246
247         name_map_status = normalize_name_unmap(mem_ctx, full_name,
248                                                &mapped_name);
249
250         /* Reset the full_name pointer if we mapped anything */
251
252         if (NT_STATUS_IS_OK(name_map_status) ||
253             NT_STATUS_EQUAL(name_map_status, NT_STATUS_FILE_RENAMED))
254         {
255                 full_name = mapped_name;
256         }
257
258         DEBUG(3,("name_to_sid [rpc] %s for domain %s\n",
259                  full_name?full_name:"", domain_name ));
260
261         names[0] = full_name;
262
263         result = winbindd_lookup_names(mem_ctx, domain, 1,
264                                        names, &domains,
265                                        &sids, &types);
266         if (!NT_STATUS_IS_OK(result))
267                 return result;
268
269         /* Return rid and type if lookup successful */
270
271         sid_copy(sid, &sids[0]);
272         *type = types[0];
273
274         return NT_STATUS_OK;
275 }
276
277 /*
278   convert a domain SID to a user or group name
279 */
280 static NTSTATUS msrpc_sid_to_name(struct winbindd_domain *domain,
281                                   TALLOC_CTX *mem_ctx,
282                                   const struct dom_sid *sid,
283                                   char **domain_name,
284                                   char **name,
285                                   enum lsa_SidType *type)
286 {
287         char **domains;
288         char **names;
289         enum lsa_SidType *types = NULL;
290         NTSTATUS result;
291         NTSTATUS name_map_status = NT_STATUS_UNSUCCESSFUL;
292         char *mapped_name = NULL;
293         struct dom_sid_buf buf;
294
295         DEBUG(3, ("msrpc_sid_to_name: %s for domain %s\n",
296                   dom_sid_str_buf(sid, &buf),
297                   domain->name));
298
299         result = winbindd_lookup_sids(mem_ctx,
300                                       domain,
301                                       1,
302                                       sid,
303                                       &domains,
304                                       &names,
305                                       &types);
306         if (!NT_STATUS_IS_OK(result)) {
307                 DEBUG(2,("msrpc_sid_to_name: failed to lookup sids: %s\n",
308                         nt_errstr(result)));
309                 return result;
310         }
311
312
313         *type = (enum lsa_SidType)types[0];
314         *domain_name = domains[0];
315         *name = names[0];
316
317         DEBUG(5,("Mapped sid to [%s]\\[%s]\n", domains[0], *name));
318
319         name_map_status = normalize_name_map(mem_ctx, domain->name, *name,
320                                              &mapped_name);
321         if (NT_STATUS_IS_OK(name_map_status) ||
322             NT_STATUS_EQUAL(name_map_status, NT_STATUS_FILE_RENAMED))
323         {
324                 *name = mapped_name;
325                 DEBUG(5,("returning mapped name -- %s\n", *name));
326         }
327
328         return NT_STATUS_OK;
329 }
330
331 static NTSTATUS msrpc_rids_to_names(struct winbindd_domain *domain,
332                                     TALLOC_CTX *mem_ctx,
333                                     const struct dom_sid *sid,
334                                     uint32_t *rids,
335                                     size_t num_rids,
336                                     char **domain_name,
337                                     char ***names,
338                                     enum lsa_SidType **types)
339 {
340         char **domains;
341         NTSTATUS result;
342         struct dom_sid *sids;
343         size_t i;
344         char **ret_names;
345
346         DEBUG(3, ("msrpc_rids_to_names: domain %s\n", domain->name ));
347
348         if (num_rids) {
349                 sids = talloc_array(mem_ctx, struct dom_sid, num_rids);
350                 if (sids == NULL) {
351                         return NT_STATUS_NO_MEMORY;
352                 }
353         } else {
354                 sids = NULL;
355         }
356
357         for (i=0; i<num_rids; i++) {
358                 if (!sid_compose(&sids[i], sid, rids[i])) {
359                         return NT_STATUS_INTERNAL_ERROR;
360                 }
361         }
362
363         result = winbindd_lookup_sids(mem_ctx,
364                                       domain,
365                                       num_rids,
366                                       sids,
367                                       &domains,
368                                       names,
369                                       types);
370
371         if (!NT_STATUS_IS_OK(result) &&
372             !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED)) {
373                 return result;
374         }
375
376         ret_names = *names;
377         for (i=0; i<num_rids; i++) {
378                 NTSTATUS name_map_status = NT_STATUS_UNSUCCESSFUL;
379                 char *mapped_name = NULL;
380
381                 if ((*types)[i] != SID_NAME_UNKNOWN) {
382                         name_map_status = normalize_name_map(mem_ctx,
383                                                              domain->name,
384                                                              ret_names[i],
385                                                              &mapped_name);
386                         if (NT_STATUS_IS_OK(name_map_status) ||
387                             NT_STATUS_EQUAL(name_map_status, NT_STATUS_FILE_RENAMED))
388                         {
389                                 ret_names[i] = mapped_name;
390                         }
391
392                         *domain_name = domains[i];
393                 }
394         }
395
396         return result;
397 }
398
399 /* Lookup groups a user is a member of.  I wish Unix had a call like this! */
400 static NTSTATUS msrpc_lookup_usergroups(struct winbindd_domain *domain,
401                                         TALLOC_CTX *mem_ctx,
402                                         const struct dom_sid *user_sid,
403                                         uint32_t *pnum_groups,
404                                         struct dom_sid **puser_grpsids)
405 {
406         struct rpc_pipe_client *samr_pipe;
407         struct policy_handle dom_pol;
408         struct dom_sid *user_grpsids = NULL;
409         struct dom_sid_buf buf;
410         uint32_t num_groups = 0;
411         TALLOC_CTX *tmp_ctx;
412         NTSTATUS status;
413
414         DEBUG(3,("msrpc_lookup_usergroups sid=%s\n",
415                  dom_sid_str_buf(user_sid, &buf)));
416
417         *pnum_groups = 0;
418
419         tmp_ctx = talloc_stackframe();
420         if (tmp_ctx == NULL) {
421                 return NT_STATUS_NO_MEMORY;
422         }
423
424         /* Check if we have a cached user_info_3 */
425         status = lookup_usergroups_cached(tmp_ctx,
426                                           user_sid,
427                                           &num_groups,
428                                           &user_grpsids);
429         if (NT_STATUS_IS_OK(status)) {
430                 goto cached;
431         }
432
433         if ( !winbindd_can_contact_domain( domain ) ) {
434                 DEBUG(10,("lookup_usergroups: No incoming trust for domain %s\n",
435                           domain->name));
436
437                 /* Tell the cache manager not to remember this one */
438                 status = NT_STATUS_SYNCHRONIZATION_REQUIRED;
439                 goto done;
440         }
441
442         /* no cache; hit the wire */
443         status = cm_connect_sam(domain, tmp_ctx, false, &samr_pipe, &dom_pol);
444         if (!NT_STATUS_IS_OK(status)) {
445                 goto done;
446         }
447
448         status = rpc_lookup_usergroups(tmp_ctx,
449                                        samr_pipe,
450                                        &dom_pol,
451                                        &domain->sid,
452                                        user_sid,
453                                        &num_groups,
454                                        &user_grpsids);
455         if (!NT_STATUS_IS_OK(status)) {
456                 goto done;
457         }
458
459 cached:
460         *pnum_groups = num_groups;
461
462         if (puser_grpsids) {
463                 *puser_grpsids = talloc_move(mem_ctx, &user_grpsids);
464         }
465
466 done:
467         TALLOC_FREE(tmp_ctx);
468         return status;
469         return NT_STATUS_OK;
470 }
471
472 #define MAX_SAM_ENTRIES_W2K 0x400 /* 1024 */
473
474 static NTSTATUS msrpc_lookup_useraliases(struct winbindd_domain *domain,
475                                          TALLOC_CTX *mem_ctx,
476                                          uint32_t num_sids, const struct dom_sid *sids,
477                                          uint32_t *pnum_aliases,
478                                          uint32_t **palias_rids)
479 {
480         struct rpc_pipe_client *samr_pipe;
481         struct policy_handle dom_pol;
482         uint32_t num_aliases = 0;
483         uint32_t *alias_rids = NULL;
484         TALLOC_CTX *tmp_ctx;
485         NTSTATUS status;
486
487         DEBUG(3,("msrpc_lookup_useraliases\n"));
488
489         if (pnum_aliases) {
490                 *pnum_aliases = 0;
491         }
492
493         tmp_ctx = talloc_stackframe();
494         if (tmp_ctx == NULL) {
495                 return NT_STATUS_NO_MEMORY;
496         }
497
498         if (!winbindd_can_contact_domain(domain)) {
499                 DEBUG(10,("msrpc_lookup_useraliases: No incoming trust for domain %s\n",
500                           domain->name));
501                 /* Tell the cache manager not to remember this one */
502                 status = NT_STATUS_SYNCHRONIZATION_REQUIRED;
503                 goto done;
504         }
505
506         status = cm_connect_sam(domain, tmp_ctx, false, &samr_pipe, &dom_pol);
507         if (!NT_STATUS_IS_OK(status)) {
508                 goto done;
509         }
510
511         status = rpc_lookup_useraliases(tmp_ctx,
512                                         samr_pipe,
513                                         &dom_pol,
514                                         num_sids,
515                                         sids,
516                                         &num_aliases,
517                                         &alias_rids);
518         if (!NT_STATUS_IS_OK(status)) {
519                 goto done;
520         }
521
522         if (pnum_aliases) {
523                 *pnum_aliases = num_aliases;
524         }
525
526         if (palias_rids) {
527                 *palias_rids = talloc_move(mem_ctx, &alias_rids);
528         }
529
530 done:
531         TALLOC_FREE(tmp_ctx);
532         return status;
533 }
534
535
536 /* Lookup group membership given a rid.   */
537 static NTSTATUS msrpc_lookup_groupmem(struct winbindd_domain *domain,
538                                       TALLOC_CTX *mem_ctx,
539                                       const struct dom_sid *group_sid,
540                                       enum lsa_SidType type,
541                                       uint32_t *num_names,
542                                       struct dom_sid **sid_mem,
543                                       char ***names,
544                                       uint32_t **name_types)
545 {
546         NTSTATUS status, result;
547         uint32_t i, total_names = 0;
548         struct policy_handle dom_pol, group_pol;
549         uint32_t des_access = SEC_FLAG_MAXIMUM_ALLOWED;
550         uint32_t *rid_mem = NULL;
551         uint32_t group_rid;
552         unsigned int j, r;
553         struct rpc_pipe_client *cli;
554         unsigned int orig_timeout;
555         struct samr_RidAttrArray *rids = NULL;
556         struct dcerpc_binding_handle *b;
557         struct dom_sid_buf buf;
558
559         DEBUG(3,("msrpc_lookup_groupmem: %s sid=%s\n", domain->name,
560                  dom_sid_str_buf(group_sid, &buf)));
561
562         if ( !winbindd_can_contact_domain( domain ) ) {
563                 DEBUG(10,("lookup_groupmem: No incoming trust for domain %s\n",
564                           domain->name));
565                 return NT_STATUS_OK;
566         }
567
568         if (!sid_peek_check_rid(&domain->sid, group_sid, &group_rid))
569                 return NT_STATUS_UNSUCCESSFUL;
570
571         *num_names = 0;
572
573         result = cm_connect_sam(domain, mem_ctx, false, &cli, &dom_pol);
574         if (!NT_STATUS_IS_OK(result))
575                 return result;
576
577         b = cli->binding_handle;
578
579         status = dcerpc_samr_OpenGroup(b, mem_ctx,
580                                        &dom_pol,
581                                        des_access,
582                                        group_rid,
583                                        &group_pol,
584                                        &result);
585         if (any_nt_status_not_ok(status, result, &status)) {
586                 return status;
587         }
588
589         /* Step #1: Get a list of user rids that are the members of the
590            group. */
591
592         /* This call can take a long time - allow the server to time out.
593            35 seconds should do it. */
594
595         orig_timeout = rpccli_set_timeout(cli, 35000);
596
597         status = dcerpc_samr_QueryGroupMember(b, mem_ctx,
598                                               &group_pol,
599                                               &rids,
600                                               &result);
601
602         /* And restore our original timeout. */
603         rpccli_set_timeout(cli, orig_timeout);
604
605         {
606                 NTSTATUS _result;
607                 dcerpc_samr_Close(b, mem_ctx, &group_pol, &_result);
608         }
609
610         if (any_nt_status_not_ok(status, result, &status)) {
611                 return status;
612         }
613
614         if (!rids || !rids->count) {
615                 names = NULL;
616                 name_types = NULL;
617                 sid_mem = NULL;
618                 return NT_STATUS_OK;
619         }
620
621         *num_names = rids->count;
622         rid_mem = rids->rids;
623
624         /* Step #2: Convert list of rids into list of usernames.  Do this
625            in bunches of ~1000 to avoid crashing NT4.  It looks like there
626            is a buffer overflow or something like that lurking around
627            somewhere. */
628
629 #define MAX_LOOKUP_RIDS 900
630
631         *names = talloc_zero_array(mem_ctx, char *, *num_names);
632         *name_types = talloc_zero_array(mem_ctx, uint32_t, *num_names);
633         *sid_mem = talloc_zero_array(mem_ctx, struct dom_sid, *num_names);
634
635         for (j=0;j<(*num_names);j++)
636                 sid_compose(&(*sid_mem)[j], &domain->sid, rid_mem[j]);
637
638         if (*num_names>0 && (!*names || !*name_types))
639                 return NT_STATUS_NO_MEMORY;
640
641         for (i = 0; i < *num_names; i += MAX_LOOKUP_RIDS) {
642                 int num_lookup_rids = MIN(*num_names - i, MAX_LOOKUP_RIDS);
643                 struct lsa_Strings tmp_names;
644                 struct samr_Ids tmp_types;
645
646                 /* Lookup a chunk of rids */
647
648                 status = dcerpc_samr_LookupRids(b, mem_ctx,
649                                                 &dom_pol,
650                                                 num_lookup_rids,
651                                                 &rid_mem[i],
652                                                 &tmp_names,
653                                                 &tmp_types,
654                                                 &result);
655                 if (!NT_STATUS_IS_OK(status)) {
656                         return status;
657                 }
658
659                 /* see if we have a real error (and yes the
660                    STATUS_SOME_UNMAPPED is the one returned from 2k) */
661
662                 if (!NT_STATUS_IS_OK(result) &&
663                     !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED))
664                         return result;
665
666                 /* Copy result into array.  The talloc system will take
667                    care of freeing the temporary arrays later on. */
668
669                 if (tmp_names.count != num_lookup_rids) {
670                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
671                 }
672                 if (tmp_types.count != num_lookup_rids) {
673                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
674                 }
675
676                 for (r=0; r<tmp_names.count; r++) {
677                         if (tmp_types.ids[r] == SID_NAME_UNKNOWN) {
678                                 continue;
679                         }
680                         if (total_names >= *num_names) {
681                                 break;
682                         }
683                         (*names)[total_names] = fill_domain_username_talloc(
684                                 mem_ctx, domain->name,
685                                 tmp_names.names[r].string, true);
686                         (*name_types)[total_names] = tmp_types.ids[r];
687                         total_names += 1;
688                 }
689         }
690
691         *num_names = total_names;
692
693         return NT_STATUS_OK;
694 }
695
696 #ifdef HAVE_LDAP
697
698 #include "ads.h"
699
700 static int get_ldap_seq(const char *server, struct sockaddr_storage *ss, int port, uint32_t *seq)
701 {
702         int ret = -1;
703         struct timeval to;
704         const char *attrs[] = {"highestCommittedUSN", NULL};
705         LDAPMessage *res = NULL;
706         char **values = NULL;
707         LDAP *ldp = NULL;
708
709         *seq = DOM_SEQUENCE_NONE;
710
711         /*
712          * Parameterised (5) second timeout on open. This is needed as the
713          * search timeout doesn't seem to apply to doing an open as well. JRA.
714          */
715
716         ldp = ldap_open_with_timeout(server, ss, port, lp_ldap_timeout());
717         if (ldp == NULL)
718                 return -1;
719
720         /* Timeout if no response within 20 seconds. */
721         to.tv_sec = 10;
722         to.tv_usec = 0;
723
724         if (ldap_search_st(ldp, "", LDAP_SCOPE_BASE, "(objectclass=*)",
725                            discard_const_p(char *, attrs), 0, &to, &res))
726                 goto done;
727
728         if (ldap_count_entries(ldp, res) != 1)
729                 goto done;
730
731         values = ldap_get_values(ldp, res, "highestCommittedUSN");
732         if (!values || !values[0])
733                 goto done;
734
735         *seq = atoi(values[0]);
736         ret = 0;
737
738   done:
739
740         if (values)
741                 ldap_value_free(values);
742         if (res)
743                 ldap_msgfree(res);
744         if (ldp)
745                 ldap_unbind(ldp);
746         return ret;
747 }
748
749 /**********************************************************************
750  Get the sequence number for a Windows AD native mode domain using
751  LDAP queries.
752 **********************************************************************/
753
754 static int get_ldap_sequence_number(struct winbindd_domain *domain, uint32_t *seq)
755 {
756         int ret = -1;
757         char addr[INET6_ADDRSTRLEN];
758
759         print_sockaddr(addr, sizeof(addr), &domain->dcaddr);
760         if ((ret = get_ldap_seq(addr, &domain->dcaddr, LDAP_PORT, seq)) == 0) {
761                 DEBUG(3, ("get_ldap_sequence_number: Retrieved sequence "
762                           "number for Domain (%s) from DC (%s)\n",
763                         domain->name, addr));
764         }
765         return ret;
766 }
767
768 #endif /* HAVE_LDAP */
769
770 /* find the sequence number for a domain */
771 static NTSTATUS msrpc_sequence_number(struct winbindd_domain *domain,
772                                       uint32_t *pseq)
773 {
774         struct rpc_pipe_client *samr_pipe;
775         struct policy_handle dom_pol;
776         uint32_t seq = DOM_SEQUENCE_NONE;
777         TALLOC_CTX *tmp_ctx;
778         NTSTATUS status;
779
780         DEBUG(3, ("msrpc_sequence_number: fetch sequence_number for %s\n", domain->name));
781
782         if (pseq) {
783                 *pseq = DOM_SEQUENCE_NONE;
784         }
785
786         tmp_ctx = talloc_stackframe();
787         if (tmp_ctx == NULL) {
788                 return NT_STATUS_NO_MEMORY;
789         }
790
791         if ( !winbindd_can_contact_domain( domain ) ) {
792                 DEBUG(10,("sequence_number: No incoming trust for domain %s\n",
793                           domain->name));
794                 if (pseq) {
795                         *pseq = time(NULL);
796                 }
797                 status = NT_STATUS_OK;
798                 goto done;
799         }
800
801 #ifdef HAVE_LDAP
802         if (domain->active_directory) {
803                 int rc;
804
805                 DEBUG(8,("using get_ldap_seq() to retrieve the "
806                          "sequence number\n"));
807
808                 rc =  get_ldap_sequence_number(domain, &seq);
809                 if (rc == 0) {
810                         DEBUG(10,("domain_sequence_number: LDAP for "
811                                   "domain %s is %u\n",
812                                   domain->name, seq));
813
814                         if (pseq) {
815                                 *pseq = seq;
816                         }
817
818                         status = NT_STATUS_OK;
819                         goto done;
820                 }
821
822                 DEBUG(10,("domain_sequence_number: failed to get LDAP "
823                           "sequence number for domain %s\n",
824                           domain->name ));
825         }
826 #endif /* HAVE_LDAP */
827
828         status = cm_connect_sam(domain, tmp_ctx, false, &samr_pipe, &dom_pol);
829         if (!NT_STATUS_IS_OK(status)) {
830                 goto done;
831         }
832
833         status = rpc_sequence_number(tmp_ctx,
834                                      samr_pipe,
835                                      &dom_pol,
836                                      domain->name,
837                                      &seq);
838         if (!NT_STATUS_IS_OK(status)) {
839                 goto done;
840         }
841
842         if (pseq) {
843                 *pseq = seq;
844         }
845
846 done:
847         TALLOC_FREE(tmp_ctx);
848         return status;
849 }
850
851 /* get a list of trusted domains */
852 static NTSTATUS msrpc_trusted_domains(struct winbindd_domain *domain,
853                                       TALLOC_CTX *mem_ctx,
854                                       struct netr_DomainTrustList *ptrust_list)
855 {
856         struct rpc_pipe_client *lsa_pipe;
857         struct policy_handle lsa_policy;
858         struct netr_DomainTrust *trusts = NULL;
859         uint32_t num_trusts = 0;
860         TALLOC_CTX *tmp_ctx;
861         NTSTATUS status;
862
863         DEBUG(3,("msrpc_trusted_domains\n"));
864
865         if (ptrust_list) {
866                 ZERO_STRUCTP(ptrust_list);
867         }
868
869         tmp_ctx = talloc_stackframe();
870         if (tmp_ctx == NULL) {
871                 return NT_STATUS_NO_MEMORY;
872         }
873
874         status = cm_connect_lsa(domain, tmp_ctx, &lsa_pipe, &lsa_policy);
875         if (!NT_STATUS_IS_OK(status)) {
876                 goto done;
877         }
878
879         status = rpc_trusted_domains(tmp_ctx,
880                                      lsa_pipe,
881                                      &lsa_policy,
882                                      &num_trusts,
883                                      &trusts);
884         if (!NT_STATUS_IS_OK(status)) {
885                 goto done;
886         }
887
888         if (ptrust_list) {
889                 ptrust_list->count = num_trusts;
890                 ptrust_list->array = talloc_move(mem_ctx, &trusts);
891         }
892
893 done:
894         TALLOC_FREE(tmp_ctx);
895         return status;
896 }
897
898 /* find the lockout policy for a domain */
899 static NTSTATUS msrpc_lockout_policy(struct winbindd_domain *domain,
900                                      TALLOC_CTX *mem_ctx,
901                                      struct samr_DomInfo12 *lockout_policy)
902 {
903         NTSTATUS status, result;
904         struct rpc_pipe_client *cli;
905         struct policy_handle dom_pol;
906         union samr_DomainInfo *info = NULL;
907         struct dcerpc_binding_handle *b;
908
909         DEBUG(3, ("msrpc_lockout_policy: fetch lockout policy for %s\n", domain->name));
910
911         if ( !winbindd_can_contact_domain( domain ) ) {
912                 DEBUG(10,("msrpc_lockout_policy: No incoming trust for domain %s\n",
913                           domain->name));
914                 return NT_STATUS_NOT_SUPPORTED;
915         }
916
917         status = cm_connect_sam(domain, mem_ctx, false, &cli, &dom_pol);
918         if (!NT_STATUS_IS_OK(status)) {
919                 goto done;
920         }
921
922         b = cli->binding_handle;
923
924         status = dcerpc_samr_QueryDomainInfo(b, mem_ctx,
925                                              &dom_pol,
926                                              DomainLockoutInformation,
927                                              &info,
928                                              &result);
929         if (any_nt_status_not_ok(status, result, &status)) {
930                 return status;
931         }
932
933         *lockout_policy = info->info12;
934
935         DEBUG(10,("msrpc_lockout_policy: lockout_threshold %d\n",
936                 info->info12.lockout_threshold));
937
938   done:
939
940         return status;
941 }
942
943 /* find the password policy for a domain */
944 static NTSTATUS msrpc_password_policy(struct winbindd_domain *domain,
945                                       TALLOC_CTX *mem_ctx,
946                                       struct samr_DomInfo1 *password_policy)
947 {
948         NTSTATUS status, result;
949         struct rpc_pipe_client *cli;
950         struct policy_handle dom_pol;
951         union samr_DomainInfo *info = NULL;
952         struct dcerpc_binding_handle *b;
953
954         DEBUG(3, ("msrpc_password_policy: fetch password policy for %s\n",
955                   domain->name));
956
957         if ( !winbindd_can_contact_domain( domain ) ) {
958                 DEBUG(10,("msrpc_password_policy: No incoming trust for domain %s\n",
959                           domain->name));
960                 return NT_STATUS_NOT_SUPPORTED;
961         }
962
963         status = cm_connect_sam(domain, mem_ctx, false, &cli, &dom_pol);
964         if (!NT_STATUS_IS_OK(status)) {
965                 goto done;
966         }
967
968         b = cli->binding_handle;
969
970         status = dcerpc_samr_QueryDomainInfo(b, mem_ctx,
971                                              &dom_pol,
972                                              DomainPasswordInformation,
973                                              &info,
974                                              &result);
975         if (!NT_STATUS_IS_OK(status)) {
976                 goto done;
977         }
978         if (!NT_STATUS_IS_OK(result)) {
979                 goto done;
980         }
981
982         *password_policy = info->info1;
983
984         DEBUG(10,("msrpc_password_policy: min_length_password %d\n",
985                 info->info1.min_password_length));
986
987   done:
988
989         return status;
990 }
991
992 static enum lsa_LookupNamesLevel winbindd_lookup_level(
993         struct winbindd_domain *domain)
994 {
995         enum lsa_LookupNamesLevel level = LSA_LOOKUP_NAMES_DOMAINS_ONLY;
996
997         if (domain->internal) {
998                 level = LSA_LOOKUP_NAMES_ALL;
999         } else if (domain->secure_channel_type == SEC_CHAN_DNS_DOMAIN) {
1000                 if (domain->domain_flags & NETR_TRUST_FLAG_IN_FOREST) {
1001                         /*
1002                          * TODO:
1003                          *
1004                          * Depending on what we want to resolve. We need to use:
1005                          * 1. LsapLookupXForestReferral(5)/LSA_LOOKUP_NAMES_FOREST_TRUSTS_ONLY
1006                          *    if we want to pass the request into the direction of the forest
1007                          *    root domain. The forest root domain uses
1008                          *    LsapLookupXForestResolve(6)/LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY2
1009                          *    when passing the request to trusted forests.
1010                          * 2. LsapLookupGC(4)/LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY
1011                          *    if we're not a GC and want to resolve a name within our own forest.
1012                          *
1013                          * As we don't support more than one domain in our own forest
1014                          * and always try to be a GC for now, we just set
1015                          * LSA_LOOKUP_NAMES_FOREST_TRUSTS_ONLY.
1016                          */
1017                         level = LSA_LOOKUP_NAMES_FOREST_TRUSTS_ONLY;
1018                 } else if (domain->domain_trust_attribs & LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE) {
1019                         /*
1020                          * This is LsapLookupXForestResolve(6)/LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY2
1021                          */
1022                         level = LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY2;
1023                 } else {
1024                         /*
1025                          * This is LsapLookupTDL(3)/LSA_LOOKUP_NAMES_PRIMARY_DOMAIN_ONLY
1026                          */
1027                         level = LSA_LOOKUP_NAMES_PRIMARY_DOMAIN_ONLY;
1028                 }
1029         } else if (domain->secure_channel_type == SEC_CHAN_DOMAIN) {
1030                 /*
1031                  * This is LsapLookupTDL(3)/LSA_LOOKUP_NAMES_PRIMARY_DOMAIN_ONLY
1032                  */
1033                 level = LSA_LOOKUP_NAMES_PRIMARY_DOMAIN_ONLY;
1034         } else if (domain->rodc) {
1035                 level = LSA_LOOKUP_NAMES_RODC_REFERRAL_TO_FULL_DC;
1036         } else {
1037                 /*
1038                  * This is LsapLookupPDC(2)/LSA_LOOKUP_NAMES_DOMAINS_ONLY
1039                  */
1040                 level = LSA_LOOKUP_NAMES_DOMAINS_ONLY;
1041         }
1042
1043         return level;
1044 }
1045
1046 NTSTATUS winbindd_lookup_sids(TALLOC_CTX *mem_ctx,
1047                               struct winbindd_domain *domain,
1048                               uint32_t num_sids,
1049                               const struct dom_sid *sids,
1050                               char ***domains,
1051                               char ***names,
1052                               enum lsa_SidType **types)
1053 {
1054         NTSTATUS status;
1055         NTSTATUS result;
1056         struct rpc_pipe_client *cli = NULL;
1057         struct dcerpc_binding_handle *b = NULL;
1058         struct policy_handle lsa_policy;
1059         unsigned int orig_timeout;
1060         bool use_lookupsids3 = false;
1061         bool retried = false;
1062         enum lsa_LookupNamesLevel level = LSA_LOOKUP_NAMES_ALL;
1063
1064  connect:
1065         status = cm_connect_lsat(domain, mem_ctx, &cli, &lsa_policy);
1066         if (!NT_STATUS_IS_OK(status)) {
1067                 return status;
1068         }
1069
1070         b = cli->binding_handle;
1071
1072         if (cli->transport->transport == NCACN_IP_TCP) {
1073                 use_lookupsids3 = true;
1074         }
1075
1076         level = winbindd_lookup_level(domain);
1077
1078         /*
1079          * This call can take a long time
1080          * allow the server to time out.
1081          * 35 seconds should do it.
1082          */
1083         orig_timeout = dcerpc_binding_handle_set_timeout(b, 35000);
1084
1085         status = dcerpc_lsa_lookup_sids_generic(b,
1086                                                 mem_ctx,
1087                                                 &lsa_policy,
1088                                                 num_sids,
1089                                                 sids,
1090                                                 level,
1091                                                 domains,
1092                                                 names,
1093                                                 types,
1094                                                 use_lookupsids3,
1095                                                 &result);
1096
1097         /* And restore our original timeout. */
1098         dcerpc_binding_handle_set_timeout(b, orig_timeout);
1099
1100         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
1101             NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
1102             NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
1103                 /*
1104                  * This can happen if the schannel key is not
1105                  * valid anymore, we need to invalidate the
1106                  * all connections to the dc and reestablish
1107                  * a netlogon connection first.
1108                  */
1109                 invalidate_cm_connection(domain);
1110                 domain->can_do_ncacn_ip_tcp = domain->active_directory;
1111                 if (!retried) {
1112                         retried = true;
1113                         goto connect;
1114                 }
1115                 status = NT_STATUS_ACCESS_DENIED;
1116         }
1117
1118         if (any_nt_status_not_ok(status, result, &status)) {
1119                 return status;
1120         }
1121
1122         return NT_STATUS_OK;
1123 }
1124
1125 static NTSTATUS winbindd_lookup_names(TALLOC_CTX *mem_ctx,
1126                                       struct winbindd_domain *domain,
1127                                       uint32_t num_names,
1128                                       const char **names,
1129                                       const char ***domains,
1130                                       struct dom_sid **sids,
1131                                       enum lsa_SidType **types)
1132 {
1133         NTSTATUS status;
1134         NTSTATUS result;
1135         struct rpc_pipe_client *cli = NULL;
1136         struct dcerpc_binding_handle *b = NULL;
1137         struct policy_handle lsa_policy;
1138         unsigned int orig_timeout = 0;
1139         bool use_lookupnames4 = false;
1140         bool retried = false;
1141         enum lsa_LookupNamesLevel level = LSA_LOOKUP_NAMES_ALL;
1142
1143  connect:
1144         status = cm_connect_lsat(domain, mem_ctx, &cli, &lsa_policy);
1145         if (!NT_STATUS_IS_OK(status)) {
1146                 return status;
1147         }
1148
1149         b = cli->binding_handle;
1150
1151         if (cli->transport->transport == NCACN_IP_TCP) {
1152                 use_lookupnames4 = true;
1153         }
1154
1155         level = winbindd_lookup_level(domain);
1156
1157         /*
1158          * This call can take a long time
1159          * allow the server to time out.
1160          * 35 seconds should do it.
1161          */
1162         orig_timeout = dcerpc_binding_handle_set_timeout(b, 35000);
1163
1164         status = dcerpc_lsa_lookup_names_generic(b,
1165                                                  mem_ctx,
1166                                                  &lsa_policy,
1167                                                  num_names,
1168                                                  (const char **) names,
1169                                                  domains,
1170                                                  level,
1171                                                  sids,
1172                                                  types,
1173                                                  use_lookupnames4,
1174                                                  &result);
1175
1176         /* And restore our original timeout. */
1177         dcerpc_binding_handle_set_timeout(b, orig_timeout);
1178
1179         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
1180             NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
1181             NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
1182                 /*
1183                  * This can happen if the schannel key is not
1184                  * valid anymore, we need to invalidate the
1185                  * all connections to the dc and reestablish
1186                  * a netlogon connection first.
1187                  */
1188                 invalidate_cm_connection(domain);
1189                 if (!retried) {
1190                         retried = true;
1191                         goto connect;
1192                 }
1193                 status = NT_STATUS_ACCESS_DENIED;
1194         }
1195
1196         if (any_nt_status_not_ok(status, result, &status)) {
1197                 return status;
1198         }
1199
1200         return NT_STATUS_OK;
1201 }
1202
1203 /* the rpc backend methods are exposed via this structure */
1204 struct winbindd_methods msrpc_methods = {
1205         False,
1206         msrpc_query_user_list,
1207         msrpc_enum_dom_groups,
1208         msrpc_enum_local_groups,
1209         msrpc_name_to_sid,
1210         msrpc_sid_to_name,
1211         msrpc_rids_to_names,
1212         msrpc_lookup_usergroups,
1213         msrpc_lookup_useraliases,
1214         msrpc_lookup_groupmem,
1215         msrpc_sequence_number,
1216         msrpc_lockout_policy,
1217         msrpc_password_policy,
1218         msrpc_trusted_domains,
1219 };