Finish removal of iconv_convenience in public API's.
[bbaumbach/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 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 ncacn_packet *pkt,
55                          struct dcerpc_auth *auth_info)
56 {
57         struct ndr_push *ndr;
58         enum ndr_err_code ndr_err;
59
60         ndr = ndr_push_init_ctx(mem_ctx);
61         if (!ndr) {
62                 return NT_STATUS_NO_MEMORY;
63         }
64
65         if (!(pkt->drep[0] & DCERPC_DREP_LE)) {
66                 ndr->flags |= LIBNDR_FLAG_BIGENDIAN;
67         }
68
69         if (pkt->pfc_flags & DCERPC_PFC_FLAG_OBJECT_UUID) {
70                 ndr->flags |= LIBNDR_FLAG_OBJECT_PRESENT;
71         }
72
73         if (auth_info) {
74                 pkt->auth_length = auth_info->credentials.length;
75         } else {
76                 pkt->auth_length = 0;
77         }
78
79         ndr_err = ndr_push_ncacn_packet(ndr, NDR_SCALARS|NDR_BUFFERS, pkt);
80         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
81                 return ndr_map_error2ntstatus(ndr_err);
82         }
83
84         if (auth_info) {
85 #if 0
86                 /* the s3 rpc server doesn't handle auth padding in
87                    bind requests. Use zero auth padding to keep us
88                    working with old servers */
89                 uint32_t offset = ndr->offset;
90                 ndr_err = ndr_push_align(ndr, 16);
91                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
92                         return ndr_map_error2ntstatus(ndr_err);
93                 }
94                 auth_info->auth_pad_length = ndr->offset - offset;
95 #else
96                 auth_info->auth_pad_length = 0;
97 #endif
98                 ndr_err = ndr_push_dcerpc_auth(ndr, NDR_SCALARS|NDR_BUFFERS, auth_info);
99                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
100                         return ndr_map_error2ntstatus(ndr_err);
101                 }
102         }
103
104         *blob = ndr_push_blob(ndr);
105
106         /* fill in the frag length */
107         dcerpc_set_frag_length(blob, blob->length);
108
109         return NT_STATUS_OK;
110 }
111
112
113 struct epm_map_binding_state {
114         struct dcerpc_binding *binding;
115         const struct ndr_interface_table *table;
116         struct dcerpc_pipe *pipe;
117         struct policy_handle handle;
118         struct GUID guid;
119         struct epm_twr_t twr;
120         struct epm_twr_t *twr_r;
121         struct epm_Map r;
122 };
123
124
125 static void continue_epm_recv_binding(struct composite_context *ctx);
126 static void continue_epm_map(struct tevent_req *subreq);
127
128
129 /*
130   Stage 2 of epm_map_binding: Receive connected rpc pipe and send endpoint
131   mapping rpc request
132 */
133 static void continue_epm_recv_binding(struct composite_context *ctx)
134 {
135         struct composite_context *c = talloc_get_type(ctx->async.private_data,
136                                                       struct composite_context);
137         struct epm_map_binding_state *s = talloc_get_type(c->private_data,
138                                                           struct epm_map_binding_state);
139         struct tevent_req *subreq;
140
141         /* receive result of rpc pipe connect request */
142         c->status = dcerpc_pipe_connect_b_recv(ctx, c, &s->pipe);
143         if (!composite_is_ok(c)) return;
144
145         s->pipe->conn->flags |= DCERPC_NDR_REF_ALLOC;
146
147         /* prepare requested binding parameters */
148         s->binding->object         = s->table->syntax_id;
149
150         c->status = dcerpc_binding_build_tower(s->pipe, s->binding, &s->twr.tower);
151         if (!composite_is_ok(c)) return;
152         
153         /* with some nice pretty paper around it of course */
154         s->r.in.object        = &s->guid;
155         s->r.in.map_tower     = &s->twr;
156         s->r.in.entry_handle  = &s->handle;
157         s->r.in.max_towers    = 1;
158         s->r.out.entry_handle = &s->handle;
159
160         /* send request for an endpoint mapping - a rpc request on connected pipe */
161         subreq = dcerpc_epm_Map_r_send(s, c->event_ctx,
162                                        s->pipe->binding_handle,
163                                        &s->r);
164         if (composite_nomem(subreq, c)) return;
165         
166         tevent_req_set_callback(subreq, continue_epm_map, c);
167 }
168
169
170 /*
171   Stage 3 of epm_map_binding: Receive endpoint mapping and provide binding details
172 */
173 static void continue_epm_map(struct tevent_req *subreq)
174 {
175         struct composite_context *c = tevent_req_callback_data(subreq,
176                                       struct composite_context);
177         struct epm_map_binding_state *s = talloc_get_type(c->private_data,
178                                                           struct epm_map_binding_state);
179
180         /* receive result of a rpc request */
181         c->status = dcerpc_epm_Map_r_recv(subreq, s);
182         TALLOC_FREE(subreq);
183         if (!composite_is_ok(c)) return;
184
185         /* check the details */
186         if (s->r.out.result != 0 || *s->r.out.num_towers != 1) {
187                 composite_error(c, NT_STATUS_PORT_UNREACHABLE);
188                 return;
189         }
190         
191         s->twr_r = s->r.out.towers[0].twr;
192         if (s->twr_r == NULL) {
193                 composite_error(c, NT_STATUS_PORT_UNREACHABLE);
194                 return;
195         }
196
197         if (s->twr_r->tower.num_floors != s->twr.tower.num_floors ||
198             s->twr_r->tower.floors[3].lhs.protocol != s->twr.tower.floors[3].lhs.protocol) {
199                 composite_error(c, NT_STATUS_PORT_UNREACHABLE);
200                 return;
201         }
202
203         /* get received endpoint */
204         s->binding->endpoint = talloc_reference(s->binding,
205                                                 dcerpc_floor_get_rhs_data(c, &s->twr_r->tower.floors[3]));
206         if (composite_nomem(s->binding->endpoint, c)) return;
207
208         composite_done(c);
209 }
210
211
212 /*
213   Request for endpoint mapping of dcerpc binding - try to request for endpoint
214   unless there is default one.
215 */
216 struct composite_context *dcerpc_epm_map_binding_send(TALLOC_CTX *mem_ctx,
217                                                       struct dcerpc_binding *binding,
218                                                       const struct ndr_interface_table *table,
219                                                       struct tevent_context *ev,
220                                                       struct loadparm_context *lp_ctx)
221 {
222         struct composite_context *c;
223         struct epm_map_binding_state *s;
224         struct composite_context *pipe_connect_req;
225         struct cli_credentials *anon_creds;
226
227         NTSTATUS status;
228         struct dcerpc_binding *epmapper_binding;
229         int i;
230
231         if (ev == NULL) {
232                 return NULL;
233         }
234
235         /* composite context allocation and setup */
236         c = composite_create(mem_ctx, ev);
237         if (c == NULL) {
238                 return NULL;
239         }
240
241         s = talloc_zero(c, struct epm_map_binding_state);
242         if (composite_nomem(s, c)) return c;
243         c->private_data = s;
244
245         s->binding = binding;
246         s->table   = table;
247
248         /* anonymous credentials for rpc connection used to get endpoint mapping */
249         anon_creds = cli_credentials_init(mem_ctx);
250         cli_credentials_set_anonymous(anon_creds);
251
252         /*
253           First, check if there is a default endpoint specified in the IDL
254         */
255         if (table != NULL) {
256                 struct dcerpc_binding *default_binding;
257
258                 /* Find one of the default pipes for this interface */
259                 for (i = 0; i < table->endpoints->count; i++) {
260                         status = dcerpc_parse_binding(mem_ctx, table->endpoints->names[i], &default_binding);
261
262                         if (NT_STATUS_IS_OK(status)) {
263                                 if (binding->transport == NCA_UNKNOWN) 
264                                         binding->transport = default_binding->transport;
265                                 if (default_binding->transport == binding->transport && 
266                                         default_binding->endpoint) {
267                                         binding->endpoint = talloc_reference(binding, default_binding->endpoint);
268                                         talloc_free(default_binding);
269
270                                         composite_done(c);
271                                         return c;
272
273                                 } else {
274                                         talloc_free(default_binding);
275                                 }
276                         }
277                 }
278         }
279
280         epmapper_binding = talloc_zero(c, struct dcerpc_binding);
281         if (composite_nomem(epmapper_binding, c)) return c;
282
283         /* basic endpoint mapping data */
284         epmapper_binding->transport             = binding->transport;
285         epmapper_binding->host                  = talloc_reference(epmapper_binding, binding->host);
286         epmapper_binding->target_hostname       = epmapper_binding->host;
287         epmapper_binding->options               = NULL;
288         epmapper_binding->flags                 = 0;
289         epmapper_binding->assoc_group_id        = 0;
290         epmapper_binding->endpoint              = NULL;
291
292         /* initiate rpc pipe connection */
293         pipe_connect_req = dcerpc_pipe_connect_b_send(c, epmapper_binding, 
294                                                       &ndr_table_epmapper,
295                                                       anon_creds, c->event_ctx,
296                                                       lp_ctx);
297         if (composite_nomem(pipe_connect_req, c)) return c;
298         
299         composite_continue(c, pipe_connect_req, continue_epm_recv_binding, c);
300         return c;
301 }
302
303
304 /*
305   Receive result of endpoint mapping request
306  */
307 NTSTATUS dcerpc_epm_map_binding_recv(struct composite_context *c)
308 {
309         NTSTATUS status = composite_wait(c);
310         
311         talloc_free(c);
312         return status;
313 }
314
315
316 /*
317   Get endpoint mapping for rpc connection
318 */
319 _PUBLIC_ NTSTATUS dcerpc_epm_map_binding(TALLOC_CTX *mem_ctx, struct dcerpc_binding *binding,
320                                 const struct ndr_interface_table *table, struct tevent_context *ev,
321                                 struct loadparm_context *lp_ctx)
322 {
323         struct composite_context *c;
324
325         c = dcerpc_epm_map_binding_send(mem_ctx, binding, table, ev, lp_ctx);
326         return dcerpc_epm_map_binding_recv(c);
327 }
328
329
330 struct pipe_auth_state {
331         struct dcerpc_pipe *pipe;
332         struct dcerpc_binding *binding;
333         const struct ndr_interface_table *table;
334         struct loadparm_context *lp_ctx;
335         struct cli_credentials *credentials;
336 };
337
338
339 static void continue_auth_schannel(struct composite_context *ctx);
340 static void continue_auth(struct composite_context *ctx);
341 static void continue_auth_none(struct composite_context *ctx);
342 static void continue_ntlmssp_connection(struct composite_context *ctx);
343 static void continue_spnego_after_wrong_pass(struct composite_context *ctx);
344
345
346 /*
347   Stage 2 of pipe_auth: Receive result of schannel bind request
348 */
349 static void continue_auth_schannel(struct composite_context *ctx)
350 {
351         struct composite_context *c = talloc_get_type(ctx->async.private_data,
352                                                       struct composite_context);
353
354         c->status = dcerpc_bind_auth_schannel_recv(ctx);
355         if (!composite_is_ok(c)) return;
356
357         composite_done(c);
358 }
359
360
361 /*
362   Stage 2 of pipe_auth: Receive result of authenticated bind request
363 */
364 static void continue_auth(struct composite_context *ctx)
365 {
366         struct composite_context *c = talloc_get_type(ctx->async.private_data,
367                                                       struct composite_context);
368
369         c->status = dcerpc_bind_auth_recv(ctx);
370         if (!composite_is_ok(c)) return;
371         
372         composite_done(c);
373 }
374 /*
375   Stage 2 of pipe_auth: Receive result of authenticated bind request, but handle fallbacks:
376   SPNEGO -> NTLMSSP
377 */
378 static void continue_auth_auto(struct composite_context *ctx)
379 {
380         struct composite_context *c = talloc_get_type(ctx->async.private_data,
381                                                       struct composite_context);
382         struct pipe_auth_state *s = talloc_get_type(c->private_data, struct pipe_auth_state);
383         struct composite_context *sec_conn_req;
384
385         c->status = dcerpc_bind_auth_recv(ctx);
386         if (NT_STATUS_EQUAL(c->status, NT_STATUS_INVALID_PARAMETER)) {
387                 /*
388                  * Retry with NTLMSSP auth as fallback
389                  * send a request for secondary rpc connection
390                  */
391                 sec_conn_req = dcerpc_secondary_connection_send(s->pipe,
392                                                                 s->binding);
393                 composite_continue(c, sec_conn_req, continue_ntlmssp_connection, c);
394                 return;
395         } else if (NT_STATUS_EQUAL(c->status, NT_STATUS_LOGON_FAILURE)) {
396                 if (cli_credentials_wrong_password(s->credentials)) {
397                         /*
398                          * Retry SPNEGO with a better password
399                          * send a request for secondary rpc connection
400                          */
401                         sec_conn_req = dcerpc_secondary_connection_send(s->pipe,
402                                                                         s->binding);
403                         composite_continue(c, sec_conn_req, continue_spnego_after_wrong_pass, c);
404                         return;
405                 }
406         }
407
408         if (!composite_is_ok(c)) return;
409
410         composite_done(c);
411 }
412
413 /*
414   Stage 3 of pipe_auth (fallback to NTLMSSP case): Receive secondary
415   rpc connection (the first one can't be used any more, due to the
416   bind nak) and perform authenticated bind request
417 */
418 static void continue_ntlmssp_connection(struct composite_context *ctx)
419 {
420         struct composite_context *c;
421         struct pipe_auth_state *s;
422         struct composite_context *auth_req;
423         struct dcerpc_pipe *p2;
424         void *pp;
425
426         c = talloc_get_type(ctx->async.private_data, struct composite_context);
427         s = talloc_get_type(c->private_data, struct pipe_auth_state);
428
429         /* receive secondary rpc connection */
430         c->status = dcerpc_secondary_connection_recv(ctx, &p2);
431         if (!composite_is_ok(c)) return;
432
433
434         /* this is a rather strange situation. When
435            we come into the routine, s is a child of s->pipe, and
436            when we created p2 above, it also became a child of
437            s->pipe.
438
439            Now we want p2 to be a parent of s->pipe, and we want s to
440            be a parent of both of them! If we don't do this very
441            carefully we end up creating a talloc loop
442         */
443
444         /* we need the new contexts to hang off the same context
445            that s->pipe is on, but the only way to get that is
446            via talloc_parent() */
447         pp = talloc_parent(s->pipe);
448
449         /* promote s to be at the top */
450         talloc_steal(pp, s);
451
452         /* and put p2 under s */
453         talloc_steal(s, p2);
454
455         /* now put s->pipe under p2 */
456         talloc_steal(p2, s->pipe);
457
458         s->pipe = p2;
459
460         /* initiate a authenticated bind */
461         auth_req = dcerpc_bind_auth_send(c, s->pipe, s->table,
462                                          s->credentials, 
463                                          lp_gensec_settings(c, s->lp_ctx),
464                                          DCERPC_AUTH_TYPE_NTLMSSP,
465                                          dcerpc_auth_level(s->pipe->conn),
466                                          s->table->authservices->names[0]);
467         composite_continue(c, auth_req, continue_auth, c);
468 }
469
470 /*
471   Stage 3 of pipe_auth (retry on wrong password): Receive secondary
472   rpc connection (the first one can't be used any more, due to the
473   bind nak) and perform authenticated bind request
474 */
475 static void continue_spnego_after_wrong_pass(struct composite_context *ctx)
476 {
477         struct composite_context *c;
478         struct pipe_auth_state *s;
479         struct composite_context *auth_req;
480         struct dcerpc_pipe *p2;
481
482         c = talloc_get_type(ctx->async.private_data, struct composite_context);
483         s = talloc_get_type(c->private_data, struct pipe_auth_state);
484
485         /* receive secondary rpc connection */
486         c->status = dcerpc_secondary_connection_recv(ctx, &p2);
487         if (!composite_is_ok(c)) return;
488
489         talloc_steal(s, p2);
490         talloc_steal(p2, s->pipe);
491         s->pipe = p2;
492
493         /* initiate a authenticated bind */
494         auth_req = dcerpc_bind_auth_send(c, s->pipe, s->table,
495                                          s->credentials, 
496                                          lp_gensec_settings(c, s->lp_ctx), 
497                                          DCERPC_AUTH_TYPE_SPNEGO,
498                                          dcerpc_auth_level(s->pipe->conn),
499                                          s->table->authservices->names[0]);
500         composite_continue(c, auth_req, continue_auth, c);
501 }
502
503
504 /*
505   Stage 2 of pipe_auth: Receive result of non-authenticated bind request
506 */
507 static void continue_auth_none(struct composite_context *ctx)
508 {
509         struct composite_context *c = talloc_get_type(ctx->async.private_data,
510                                                       struct composite_context);
511
512         c->status = dcerpc_bind_auth_none_recv(ctx);
513         if (!composite_is_ok(c)) return;
514         
515         composite_done(c);
516 }
517
518
519 /*
520   Request to perform an authenticated bind if required. Authentication
521   is determined using credentials passed and binding flags.
522 */
523 struct composite_context *dcerpc_pipe_auth_send(struct dcerpc_pipe *p, 
524                                                 struct dcerpc_binding *binding,
525                                                 const struct ndr_interface_table *table,
526                                                 struct cli_credentials *credentials,
527                                                 struct loadparm_context *lp_ctx)
528 {
529         struct composite_context *c;
530         struct pipe_auth_state *s;
531         struct composite_context *auth_schannel_req;
532         struct composite_context *auth_req;
533         struct composite_context *auth_none_req;
534         struct dcerpc_connection *conn;
535         uint8_t auth_type;
536
537         /* composite context allocation and setup */
538         c = composite_create(p, p->conn->event_ctx);
539         if (c == NULL) return NULL;
540
541         s = talloc_zero(c, struct pipe_auth_state);
542         if (composite_nomem(s, c)) return c;
543         c->private_data = s;
544
545         /* store parameters in state structure */
546         s->binding      = binding;
547         s->table        = table;
548         s->credentials  = credentials;
549         s->pipe         = p;
550         s->lp_ctx       = lp_ctx;
551
552         conn = s->pipe->conn;
553         conn->flags = binding->flags;
554
555         if (DEBUGLVL(100)) {
556                 conn->flags |= DCERPC_DEBUG_PRINT_BOTH;
557         }
558         
559         /* remember the binding string for possible secondary connections */
560         conn->binding_string = dcerpc_binding_string(p, binding);
561
562         if (cli_credentials_is_anonymous(s->credentials)) {
563                 auth_none_req = dcerpc_bind_auth_none_send(c, s->pipe, s->table);
564                 composite_continue(c, auth_none_req, continue_auth_none, c);
565                 return c;
566         }
567
568         if ((binding->flags & DCERPC_SCHANNEL) &&
569             !cli_credentials_get_netlogon_creds(s->credentials)) {
570                 /* If we don't already have netlogon credentials for
571                  * the schannel bind, then we have to get these
572                  * first */
573                 auth_schannel_req = dcerpc_bind_auth_schannel_send(c, s->pipe, s->table,
574                                                                    s->credentials, s->lp_ctx,
575                                                                    dcerpc_auth_level(conn));
576                 composite_continue(c, auth_schannel_req, continue_auth_schannel, c);
577                 return c;
578         }
579
580         /*
581          * we rely on the already authenticated CIFS connection
582          * if not doing sign or seal
583          */
584         if (conn->transport.transport == NCACN_NP &&
585             !(s->binding->flags & (DCERPC_SIGN|DCERPC_SEAL))) {
586                 auth_none_req = dcerpc_bind_auth_none_send(c, s->pipe, s->table);
587                 composite_continue(c, auth_none_req, continue_auth_none, c);
588                 return c;
589         }
590
591
592         /* Perform an authenticated DCE-RPC bind
593          */
594         if (!(conn->flags & (DCERPC_SIGN|DCERPC_SEAL))) {
595                 /*
596                   we are doing an authenticated connection,
597                   but not using sign or seal. We must force
598                   the CONNECT dcerpc auth type as a NONE auth
599                   type doesn't allow authentication
600                   information to be passed.
601                 */
602                 conn->flags |= DCERPC_CONNECT;
603         }
604
605         if (s->binding->flags & DCERPC_AUTH_SPNEGO) {
606                 auth_type = DCERPC_AUTH_TYPE_SPNEGO;
607
608         } else if (s->binding->flags & DCERPC_AUTH_KRB5) {
609                 auth_type = DCERPC_AUTH_TYPE_KRB5;
610
611         } else if (s->binding->flags & DCERPC_SCHANNEL) {
612                 auth_type = DCERPC_AUTH_TYPE_SCHANNEL;
613
614         } else if (s->binding->flags & DCERPC_AUTH_NTLM) {
615                 auth_type = DCERPC_AUTH_TYPE_NTLMSSP;
616
617         } else {
618                 /* try SPNEGO with fallback to NTLMSSP */
619                 auth_req = dcerpc_bind_auth_send(c, s->pipe, s->table,
620                                                  s->credentials, 
621                                                  lp_gensec_settings(c, s->lp_ctx), 
622                                                  DCERPC_AUTH_TYPE_SPNEGO,
623                                                  dcerpc_auth_level(conn),
624                                                  s->table->authservices->names[0]);
625                 composite_continue(c, auth_req, continue_auth_auto, c);
626                 return c;
627         }
628
629         auth_req = dcerpc_bind_auth_send(c, s->pipe, s->table,
630                                          s->credentials, 
631                                          lp_gensec_settings(c, s->lp_ctx), 
632                                          auth_type,
633                                          dcerpc_auth_level(conn),
634                                          s->table->authservices->names[0]);
635         composite_continue(c, auth_req, continue_auth, c);
636         return c;
637 }
638
639
640 /*
641   Receive result of authenticated bind request on dcerpc pipe
642
643   This returns *p, which may be different to the one originally
644   supllied, as it rebinds to a new pipe due to authentication fallback
645
646 */
647 NTSTATUS dcerpc_pipe_auth_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, 
648                                struct dcerpc_pipe **p)
649 {
650         NTSTATUS status;
651
652         struct pipe_auth_state *s = talloc_get_type(c->private_data,
653                                                     struct pipe_auth_state);
654         status = composite_wait(c);
655         if (!NT_STATUS_IS_OK(status)) {
656                 char *uuid_str = GUID_string(s->pipe, &s->table->syntax_id.uuid);
657                 DEBUG(0, ("Failed to bind to uuid %s - %s\n", uuid_str, nt_errstr(status)));
658                 talloc_free(uuid_str);
659         } else {
660                 talloc_steal(mem_ctx, s->pipe);
661                 *p = s->pipe;
662         }
663
664         talloc_free(c);
665         return status;
666 }
667
668
669 /* 
670    Perform an authenticated bind if needed - sync version
671
672    This may change *p, as it rebinds to a new pipe due to authentication fallback
673 */
674 _PUBLIC_ NTSTATUS dcerpc_pipe_auth(TALLOC_CTX *mem_ctx,
675                           struct dcerpc_pipe **p, 
676                           struct dcerpc_binding *binding,
677                           const struct ndr_interface_table *table,
678                           struct cli_credentials *credentials,
679                           struct loadparm_context *lp_ctx)
680 {
681         struct composite_context *c;
682
683         c = dcerpc_pipe_auth_send(*p, binding, table, credentials, lp_ctx);
684         return dcerpc_pipe_auth_recv(c, mem_ctx, p);
685 }
686
687
688 NTSTATUS dcerpc_generic_session_key(struct dcerpc_connection *c,
689                                     DATA_BLOB *session_key)
690 {
691         /* this took quite a few CPU cycles to find ... */
692         session_key->data = discard_const_p(unsigned char, "SystemLibraryDTC");
693         session_key->length = 16;
694         return NT_STATUS_OK;
695 }
696
697 /*
698   fetch the user session key - may be default (above) or the SMB session key
699
700   The key is always truncated to 16 bytes 
701 */
702 _PUBLIC_ NTSTATUS dcerpc_fetch_session_key(struct dcerpc_pipe *p,
703                                            DATA_BLOB *session_key)
704 {
705         NTSTATUS status;
706         status = p->conn->security_state.session_key(p->conn, session_key);
707         if (!NT_STATUS_IS_OK(status)) {
708                 return status;
709         }
710
711         session_key->length = MIN(session_key->length, 16);
712
713         return NT_STATUS_OK;
714 }
715
716
717 /*
718   log a rpc packet in a format suitable for ndrdump. This is especially useful
719   for sealed packets, where ethereal cannot easily see the contents
720
721   this triggers on a debug level of >= 10
722 */
723 _PUBLIC_ void dcerpc_log_packet(const char *lockdir,
724                                                                 const struct ndr_interface_table *ndr,
725                        uint32_t opnum, uint32_t flags, 
726                        DATA_BLOB *pkt)
727 {
728         const int num_examples = 20;
729         int i;
730
731         if (lockdir == NULL) return;
732
733         for (i=0;i<num_examples;i++) {
734                 char *name=NULL;
735                 asprintf(&name, "%s/rpclog/%s-%u.%d.%s", 
736                          lockdir, ndr->name, opnum, i,
737                          (flags&NDR_IN)?"in":"out");
738                 if (name == NULL) {
739                         return;
740                 }
741                 if (!file_exist(name)) {
742                         if (file_save(name, pkt->data, pkt->length)) {
743                                 DEBUG(10,("Logged rpc packet to %s\n", name));
744                         }
745                         free(name);
746                         break;
747                 }
748                 free(name);
749         }
750 }
751
752
753
754 /*
755   create a secondary context from a primary connection
756
757   this uses dcerpc_alter_context() to create a new dcerpc context_id
758 */
759 _PUBLIC_ NTSTATUS dcerpc_secondary_context(struct dcerpc_pipe *p, 
760                                   struct dcerpc_pipe **pp2,
761                                   const struct ndr_interface_table *table)
762 {
763         NTSTATUS status;
764         struct dcerpc_pipe *p2;
765         
766         p2 = talloc_zero(p, struct dcerpc_pipe);
767         if (p2 == NULL) {
768                 return NT_STATUS_NO_MEMORY;
769         }
770         p2->conn = talloc_reference(p2, p->conn);
771         p2->request_timeout = p->request_timeout;
772
773         p2->context_id = ++p->conn->next_context_id;
774
775         p2->syntax = table->syntax_id;
776
777         p2->transfer_syntax = p->transfer_syntax;
778
779         p2->binding = talloc_reference(p2, p->binding);
780
781         p2->binding_handle = talloc(p2, struct dcerpc_binding_handle);
782         if (p2->binding_handle == NULL) {
783                 talloc_free(p2);
784                 return NT_STATUS_NO_MEMORY;
785         }
786         p2->binding_handle->private_data = p2;
787
788         status = dcerpc_alter_context(p2, p2, &p2->syntax, &p2->transfer_syntax);
789         if (!NT_STATUS_IS_OK(status)) {
790                 talloc_free(p2);
791                 return status;
792         }
793
794         *pp2 = p2;
795
796         return NT_STATUS_OK;
797 }
798
799
800 /*
801   pull an dcerpc_auth structure, taking account of any auth padding in
802   the blob at the end of the structure
803  */
804 NTSTATUS dcerpc_pull_auth_trailer(struct ncacn_packet *pkt,
805                                   TALLOC_CTX *mem_ctx,
806                                   DATA_BLOB *pkt_auth_blob,
807                                   struct dcerpc_auth *auth,
808                                   uint32_t *auth_length,
809                                   bool check_pad)
810 {
811         struct ndr_pull *ndr;
812         enum ndr_err_code ndr_err;
813         uint32_t pad;
814
815         pad = pkt_auth_blob->length - (DCERPC_AUTH_TRAILER_LENGTH + pkt->auth_length);
816
817         /* paranoia check for pad size. This would be caught anyway by
818            the ndr_pull_advance() a few lines down, but it scared
819            Jeremy enough for him to call me, so we might as well check
820            it now, just to prevent someone posting a bogus YouTube
821            video in the future.
822         */
823         if (pad > pkt_auth_blob->length) {
824                 return NT_STATUS_INFO_LENGTH_MISMATCH;
825         }
826
827         *auth_length = pkt_auth_blob->length - pad;
828
829         ndr = ndr_pull_init_blob(pkt_auth_blob, mem_ctx);
830         if (!ndr) {
831                 return NT_STATUS_NO_MEMORY;
832         }
833
834         if (!(pkt->drep[0] & DCERPC_DREP_LE)) {
835                 ndr->flags |= LIBNDR_FLAG_BIGENDIAN;
836         }
837
838         ndr_err = ndr_pull_advance(ndr, pad);
839         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
840                 talloc_free(ndr);
841                 return ndr_map_error2ntstatus(ndr_err);
842         }
843
844         ndr_err = ndr_pull_dcerpc_auth(ndr, NDR_SCALARS|NDR_BUFFERS, auth);
845         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
846                 talloc_free(ndr);
847                 return ndr_map_error2ntstatus(ndr_err);
848         }
849
850         if (check_pad && pad != auth->auth_pad_length) {
851                 DEBUG(1,(__location__ ": WARNING: pad length mismatch. Calculated %u  got %u\n",
852                          (unsigned)pad, (unsigned)auth->auth_pad_length));
853         }
854
855         DEBUG(6,(__location__ ": auth_pad_length %u\n",
856                  (unsigned)auth->auth_pad_length));
857
858         talloc_steal(mem_ctx, auth->credentials.data);
859         talloc_free(ndr);
860
861         return NT_STATUS_OK;
862 }
863
864