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