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