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