r14363: Remove credentials.h from the global includes.
[kai/samba-autobuild/.git] / source4 / librpc / rpc / dcerpc_util.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    dcerpc utility functions
5
6    Copyright (C) Andrew Tridgell 2003
7    Copyright (C) Jelmer Vernooij 2004
8    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
9    Copyright (C) Rafal Szczesniak 2006
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 2 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, write to the Free Software
23    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 */
25
26 #include "includes.h"
27 #include "lib/events/events.h"
28 #include "libcli/composite/composite.h"
29 #include "librpc/gen_ndr/ndr_epmapper.h"
30 #include "librpc/gen_ndr/ndr_dcerpc.h"
31 #include "librpc/gen_ndr/ndr_misc.h"
32 #include "auth/credentials/credentials.h"
33
34 /*
35   find a dcerpc call on an interface by name
36 */
37 const struct dcerpc_interface_call *dcerpc_iface_find_call(const struct dcerpc_interface_table *iface,
38                                                            const char *name)
39 {
40         int i;
41         for (i=0;i<iface->num_calls;i++) {
42                 if (strcmp(iface->calls[i].name, name) == 0) {
43                         return &iface->calls[i];
44                 }
45         }
46         return NULL;
47 }
48
49 /* 
50    push a ncacn_packet into a blob, potentially with auth info
51 */
52 NTSTATUS ncacn_push_auth(DATA_BLOB *blob, TALLOC_CTX *mem_ctx, 
53                           struct ncacn_packet *pkt,
54                           struct dcerpc_auth *auth_info)
55 {
56         NTSTATUS status;
57         struct ndr_push *ndr;
58
59         ndr = ndr_push_init_ctx(mem_ctx);
60         if (!ndr) {
61                 return NT_STATUS_NO_MEMORY;
62         }
63
64         if (!(pkt->drep[0] & DCERPC_DREP_LE)) {
65                 ndr->flags |= LIBNDR_FLAG_BIGENDIAN;
66         }
67
68         if (pkt->pfc_flags & DCERPC_PFC_FLAG_ORPC) {
69                 ndr->flags |= LIBNDR_FLAG_OBJECT_PRESENT;
70         }
71
72         if (auth_info) {
73                 pkt->auth_length = auth_info->credentials.length;
74         } else {
75                 pkt->auth_length = 0;
76         }
77
78         status = ndr_push_ncacn_packet(ndr, NDR_SCALARS|NDR_BUFFERS, pkt);
79         if (!NT_STATUS_IS_OK(status)) {
80                 return status;
81         }
82
83         if (auth_info) {
84                 status = ndr_push_dcerpc_auth(ndr, NDR_SCALARS|NDR_BUFFERS, auth_info);
85         }
86
87         *blob = ndr_push_blob(ndr);
88
89         /* fill in the frag length */
90         dcerpc_set_frag_length(blob, blob->length);
91
92         return NT_STATUS_OK;
93 }
94
95 #define MAX_PROTSEQ             10
96
97 static const struct {
98         const char *name;
99         enum dcerpc_transport_t transport;
100         int num_protocols;
101         enum epm_protocol protseq[MAX_PROTSEQ];
102 } transports[] = {
103         { "ncacn_np",     NCACN_NP, 3, 
104                 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB, EPM_PROTOCOL_NETBIOS }},
105         { "ncacn_ip_tcp", NCACN_IP_TCP, 3, 
106                 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP, EPM_PROTOCOL_IP } }, 
107         { "ncacn_http", NCACN_HTTP, 3, 
108                 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP, EPM_PROTOCOL_IP } }, 
109         { "ncadg_ip_udp", NCACN_IP_UDP, 3, 
110                 { EPM_PROTOCOL_NCADG, EPM_PROTOCOL_UDP, EPM_PROTOCOL_IP } },
111         { "ncalrpc", NCALRPC, 2, 
112                 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE } },
113         { "ncacn_unix_stream", NCACN_UNIX_STREAM, 2, 
114                 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_UNIX_DS } },
115         { "ncadg_unix_dgram", NCADG_UNIX_DGRAM, 2, 
116                 { EPM_PROTOCOL_NCADG, EPM_PROTOCOL_UNIX_DS } },
117         { "ncacn_at_dsp", NCACN_AT_DSP, 3, 
118                 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_APPLETALK, EPM_PROTOCOL_DSP } },
119         { "ncadg_at_ddp", NCADG_AT_DDP, 3, 
120                 { EPM_PROTOCOL_NCADG, EPM_PROTOCOL_APPLETALK, EPM_PROTOCOL_DDP } },
121         { "ncacn_vns_ssp", NCACN_VNS_SPP, 3, 
122                 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_STREETTALK, EPM_PROTOCOL_VINES_SPP } },
123         { "ncacn_vns_ipc", NCACN_VNS_IPC, 3, 
124                 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_STREETTALK, EPM_PROTOCOL_VINES_IPC }, },
125         { "ncadg_ipx", NCADG_IPX, 2,
126                 { EPM_PROTOCOL_NCADG, EPM_PROTOCOL_IPX },
127         },
128         { "ncacn_spx", NCACN_SPX, 3,
129                 /* I guess some MS programmer confused the identifier for 
130                  * EPM_PROTOCOL_UUID (0x0D or 13) with the one for 
131                  * EPM_PROTOCOL_SPX (0x13) here. -- jelmer*/
132                 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_UUID },
133         },
134 };
135
136 static const struct {
137         const char *name;
138         uint32_t flag;
139 } ncacn_options[] = {
140         {"sign", DCERPC_SIGN},
141         {"seal", DCERPC_SEAL},
142         {"connect", DCERPC_CONNECT},
143         {"spnego", DCERPC_AUTH_SPNEGO},
144         {"krb5", DCERPC_AUTH_KRB5},
145         {"validate", DCERPC_DEBUG_VALIDATE_BOTH},
146         {"print", DCERPC_DEBUG_PRINT_BOTH},
147         {"padcheck", DCERPC_DEBUG_PAD_CHECK},
148         {"bigendian", DCERPC_PUSH_BIGENDIAN},
149         {"smb2", DCERPC_SMB2}
150 };
151
152 const char *epm_floor_string(TALLOC_CTX *mem_ctx, struct epm_floor *epm_floor)
153 {
154         struct GUID uuid;
155         uint16_t if_version;
156         NTSTATUS status;
157
158         switch(epm_floor->lhs.protocol) {
159                 case EPM_PROTOCOL_UUID:
160                         status = dcerpc_floor_get_lhs_data(epm_floor, &uuid, &if_version);
161                         if (NT_STATUS_IS_OK(status)) {
162                                 /* lhs is used: UUID */
163                                 char *uuidstr;
164
165                                 if (GUID_equal(&uuid, &ndr_transfer_syntax.uuid)) {
166                                         return "NDR";
167                                 } 
168
169                                 if (GUID_equal(&uuid, &ndr64_transfer_syntax.uuid)) {
170                                         return "NDR64";
171                                 } 
172
173                                 uuidstr = GUID_string(mem_ctx, &uuid);
174
175                                 return talloc_asprintf(mem_ctx, " uuid %s/0x%02x", uuidstr, if_version);
176                         } else { /* IPX */
177                                 return talloc_asprintf(mem_ctx, "IPX:%s", 
178                                                 data_blob_hex_string(mem_ctx, &epm_floor->rhs.uuid.unknown));
179                         }
180
181                 case EPM_PROTOCOL_NCACN:
182                         return "RPC-C";
183
184                 case EPM_PROTOCOL_NCADG:
185                         return "RPC";
186
187                 case EPM_PROTOCOL_NCALRPC:
188                         return "NCALRPC";
189
190                 case EPM_PROTOCOL_DNET_NSP:
191                         return "DNET/NSP";
192
193                 case EPM_PROTOCOL_IP:
194                         return talloc_asprintf(mem_ctx, "IP:%s", epm_floor->rhs.ip.ipaddr);
195
196                 case EPM_PROTOCOL_PIPE:
197                         return talloc_asprintf(mem_ctx, "PIPE:%s", epm_floor->rhs.pipe.path);
198
199                 case EPM_PROTOCOL_SMB:
200                         return talloc_asprintf(mem_ctx, "SMB:%s", epm_floor->rhs.smb.unc);
201
202                 case EPM_PROTOCOL_UNIX_DS:
203                         return talloc_asprintf(mem_ctx, "Unix:%s", epm_floor->rhs.unix_ds.path);
204
205                 case EPM_PROTOCOL_NETBIOS:
206                         return talloc_asprintf(mem_ctx, "NetBIOS:%s", epm_floor->rhs.netbios.name);
207
208                 case EPM_PROTOCOL_NETBEUI:
209                         return "NETBeui";
210
211                 case EPM_PROTOCOL_SPX:
212                         return "SPX";
213
214                 case EPM_PROTOCOL_NB_IPX:
215                         return "NB_IPX";
216
217                 case EPM_PROTOCOL_HTTP:
218                         return talloc_asprintf(mem_ctx, "HTTP:%d", epm_floor->rhs.http.port);
219
220                 case EPM_PROTOCOL_TCP:
221                         return talloc_asprintf(mem_ctx, "TCP:%d", epm_floor->rhs.tcp.port);
222
223                 case EPM_PROTOCOL_UDP:
224                         return talloc_asprintf(mem_ctx, "UDP:%d", epm_floor->rhs.udp.port);
225
226                 default:
227                         return talloc_asprintf(mem_ctx, "UNK(%02x):", epm_floor->lhs.protocol);
228         }
229 }
230
231
232 /*
233   form a binding string from a binding structure
234 */
235 const char *dcerpc_binding_string(TALLOC_CTX *mem_ctx, const struct dcerpc_binding *b)
236 {
237         char *s = talloc_strdup(mem_ctx, "");
238         int i;
239         const char *t_name=NULL;
240
241         for (i=0;i<ARRAY_SIZE(transports);i++) {
242                 if (transports[i].transport == b->transport) {
243                         t_name = transports[i].name;
244                 }
245         }
246         if (!t_name) {
247                 return NULL;
248         }
249
250         if (!GUID_all_zero(&b->object)) { 
251                 s = talloc_asprintf(s, "%s@",
252                                     GUID_string(mem_ctx, &b->object));
253         }
254
255         s = talloc_asprintf_append(s, "%s:", t_name);
256         if (!s) return NULL;
257
258         if (b->host) {
259                 s = talloc_asprintf_append(s, "%s", b->host);
260         }
261
262         if (!b->endpoint && !b->options && !b->flags) {
263                 return s;
264         }
265
266         s = talloc_asprintf_append(s, "[");
267
268         if (b->endpoint) {
269                 s = talloc_asprintf_append(s, "%s", b->endpoint);
270         }
271
272         /* this is a *really* inefficent way of dealing with strings,
273            but this is rarely called and the strings are always short,
274            so I don't care */
275         for (i=0;b->options && b->options[i];i++) {
276                 s = talloc_asprintf_append(s, ",%s", b->options[i]);
277                 if (!s) return NULL;
278         }
279
280         for (i=0;i<ARRAY_SIZE(ncacn_options);i++) {
281                 if (b->flags & ncacn_options[i].flag) {
282                         s = talloc_asprintf_append(s, ",%s", ncacn_options[i].name);
283                         if (!s) return NULL;
284                 }
285         }
286
287         s = talloc_asprintf_append(s, "]");
288
289         return s;
290 }
291
292 /*
293   parse a binding string into a dcerpc_binding structure
294 */
295 NTSTATUS dcerpc_parse_binding(TALLOC_CTX *mem_ctx, const char *s, struct dcerpc_binding **b_out)
296 {
297         struct dcerpc_binding *b;
298         char *options, *type;
299         char *p;
300         int i, j, comma_count;
301
302         b = talloc(mem_ctx, struct dcerpc_binding);
303         if (!b) {
304                 return NT_STATUS_NO_MEMORY;
305         }
306
307         p = strchr(s, '@');
308
309         if (p && PTR_DIFF(p, s) == 36) { /* 36 is the length of a UUID */
310                 NTSTATUS status;
311
312                 status = GUID_from_string(s, &b->object);
313
314                 if (NT_STATUS_IS_ERR(status)) {
315                         DEBUG(0, ("Failed parsing UUID\n"));
316                         return status;
317                 }
318
319                 s = p + 1;
320         } else {
321                 ZERO_STRUCT(b->object);
322         }
323
324         b->object_version = 0;
325
326         p = strchr(s, ':');
327         if (!p) {
328                 return NT_STATUS_INVALID_PARAMETER;
329         }
330
331         type = talloc_strndup(mem_ctx, s, PTR_DIFF(p, s));
332         if (!type) {
333                 return NT_STATUS_NO_MEMORY;
334         }
335
336         for (i=0;i<ARRAY_SIZE(transports);i++) {
337                 if (strcasecmp(type, transports[i].name) == 0) {
338                         b->transport = transports[i].transport;
339                         break;
340                 }
341         }
342         if (i==ARRAY_SIZE(transports)) {
343                 DEBUG(0,("Unknown dcerpc transport '%s'\n", type));
344                 return NT_STATUS_INVALID_PARAMETER;
345         }
346         
347         s = p+1;
348
349         p = strchr(s, '[');
350         if (p) {
351                 b->host = talloc_strndup(b, s, PTR_DIFF(p, s));
352                 options = talloc_strdup(mem_ctx, p+1);
353                 if (options[strlen(options)-1] != ']') {
354                         return NT_STATUS_INVALID_PARAMETER;
355                 }
356                 options[strlen(options)-1] = 0;
357         } else {
358                 b->host = talloc_strdup(b, s);
359                 options = NULL;
360         }
361
362         if (!b->host) {
363                 return NT_STATUS_NO_MEMORY;
364         }
365
366         b->options = NULL;
367         b->flags = 0;
368         b->endpoint = NULL;
369
370         if (!options) {
371                 *b_out = b;
372                 return NT_STATUS_OK;
373         }
374
375         comma_count = count_chars(options, ',');
376
377         b->options = talloc_array(b, const char *, comma_count+2);
378         if (!b->options) {
379                 return NT_STATUS_NO_MEMORY;
380         }
381
382         for (i=0; (p = strchr(options, ',')); i++) {
383                 b->options[i] = talloc_strndup(b, options, PTR_DIFF(p, options));
384                 if (!b->options[i]) {
385                         return NT_STATUS_NO_MEMORY;
386                 }
387                 options = p+1;
388         }
389         b->options[i] = options;
390         b->options[i+1] = NULL;
391
392         /* some options are pre-parsed for convenience */
393         for (i=0;b->options[i];i++) {
394                 for (j=0;j<ARRAY_SIZE(ncacn_options);j++) {
395                         if (strcasecmp(ncacn_options[j].name, b->options[i]) == 0) {
396                                 int k;
397                                 b->flags |= ncacn_options[j].flag;
398                                 for (k=i;b->options[k];k++) {
399                                         b->options[k] = b->options[k+1];
400                                 }
401                                 i--;
402                                 break;
403                         }
404                 }
405         }
406
407         if (b->options[0]) {
408                 /* Endpoint is first option */
409                 b->endpoint = b->options[0];
410                 if (strlen(b->endpoint) == 0) b->endpoint = NULL;
411
412                 for (i=0;b->options[i];i++) {
413                         b->options[i] = b->options[i+1];
414                 }
415         }
416
417         if (b->options[0] == NULL)
418                 b->options = NULL;
419         
420         *b_out = b;
421         return NT_STATUS_OK;
422 }
423
424 NTSTATUS dcerpc_floor_get_lhs_data(struct epm_floor *epm_floor, struct GUID *uuid, uint16_t *if_version)
425 {
426         TALLOC_CTX *mem_ctx = talloc_init("floor_get_lhs_data");
427         struct ndr_pull *ndr = ndr_pull_init_blob(&epm_floor->lhs.lhs_data, mem_ctx);
428         NTSTATUS status;
429         
430         ndr->flags |= LIBNDR_FLAG_NOALIGN;
431
432         status = ndr_pull_GUID(ndr, NDR_SCALARS | NDR_BUFFERS, uuid);
433         if (NT_STATUS_IS_ERR(status)) {
434                 talloc_free(mem_ctx);
435                 return status;
436         }
437
438         status = ndr_pull_uint16(ndr, NDR_SCALARS, if_version);
439
440         talloc_free(mem_ctx);
441
442         return status;
443 }
444
445 static DATA_BLOB dcerpc_floor_pack_lhs_data(TALLOC_CTX *mem_ctx, const struct GUID *uuid, uint32_t if_version)
446 {
447         struct ndr_push *ndr = ndr_push_init_ctx(mem_ctx);
448
449         ndr->flags |= LIBNDR_FLAG_NOALIGN;
450
451         ndr_push_GUID(ndr, NDR_SCALARS | NDR_BUFFERS, uuid);
452         ndr_push_uint16(ndr, NDR_SCALARS, if_version);
453
454         return ndr_push_blob(ndr);
455 }
456
457 const char *dcerpc_floor_get_rhs_data(TALLOC_CTX *mem_ctx, struct epm_floor *epm_floor)
458 {
459         switch (epm_floor->lhs.protocol) {
460         case EPM_PROTOCOL_TCP:
461                 if (epm_floor->rhs.tcp.port == 0) return NULL;
462                 return talloc_asprintf(mem_ctx, "%d", epm_floor->rhs.tcp.port);
463                 
464         case EPM_PROTOCOL_UDP:
465                 if (epm_floor->rhs.udp.port == 0) return NULL;
466                 return talloc_asprintf(mem_ctx, "%d", epm_floor->rhs.udp.port);
467
468         case EPM_PROTOCOL_HTTP:
469                 if (epm_floor->rhs.http.port == 0) return NULL;
470                 return talloc_asprintf(mem_ctx, "%d", epm_floor->rhs.http.port);
471
472         case EPM_PROTOCOL_IP:
473                 return talloc_strdup(mem_ctx, epm_floor->rhs.ip.ipaddr);
474
475         case EPM_PROTOCOL_NCACN:
476                 return NULL;
477
478         case EPM_PROTOCOL_NCADG:
479                 return NULL;
480
481         case EPM_PROTOCOL_SMB:
482                 if (strlen(epm_floor->rhs.smb.unc) == 0) return NULL;
483                 return talloc_strdup(mem_ctx, epm_floor->rhs.smb.unc);
484
485         case EPM_PROTOCOL_PIPE:
486                 if (strlen(epm_floor->rhs.pipe.path) == 0) return NULL;
487                 return talloc_strdup(mem_ctx, epm_floor->rhs.pipe.path);
488
489         case EPM_PROTOCOL_NETBIOS:
490                 if (strlen(epm_floor->rhs.netbios.name) == 0) return NULL;
491                 return talloc_strdup(mem_ctx, epm_floor->rhs.netbios.name);
492
493         case EPM_PROTOCOL_NCALRPC:
494                 return NULL;
495                 
496         case EPM_PROTOCOL_VINES_SPP:
497                 return talloc_asprintf(mem_ctx, "%d", epm_floor->rhs.vines_spp.port);
498                 
499         case EPM_PROTOCOL_VINES_IPC:
500                 return talloc_asprintf(mem_ctx, "%d", epm_floor->rhs.vines_ipc.port);
501                 
502         case EPM_PROTOCOL_STREETTALK:
503                 return talloc_strdup(mem_ctx, epm_floor->rhs.streettalk.streettalk);
504                 
505         case EPM_PROTOCOL_UNIX_DS:
506                 if (strlen(epm_floor->rhs.unix_ds.path) == 0) return NULL;
507                 return talloc_strdup(mem_ctx, epm_floor->rhs.unix_ds.path);
508                 
509         case EPM_PROTOCOL_NULL:
510                 return NULL;
511
512         default:
513                 DEBUG(0,("Unsupported lhs protocol %d\n", epm_floor->lhs.protocol));
514                 break;
515         }
516
517         return NULL;
518 }
519
520 static NTSTATUS dcerpc_floor_set_rhs_data(TALLOC_CTX *mem_ctx, struct epm_floor *epm_floor,  const char *data)
521 {
522         switch (epm_floor->lhs.protocol) {
523         case EPM_PROTOCOL_TCP:
524                 epm_floor->rhs.tcp.port = atoi(data);
525                 return NT_STATUS_OK;
526                 
527         case EPM_PROTOCOL_UDP:
528                 epm_floor->rhs.udp.port = atoi(data);
529                 return NT_STATUS_OK;
530
531         case EPM_PROTOCOL_HTTP:
532                 epm_floor->rhs.http.port = atoi(data);
533                 return NT_STATUS_OK;
534
535         case EPM_PROTOCOL_IP:
536                 epm_floor->rhs.ip.ipaddr = talloc_strdup(mem_ctx, data);
537                 NT_STATUS_HAVE_NO_MEMORY(epm_floor->rhs.ip.ipaddr);
538                 return NT_STATUS_OK;
539
540         case EPM_PROTOCOL_NCACN:
541                 epm_floor->rhs.ncacn.minor_version = 0;
542                 return NT_STATUS_OK;
543
544         case EPM_PROTOCOL_NCADG:
545                 epm_floor->rhs.ncadg.minor_version = 0;
546                 return NT_STATUS_OK;
547
548         case EPM_PROTOCOL_SMB:
549                 epm_floor->rhs.smb.unc = talloc_strdup(mem_ctx, data);
550                 NT_STATUS_HAVE_NO_MEMORY(epm_floor->rhs.smb.unc);
551                 return NT_STATUS_OK;
552
553         case EPM_PROTOCOL_PIPE:
554                 epm_floor->rhs.pipe.path = talloc_strdup(mem_ctx, data);
555                 NT_STATUS_HAVE_NO_MEMORY(epm_floor->rhs.pipe.path);
556                 return NT_STATUS_OK;
557
558         case EPM_PROTOCOL_NETBIOS:
559                 epm_floor->rhs.netbios.name = talloc_strdup(mem_ctx, data);
560                 NT_STATUS_HAVE_NO_MEMORY(epm_floor->rhs.netbios.name);
561                 return NT_STATUS_OK;
562
563         case EPM_PROTOCOL_NCALRPC:
564                 return NT_STATUS_OK;
565                 
566         case EPM_PROTOCOL_VINES_SPP:
567                 epm_floor->rhs.vines_spp.port = atoi(data);
568                 return NT_STATUS_OK;
569                 
570         case EPM_PROTOCOL_VINES_IPC:
571                 epm_floor->rhs.vines_ipc.port = atoi(data);
572                 return NT_STATUS_OK;
573                 
574         case EPM_PROTOCOL_STREETTALK:
575                 epm_floor->rhs.streettalk.streettalk = talloc_strdup(mem_ctx, data);
576                 NT_STATUS_HAVE_NO_MEMORY(epm_floor->rhs.streettalk.streettalk);
577                 return NT_STATUS_OK;
578                 
579         case EPM_PROTOCOL_UNIX_DS:
580                 epm_floor->rhs.unix_ds.path = talloc_strdup(mem_ctx, data);
581                 NT_STATUS_HAVE_NO_MEMORY(epm_floor->rhs.unix_ds.path);
582                 return NT_STATUS_OK;
583                 
584         case EPM_PROTOCOL_NULL:
585                 return NT_STATUS_OK;
586
587         default:
588                 DEBUG(0,("Unsupported lhs protocol %d\n", epm_floor->lhs.protocol));
589                 break;
590         }
591
592         return NT_STATUS_NOT_SUPPORTED;
593 }
594
595 enum dcerpc_transport_t dcerpc_transport_by_endpoint_protocol(int prot)
596 {
597         int i;
598
599         /* Find a transport that has 'prot' as 4th protocol */
600         for (i=0;i<ARRAY_SIZE(transports);i++) {
601                 if (transports[i].num_protocols >= 2 && 
602                         transports[i].protseq[1] == prot) {
603                         return transports[i].transport;
604                 }
605         }
606         
607         /* Unknown transport */
608         return -1;
609 }
610
611 enum dcerpc_transport_t dcerpc_transport_by_tower(struct epm_tower *tower)
612 {
613         int i;
614
615         /* Find a transport that matches this tower */
616         for (i=0;i<ARRAY_SIZE(transports);i++) {
617                 int j;
618                 if (transports[i].num_protocols != tower->num_floors - 2) {
619                         continue; 
620                 }
621
622                 for (j = 0; j < transports[i].num_protocols; j++) {
623                         if (transports[i].protseq[j] != tower->floors[j+2].lhs.protocol) {
624                                 break;
625                         }
626                 }
627
628                 if (j == transports[i].num_protocols) {
629                         return transports[i].transport;
630                 }
631         }
632         
633         /* Unknown transport */
634         return -1;
635 }
636
637 NTSTATUS dcerpc_binding_from_tower(TALLOC_CTX *mem_ctx, struct epm_tower *tower, struct dcerpc_binding **b_out)
638 {
639         NTSTATUS status;
640         struct dcerpc_binding *binding;
641
642         binding = talloc(mem_ctx, struct dcerpc_binding);
643         NT_STATUS_HAVE_NO_MEMORY(binding);
644
645         ZERO_STRUCT(binding->object);
646         binding->options = NULL;
647         binding->host = NULL;
648         binding->flags = 0;
649
650         binding->transport = dcerpc_transport_by_tower(tower);
651
652         if (binding->transport == -1) {
653                 return NT_STATUS_NOT_SUPPORTED;
654         }
655
656         if (tower->num_floors < 1) {
657                 return NT_STATUS_OK;
658         }
659
660         /* Set object uuid */
661         status = dcerpc_floor_get_lhs_data(&tower->floors[0], &binding->object, &binding->object_version);
662         
663         if (!NT_STATUS_IS_OK(status)) {
664                 DEBUG(1, ("Error pulling object uuid and version: %s", nt_errstr(status)));     
665                 return status;
666         }
667
668         /* Ignore floor 1, it contains the NDR version info */
669         
670         binding->options = NULL;
671
672         /* Set endpoint */
673         if (tower->num_floors >= 4) {
674                 binding->endpoint = dcerpc_floor_get_rhs_data(mem_ctx, &tower->floors[3]);
675         } else {
676                 binding->endpoint = NULL;
677         }
678
679         /* Set network address */
680         if (tower->num_floors >= 5) {
681                 binding->host = dcerpc_floor_get_rhs_data(mem_ctx, &tower->floors[4]);
682         }
683         *b_out = binding;
684         return NT_STATUS_OK;
685 }
686
687 NTSTATUS dcerpc_binding_build_tower(TALLOC_CTX *mem_ctx, struct dcerpc_binding *binding, struct epm_tower *tower)
688 {
689         const enum epm_protocol *protseq = NULL;
690         int num_protocols = -1, i;
691         NTSTATUS status;
692         
693         /* Find transport */
694         for (i=0;i<ARRAY_SIZE(transports);i++) {
695                 if (transports[i].transport == binding->transport) {
696                         protseq = transports[i].protseq;
697                         num_protocols = transports[i].num_protocols;
698                         break;
699                 }
700         }
701
702         if (num_protocols == -1) {
703                 DEBUG(0, ("Unable to find transport with id '%d'\n", binding->transport));
704                 return NT_STATUS_UNSUCCESSFUL;
705         }
706
707         tower->num_floors = 2 + num_protocols;
708         tower->floors = talloc_array(mem_ctx, struct epm_floor, tower->num_floors);
709
710         /* Floor 0 */
711         tower->floors[0].lhs.protocol = EPM_PROTOCOL_UUID;
712
713         tower->floors[0].lhs.lhs_data = dcerpc_floor_pack_lhs_data(mem_ctx, &binding->object, binding->object_version);
714
715         tower->floors[0].rhs.uuid.unknown = data_blob_talloc_zero(mem_ctx, 2);
716         
717         /* Floor 1 */
718         tower->floors[1].lhs.protocol = EPM_PROTOCOL_UUID;
719
720         tower->floors[1].lhs.lhs_data = dcerpc_floor_pack_lhs_data(mem_ctx, 
721                                                                 &ndr_transfer_syntax.uuid, 
722                                                                 ndr_transfer_syntax.if_version);
723         
724         tower->floors[1].rhs.uuid.unknown = data_blob_talloc_zero(mem_ctx, 2);
725         
726         /* Floor 2 to num_protocols */
727         for (i = 0; i < num_protocols; i++) {
728                 tower->floors[2 + i].lhs.protocol = protseq[i];
729                 tower->floors[2 + i].lhs.lhs_data = data_blob_talloc(mem_ctx, NULL, 0);
730                 ZERO_STRUCT(tower->floors[2 + i].rhs);
731                 dcerpc_floor_set_rhs_data(mem_ctx, &tower->floors[2 + i], "");
732         }
733
734         /* The 4th floor contains the endpoint */
735         if (num_protocols >= 2 && binding->endpoint) {
736                 status = dcerpc_floor_set_rhs_data(mem_ctx, &tower->floors[3], binding->endpoint);
737                 if (NT_STATUS_IS_ERR(status)) {
738                         return status;
739                 }
740         }
741         
742         /* The 5th contains the network address */
743         if (num_protocols >= 3 && binding->host) {
744                 if (is_ipaddress(binding->host)) {
745                         status = dcerpc_floor_set_rhs_data(mem_ctx, &tower->floors[4], 
746                                                            binding->host);
747                 } else {
748                         /* note that we don't attempt to resolve the
749                            name here - when we get a hostname here we
750                            are in the client code, and want to put in
751                            a wildcard all-zeros IP for the server to
752                            fill in */
753                         status = dcerpc_floor_set_rhs_data(mem_ctx, &tower->floors[4], 
754                                                            "0.0.0.0");
755                 }
756                 if (NT_STATUS_IS_ERR(status)) {
757                         return status;
758                 }
759         }
760
761         return NT_STATUS_OK;
762 }
763
764
765 struct epm_map_binding_state {
766         struct dcerpc_binding *binding;
767         const struct dcerpc_interface_table *table;
768         struct dcerpc_pipe *pipe;
769         struct policy_handle handle;
770         struct GUID guid;
771         struct epm_twr_t twr;
772         struct epm_twr_t *twr_r;
773         struct epm_Map r;
774 };
775
776
777 static void continue_epm_recv_binding(struct composite_context *ctx);
778 static void continue_epm_map(struct rpc_request *req);
779
780
781 /*
782   Stage 2 of epm_map_binding: Receive connected rpc pipe and send endpoint
783   mapping rpc request
784 */
785 static void continue_epm_recv_binding(struct composite_context *ctx)
786 {
787         struct rpc_request *map_req;
788
789         struct composite_context *c = talloc_get_type(ctx->async.private_data,
790                                                       struct composite_context);
791         struct epm_map_binding_state *s = talloc_get_type(c->private_data,
792                                                           struct epm_map_binding_state);
793
794         /* receive result of rpc pipe connect request */
795         c->status = dcerpc_pipe_connect_b_recv(ctx, c, &s->pipe);
796         if (!composite_is_ok(c)) return;
797
798         /* prepare requested binding parameters */
799         s->binding->object         = s->table->uuid;
800         s->binding->object_version = s->table->if_version;
801
802         c->status = dcerpc_binding_build_tower(s->pipe, s->binding, &s->twr.tower);
803         if (!composite_is_ok(c)) return;
804         
805         /* with some nice pretty paper around it of course */
806         s->r.in.object        = &s->guid;
807         s->r.in.map_tower     = &s->twr;
808         s->r.in.entry_handle  = &s->handle;
809         s->r.in.max_towers    = 1;
810         s->r.out.entry_handle = &s->handle;
811
812         /* send request for an endpoint mapping - a rpc request on connected pipe */
813         map_req = dcerpc_epm_Map_send(s->pipe, c, &s->r);
814         if (composite_nomem(map_req, c)) return;
815         
816         composite_continue_rpc(c, map_req, continue_epm_map, c);
817 }
818
819
820 /*
821   Stage 3 of epm_map_binding: Receive endpoint mapping and provide binding details
822 */
823 static void continue_epm_map(struct rpc_request *req)
824 {
825         struct composite_context *c = talloc_get_type(req->async.private,
826                                                       struct composite_context);
827         struct epm_map_binding_state *s = talloc_get_type(c->private_data,
828                                                           struct epm_map_binding_state);
829
830         /* receive result of a rpc request */
831         c->status = dcerpc_ndr_request_recv(req);
832         if (!composite_is_ok(c)) return;
833
834         /* check the details */
835         if (s->r.out.result != 0 || s->r.out.num_towers != 1) {
836                 composite_error(c, NT_STATUS_PORT_UNREACHABLE);
837                 return;
838         }
839         
840         s->twr_r = s->r.out.towers[0].twr;
841         if (s->twr_r == NULL) {
842                 composite_error(c, NT_STATUS_PORT_UNREACHABLE);
843                 return;
844         }
845
846         if (s->twr_r->tower.num_floors != s->twr.tower.num_floors ||
847             s->twr_r->tower.floors[3].lhs.protocol != s->twr.tower.floors[3].lhs.protocol) {
848                 composite_error(c, NT_STATUS_PORT_UNREACHABLE);
849                 return;
850         }
851
852         /* get received endpoint */
853         s->binding->endpoint = talloc_reference(s->binding,
854                                                 dcerpc_floor_get_rhs_data(c, &s->twr_r->tower.floors[3]));
855         composite_done(c);
856 }
857
858
859 /*
860   Request for endpoint mapping of dcerpc binding - try to request for endpoint
861   unless there is default one.
862 */
863 struct composite_context *dcerpc_epm_map_binding_send(TALLOC_CTX *mem_ctx,
864                                                       struct dcerpc_binding *binding,
865                                                       const struct dcerpc_interface_table *table,
866                                                       struct event_context *ev)
867 {
868         struct composite_context *c;
869         struct epm_map_binding_state *s;
870         struct composite_context *pipe_connect_req;
871         struct cli_credentials *anon_creds;
872
873         NTSTATUS status;
874         struct dcerpc_binding *epmapper_binding;
875         int i;
876
877         /* composite context allocation and setup */
878         c = talloc_zero(mem_ctx, struct composite_context);
879         if (c == NULL) return NULL;
880
881         s = talloc_zero(c, struct epm_map_binding_state);
882         if (composite_nomem(s, c)) return c;
883
884         c->state = COMPOSITE_STATE_IN_PROGRESS;
885         c->private_data = s;
886         c->event_ctx = ev;
887
888         /* Try to find event context in memory context in case passed
889          * event_context (argument) was NULL. If there's none, just
890          * create a new one.
891          */
892         if (c->event_ctx == NULL) {
893                 c->event_ctx = event_context_find(mem_ctx);
894         }
895         
896         s->binding = binding;
897         s->table   = table;
898
899         /* anonymous credentials for rpc connection used to get endpoint mapping */
900         anon_creds = cli_credentials_init(mem_ctx);
901         cli_credentials_set_conf(anon_creds);
902         cli_credentials_set_anonymous(anon_creds);
903
904         /*
905           First, check if there is a default endpoint specified in the IDL
906         */
907         if (table) {
908                 struct dcerpc_binding *default_binding;
909
910                 /* Find one of the default pipes for this interface */
911                 for (i = 0; i < table->endpoints->count; i++) {
912                         status = dcerpc_parse_binding(mem_ctx, table->endpoints->names[i], &default_binding);
913
914                         if (NT_STATUS_IS_OK(status)) {
915                                 if (default_binding->transport == binding->transport && default_binding->endpoint) {
916                                         binding->endpoint = talloc_reference(binding, default_binding->endpoint);
917                                         talloc_free(default_binding);
918
919                                         composite_done(c);
920                                         return c;
921
922                                 } else {
923                                         talloc_free(default_binding);
924                                 }
925                         }
926                 }
927         }
928
929         epmapper_binding = talloc_zero(c, struct dcerpc_binding);
930         if (composite_nomem(epmapper_binding, c)) return c;
931
932         /* basic endpoint mapping data */
933         epmapper_binding->transport  = binding->transport;
934         epmapper_binding->host       = talloc_reference(epmapper_binding, binding->host);
935         epmapper_binding->options    = NULL;
936         epmapper_binding->flags      = 0;
937         epmapper_binding->endpoint   = NULL;
938
939         /* initiate rpc pipe connection */
940         pipe_connect_req = dcerpc_pipe_connect_b_send(c, &s->pipe, epmapper_binding, &dcerpc_table_epmapper,
941                                                       anon_creds, c->event_ctx);
942         if (composite_nomem(pipe_connect_req, c)) return c;
943         
944         composite_continue(c, pipe_connect_req, continue_epm_recv_binding, c);
945         return c;
946 }
947
948
949 /*
950   Receive result of endpoint mapping request
951  */
952 NTSTATUS dcerpc_epm_map_binding_recv(struct composite_context *c)
953 {
954         NTSTATUS status = composite_wait(c);
955         
956         talloc_free(c);
957         return status;
958 }
959
960
961 /*
962   Get endpoint mapping for rpc connection
963 */
964 NTSTATUS dcerpc_epm_map_binding(TALLOC_CTX *mem_ctx, struct dcerpc_binding *binding,
965                                 const struct dcerpc_interface_table *table, struct event_context *ev)
966 {
967         struct composite_context *c;
968
969         c = dcerpc_epm_map_binding_send(mem_ctx, binding, table, ev);
970         return dcerpc_epm_map_binding_recv(c);
971 }
972
973
974 struct pipe_auth_state {
975         struct dcerpc_pipe *pipe;
976         struct dcerpc_binding *binding;
977         const struct dcerpc_interface_table *table;
978         struct cli_credentials *credentials;
979 };
980
981
982 static void continue_auth_schannel(struct composite_context *ctx);
983 static void continue_auth(struct composite_context *ctx);
984 static void continue_auth_none(struct composite_context *ctx);
985
986
987 /*
988   Stage 2 of pipe_auth: Receive result of schannel bind request
989 */
990 static void continue_auth_schannel(struct composite_context *ctx)
991 {
992         struct composite_context *c = talloc_get_type(ctx->async.private_data,
993                                                       struct composite_context);
994
995         c->status = dcerpc_bind_auth_schannel_recv(ctx);
996         if (!composite_is_ok(c)) return;
997
998         composite_done(c);
999 }
1000
1001
1002 /*
1003   Stage 2 of pipe_auth: Receive result of authenticated bind request
1004 */
1005 static void continue_auth(struct composite_context *ctx)
1006 {
1007         struct composite_context *c = talloc_get_type(ctx->async.private_data,
1008                                                       struct composite_context);
1009
1010         c->status = dcerpc_bind_auth_recv(ctx);
1011         if (!composite_is_ok(c)) return;
1012         
1013         composite_done(c);
1014 }
1015
1016
1017 /*
1018   Stage 2 of pipe_auth: Receive result of non-authenticated bind request
1019 */
1020 static void continue_auth_none(struct composite_context *ctx)
1021 {
1022         struct composite_context *c = talloc_get_type(ctx->async.private_data,
1023                                                       struct composite_context);
1024
1025         c->status = dcerpc_bind_auth_none_recv(ctx);
1026         if (!composite_is_ok(c)) return;
1027         
1028         composite_done(c);
1029 }
1030
1031
1032 /*
1033   Request to perform an authenticated bind if required. Authentication
1034   is determined using credentials passed and binding flags.
1035 */
1036 struct composite_context *dcerpc_pipe_auth_send(struct dcerpc_pipe *p, 
1037                                                 struct dcerpc_binding *binding,
1038                                                 const struct dcerpc_interface_table *table,
1039                                                 struct cli_credentials *credentials)
1040 {
1041         struct composite_context *c;
1042         struct pipe_auth_state *s;
1043         struct composite_context *auth_schannel_req;
1044         struct composite_context *auth_req;
1045         struct composite_context *auth_none_req;
1046
1047         /* composite context allocation and setup */
1048         c = talloc_zero(NULL, struct composite_context);
1049         if (c == NULL) return NULL;
1050
1051         s = talloc_zero(c, struct pipe_auth_state);
1052         if (composite_nomem(s, c)) return c;
1053
1054         c->state = COMPOSITE_STATE_IN_PROGRESS;
1055         c->private_data = s;
1056         c->event_ctx = p->conn->event_ctx;
1057
1058         /* store parameters in state structure */
1059         s->binding      = binding;
1060         s->table        = table;
1061         s->credentials  = credentials;
1062         s->pipe         = p;
1063
1064         s->pipe->conn->flags = binding->flags;
1065         
1066         /* remember the binding string for possible secondary connections */
1067         s->pipe->conn->binding_string = dcerpc_binding_string(p, binding);
1068
1069         if (!cli_credentials_is_anonymous(s->credentials) &&
1070             (binding->flags & DCERPC_SCHANNEL) &&
1071             !cli_credentials_get_netlogon_creds(s->credentials)) {
1072
1073                 /* If we don't already have netlogon credentials for
1074                  * the schannel bind, then we have to get these
1075                  * first */
1076                 auth_schannel_req = dcerpc_bind_auth_schannel_send(c, s->pipe, s->table,
1077                                                                    s->credentials,
1078                                                                    dcerpc_auth_level(s->pipe->conn));
1079                 if (composite_nomem(auth_schannel_req, c)) return c;
1080
1081                 composite_continue(c, auth_schannel_req, continue_auth_schannel, c);
1082
1083         } else if (!cli_credentials_is_anonymous(s->credentials) &&
1084                    !(s->pipe->conn->transport.transport == NCACN_NP &&
1085                      !(s->binding->flags & DCERPC_SIGN) &&
1086                      !(s->binding->flags & DCERPC_SEAL))) {
1087
1088                 /* Perform an authenticated DCE-RPC bind, except where
1089                  * we ask for a connection on NCACN_NP, and that
1090                  * connection is not signed or sealed.  For that case
1091                  * we rely on the already authenticated CIFS connection
1092                  */
1093                 
1094                 uint8_t auth_type;
1095
1096                 if ((s->pipe->conn->flags & (DCERPC_SIGN|DCERPC_SEAL)) == 0) {
1097                         /*
1098                           we are doing an authenticated connection,
1099                           but not using sign or seal. We must force
1100                           the CONNECT dcerpc auth type as a NONE auth
1101                           type doesn't allow authentication
1102                           information to be passed.
1103                         */
1104                         s->pipe->conn->flags |= DCERPC_CONNECT;
1105                 }
1106
1107                 if (s->binding->flags & DCERPC_AUTH_SPNEGO) {
1108                         auth_type = DCERPC_AUTH_TYPE_SPNEGO;
1109
1110                 } else if (s->binding->flags & DCERPC_AUTH_KRB5) {
1111                         auth_type = DCERPC_AUTH_TYPE_KRB5;
1112
1113                 } else if (s->binding->flags & DCERPC_SCHANNEL) {
1114                         auth_type = DCERPC_AUTH_TYPE_SCHANNEL;
1115
1116                 } else {
1117                         auth_type = DCERPC_AUTH_TYPE_NTLMSSP;
1118                 }
1119                 
1120                 auth_req = dcerpc_bind_auth_send(c, s->pipe, s->table,
1121                                                  s->credentials, auth_type,
1122                                                  dcerpc_auth_level(s->pipe->conn),
1123                                                  s->table->authservices->names[0]);
1124                 if (composite_nomem(auth_req, c)) return c;
1125                 
1126                 composite_continue(c, auth_req, continue_auth, c);
1127
1128         } else {
1129                 auth_none_req = dcerpc_bind_auth_none_send(c, s->pipe, s->table);
1130                 if (composite_nomem(auth_none_req, c)) return c;
1131
1132                 composite_continue(c, auth_none_req, continue_auth_none, c);
1133         }
1134
1135         return c;
1136 }
1137
1138
1139 /*
1140   Receive result of authenticated bind request on dcerpc pipe
1141 */
1142 NTSTATUS dcerpc_pipe_auth_recv(struct composite_context *c)
1143 {
1144         NTSTATUS status;
1145
1146         struct pipe_auth_state *s = talloc_get_type(c->private_data,
1147                                                     struct pipe_auth_state);
1148         status = composite_wait(c);
1149         if (!NT_STATUS_IS_OK(status)) {
1150                 char *uuid_str = GUID_string(s->pipe, &s->table->uuid);
1151                 DEBUG(0, ("Failed to bind to uuid %s - %s\n", uuid_str, nt_errstr(status)));
1152                 talloc_free(uuid_str);
1153         }
1154
1155         talloc_free(c);
1156         return status;
1157 }
1158
1159
1160 /* 
1161    Perform an authenticated bind if needed - sync version
1162 */
1163 NTSTATUS dcerpc_pipe_auth(struct dcerpc_pipe *p, 
1164                           struct dcerpc_binding *binding,
1165                           const struct dcerpc_interface_table *table,
1166                           struct cli_credentials *credentials)
1167 {
1168         struct composite_context *c;
1169
1170         c = dcerpc_pipe_auth_send(p, binding, table, credentials);
1171         return dcerpc_pipe_auth_recv(c);
1172 }
1173
1174
1175 NTSTATUS dcerpc_generic_session_key(struct dcerpc_connection *c,
1176                                     DATA_BLOB *session_key)
1177 {
1178         /* this took quite a few CPU cycles to find ... */
1179         session_key->data = discard_const_p(unsigned char, "SystemLibraryDTC");
1180         session_key->length = 16;
1181         return NT_STATUS_OK;
1182 }
1183
1184 /*
1185   fetch the user session key - may be default (above) or the SMB session key
1186 */
1187 NTSTATUS dcerpc_fetch_session_key(struct dcerpc_pipe *p,
1188                                   DATA_BLOB *session_key)
1189 {
1190         return p->conn->security_state.session_key(p->conn, session_key);
1191 }
1192
1193
1194 /*
1195   log a rpc packet in a format suitable for ndrdump. This is especially useful
1196   for sealed packets, where ethereal cannot easily see the contents
1197
1198   this triggers on a debug level of >= 10
1199 */
1200 void dcerpc_log_packet(const struct dcerpc_interface_table *ndr,
1201                        uint32_t opnum, uint32_t flags, DATA_BLOB *pkt)
1202 {
1203         const int num_examples = 20;
1204         int i;
1205
1206         if (DEBUGLEVEL < 10) return;
1207
1208         for (i=0;i<num_examples;i++) {
1209                 char *name=NULL;
1210                 asprintf(&name, "%s/rpclog/%s-%u.%d.%s", 
1211                          lp_lockdir(), ndr->name, opnum, i,
1212                          (flags&NDR_IN)?"in":"out");
1213                 if (name == NULL) {
1214                         return;
1215                 }
1216                 if (!file_exist(name)) {
1217                         if (file_save(name, pkt->data, pkt->length)) {
1218                                 DEBUG(10,("Logged rpc packet to %s\n", name));
1219                         }
1220                         free(name);
1221                         break;
1222                 }
1223                 free(name);
1224         }
1225 }
1226
1227
1228
1229 /*
1230   create a secondary context from a primary connection
1231
1232   this uses dcerpc_alter_context() to create a new dcerpc context_id
1233 */
1234 NTSTATUS dcerpc_secondary_context(struct dcerpc_pipe *p, 
1235                                   struct dcerpc_pipe **pp2,
1236                                   const struct dcerpc_interface_table *table)
1237 {
1238         NTSTATUS status;
1239         struct dcerpc_pipe *p2;
1240         
1241         p2 = talloc_zero(p, struct dcerpc_pipe);
1242         if (p2 == NULL) {
1243                 return NT_STATUS_NO_MEMORY;
1244         }
1245         p2->conn = talloc_reference(p2, p->conn);
1246         p2->request_timeout = p->request_timeout;
1247
1248         p2->context_id = ++p->conn->next_context_id;
1249
1250         p2->syntax.uuid = table->uuid;
1251         p2->syntax.if_version = table->if_version;
1252
1253         p2->transfer_syntax = ndr_transfer_syntax;
1254
1255         status = dcerpc_alter_context(p2, p2, &p2->syntax, &p2->transfer_syntax);
1256         if (!NT_STATUS_IS_OK(status)) {
1257                 talloc_free(p2);
1258                 return status;
1259         }
1260
1261         *pp2 = p2;
1262
1263         return status;
1264 }