summaryrefslogtreecommitdiff
path: root/source4/librpc/rpc/dcerpc.c
blob: aabc71a258fe71163aa60ffc5bbe4f859fd8535a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
/* 
   Unix SMB/CIFS implementation.
   raw dcerpc operations

   Copyright (C) Tim Potter 2003
   Copyright (C) Andrew Tridgell 2003-2005
   Copyright (C) Jelmer Vernooij 2004-2005
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "includes.h"
#include "dlinklist.h"
#include "lib/events/events.h"
#include "librpc/gen_ndr/ndr_epmapper.h"
#include "librpc/gen_ndr/ndr_dcerpc.h"
#include "librpc/gen_ndr/ndr_misc.h"
#include "libcli/composite/composite.h"

static void dcerpc_ship_next_request(struct dcerpc_connection *c);

static struct dcerpc_interface_list *dcerpc_pipes = NULL;

/*
  register a dcerpc client interface
*/
NTSTATUS librpc_register_interface(const struct dcerpc_interface_table *interface)
{
	struct dcerpc_interface_list *l = talloc(talloc_autofree_context(),
						   struct dcerpc_interface_list);
		
	if (idl_iface_by_name (interface->name) != NULL) {
		DEBUG(0, ("Attempt to register interface %s twice\n", interface->name));
		return NT_STATUS_OBJECT_NAME_COLLISION;
	}
	l->table = interface;

	DLIST_ADD(dcerpc_pipes, l);
	
  	return NT_STATUS_OK;
}

/*
  return the list of registered dcerpc_pipes
*/
const struct dcerpc_interface_list *librpc_dcerpc_pipes(void)
{
	return dcerpc_pipes;
}

/* destroy a dcerpc connection */
static int dcerpc_connection_destructor(void *ptr)
{
	struct dcerpc_connection *c = ptr;
	if (c->transport.shutdown_pipe) {
		c->transport.shutdown_pipe(c);
	}
	return 0;
}


/* initialise a dcerpc connection. 
   the event context is optional
*/
struct dcerpc_connection *dcerpc_connection_init(TALLOC_CTX *mem_ctx, 
						 struct event_context *ev)
{
	struct dcerpc_connection *c;

	c = talloc_zero(mem_ctx, struct dcerpc_connection);
	if (!c) {
		return NULL;
	}

	if (ev == NULL) {
		ev = event_context_init(c);
		if (ev == NULL) {
			talloc_free(c);
			return NULL;
		}
	}

	c->event_ctx = ev;
	c->call_id = 1;
	c->security_state.auth_info = NULL;
	c->security_state.session_key = dcerpc_generic_session_key;
	c->security_state.generic_state = NULL;
	c->binding_string = NULL;
	c->flags = 0;
	c->srv_max_xmit_frag = 0;
	c->srv_max_recv_frag = 0;
	c->pending = NULL;

	talloc_set_destructor(c, dcerpc_connection_destructor);

	return c;
}

/* initialise a dcerpc pipe. */
struct dcerpc_pipe *dcerpc_pipe_init(TALLOC_CTX *mem_ctx, struct event_context *ev)
{
	struct dcerpc_pipe *p;

	p = talloc(mem_ctx, struct dcerpc_pipe);
	if (!p) {
		return NULL;
	}

	p->conn = dcerpc_connection_init(p, ev);
	if (p->conn == NULL) {
		talloc_free(p);
		return NULL;
	}

	p->last_fault_code = 0;
	p->context_id = 0;
	p->request_timeout = DCERPC_REQUEST_TIMEOUT;

	ZERO_STRUCT(p->syntax);
	ZERO_STRUCT(p->transfer_syntax);

	return p;
}


/* 
   choose the next call id to use
*/
static uint32_t next_call_id(struct dcerpc_connection *c)
{
	c->call_id++;
	if (c->call_id == 0) {
		c->call_id++;
	}
	return c->call_id;
}

/* we need to be able to get/set the fragment length without doing a full
   decode */
void dcerpc_set_frag_length(DATA_BLOB *blob, uint16_t v)
{
	if (CVAL(blob->data,DCERPC_DREP_OFFSET) & DCERPC_DREP_LE) {
		SSVAL(blob->data, DCERPC_FRAG_LEN_OFFSET, v);
	} else {
		RSSVAL(blob->data, DCERPC_FRAG_LEN_OFFSET, v);
	}
}

uint16_t dcerpc_get_frag_length(const DATA_BLOB *blob)
{
	if (CVAL(blob->data,DCERPC_DREP_OFFSET) & DCERPC_DREP_LE) {
		return SVAL(blob->data, DCERPC_FRAG_LEN_OFFSET);
	} else {
		return RSVAL(blob->data, DCERPC_FRAG_LEN_OFFSET);
	}
}

void dcerpc_set_auth_length(DATA_BLOB *blob, uint16_t v)
{
	if (CVAL(blob->data,DCERPC_DREP_OFFSET) & DCERPC_DREP_LE) {
		SSVAL(blob->data, DCERPC_AUTH_LEN_OFFSET, v);
	} else {
		RSSVAL(blob->data, DCERPC_AUTH_LEN_OFFSET, v);
	}
}


/*
  setup for a ndr pull, also setting up any flags from the binding string
*/
static struct ndr_pull *ndr_pull_init_flags(struct dcerpc_connection *c, 
					    DATA_BLOB *blob, TALLOC_CTX *mem_ctx)
{
	struct ndr_pull *ndr = ndr_pull_init_blob(blob, mem_ctx);

	if (ndr == NULL) return ndr;

	if (c->flags & DCERPC_DEBUG_PAD_CHECK) {
		ndr->flags |= LIBNDR_FLAG_PAD_CHECK;
	}

	if (c->flags & DCERPC_NDR_REF_ALLOC) {
		ndr->flags |= LIBNDR_FLAG_REF_ALLOC;
	}

	return ndr;
}

/* 
   parse a data blob into a ncacn_packet structure. This handles both
   input and output packets
*/
static NTSTATUS ncacn_pull(struct dcerpc_connection *c, DATA_BLOB *blob, TALLOC_CTX *mem_ctx, 
			    struct ncacn_packet *pkt)
{
	struct ndr_pull *ndr;

	ndr = ndr_pull_init_flags(c, blob, mem_ctx);
	if (!ndr) {
		return NT_STATUS_NO_MEMORY;
	}

	if (! (CVAL(blob->data, DCERPC_DREP_OFFSET) & DCERPC_DREP_LE)) {
		ndr->flags |= LIBNDR_FLAG_BIGENDIAN;
	}

	return ndr_pull_ncacn_packet(ndr, NDR_SCALARS|NDR_BUFFERS, pkt);
}

/*
  generate a CONNECT level verifier
*/
static NTSTATUS dcerpc_connect_verifier(TALLOC_CTX *mem_ctx, DATA_BLOB *blob)
{
	*blob = data_blob_talloc(mem_ctx, NULL, 16);
	if (blob->data == NULL) {
		return NT_STATUS_NO_MEMORY;
	}
	SIVAL(blob->data, 0, 1);
	memset(blob->data+4, 0, 12);
	return NT_STATUS_OK;
}

/*
  check a CONNECT level verifier
*/
static NTSTATUS dcerpc_check_connect_verifier(DATA_BLOB *blob)
{
	if (blob->length != 16 ||
	    IVAL(blob->data, 0) != 1) {
		return NT_STATUS_ACCESS_DENIED;
	}
	return NT_STATUS_OK;
}

/* 
   parse the authentication information on a dcerpc response packet
*/
static NTSTATUS ncacn_pull_request_auth(struct dcerpc_connection *c, TALLOC_CTX *mem_ctx, 
					DATA_BLOB *raw_packet,
					struct ncacn_packet *pkt)
{
	struct ndr_pull *ndr;
	NTSTATUS status;
	struct dcerpc_auth auth;
	DATA_BLOB auth_blob;

	if (pkt->auth_length == 0 &&
	    c->security_state.auth_info->auth_level == DCERPC_AUTH_LEVEL_CONNECT) {
		return NT_STATUS_OK;
	}

	auth_blob.length = 8 + pkt->auth_length;

	/* check for a valid length */
	if (pkt->u.response.stub_and_verifier.length < auth_blob.length) {
		return NT_STATUS_INFO_LENGTH_MISMATCH;
	}

	auth_blob.data = 
		pkt->u.response.stub_and_verifier.data + 
		pkt->u.response.stub_and_verifier.length - auth_blob.length;
	pkt->u.response.stub_and_verifier.length -= auth_blob.length;

	/* pull the auth structure */
	ndr = ndr_pull_init_flags(c, &auth_blob, mem_ctx);
	if (!ndr) {
		return NT_STATUS_NO_MEMORY;
	}

	if (!(pkt->drep[0] & DCERPC_DREP_LE)) {
		ndr->flags |= LIBNDR_FLAG_BIGENDIAN;
	}

	status = ndr_pull_dcerpc_auth(ndr, NDR_SCALARS|NDR_BUFFERS, &auth);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	
	
	/* check signature or unseal the packet */
	switch (c->security_state.auth_info->auth_level) {
	case DCERPC_AUTH_LEVEL_PRIVACY:
		status = gensec_unseal_packet(c->security_state.generic_state, 
					      mem_ctx, 
					      raw_packet->data + DCERPC_REQUEST_LENGTH,
					      pkt->u.response.stub_and_verifier.length, 
					      raw_packet->data,
					      raw_packet->length - auth.credentials.length,
					      &auth.credentials);
		memcpy(pkt->u.response.stub_and_verifier.data,
		       raw_packet->data + DCERPC_REQUEST_LENGTH,
		       pkt->u.response.stub_and_verifier.length);
		break;
		
	case DCERPC_AUTH_LEVEL_INTEGRITY:
		status = gensec_check_packet(c->security_state.generic_state, 
					     mem_ctx, 
					     pkt->u.response.stub_and_verifier.data, 
					     pkt->u.response.stub_and_verifier.length, 
					     raw_packet->data,
					     raw_packet->length - auth.credentials.length,
					     &auth.credentials);
		break;

	case DCERPC_AUTH_LEVEL_CONNECT:
		status = dcerpc_check_connect_verifier(&auth.credentials);
		break;

	case DCERPC_AUTH_LEVEL_NONE:
		break;

	default:
		status = NT_STATUS_INVALID_LEVEL;
		break;
	}
	
	/* remove the indicated amount of paddiing */
	if (pkt->u.response.stub_and_verifier.length < auth.auth_pad_length) {
		return NT_STATUS_INFO_LENGTH_MISMATCH;
	}
	pkt->u.response.stub_and_verifier.length -= auth.auth_pad_length;

	return status;
}


/* 
   push a dcerpc request packet into a blob, possibly signing it.
*/
static NTSTATUS ncacn_push_request_sign(struct dcerpc_connection *c, 
					 DATA_BLOB *blob, TALLOC_CTX *mem_ctx, 
					 struct ncacn_packet *pkt)
{
	NTSTATUS status;
	struct ndr_push *ndr;
	DATA_BLOB creds2;
	size_t payload_length;

	/* non-signed packets are simpler */
	if (!c->security_state.auth_info || 
	    !c->security_state.generic_state) {
		return ncacn_push_auth(blob, mem_ctx, pkt, c->security_state.auth_info);
	}

	ndr = ndr_push_init_ctx(mem_ctx);
	if (!ndr) {
		return NT_STATUS_NO_MEMORY;
	}

	if (c->flags & DCERPC_PUSH_BIGENDIAN) {
		ndr->flags |= LIBNDR_FLAG_BIGENDIAN;
	}

	if (pkt->pfc_flags & DCERPC_PFC_FLAG_ORPC) {
		ndr->flags |= LIBNDR_FLAG_OBJECT_PRESENT;
	}

	status = ndr_push_ncacn_packet(ndr, NDR_SCALARS|NDR_BUFFERS, pkt);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}

	/* pad to 16 byte multiple in the payload portion of the
	   packet. This matches what w2k3 does */
	c->security_state.auth_info->auth_pad_length = 
		(16 - (pkt->u.request.stub_and_verifier.length & 15)) & 15;
	ndr_push_zero(ndr, c->security_state.auth_info->auth_pad_length);

	payload_length = pkt->u.request.stub_and_verifier.length + 
		c->security_state.auth_info->auth_pad_length;

	/* sign or seal the packet */
	switch (c->security_state.auth_info->auth_level) {
	case DCERPC_AUTH_LEVEL_PRIVACY:
	case DCERPC_AUTH_LEVEL_INTEGRITY:
		c->security_state.auth_info->credentials
			= data_blob_talloc(mem_ctx, NULL, gensec_sig_size(c->security_state.generic_state, 
									  payload_length));
		data_blob_clear(&c->security_state.auth_info->credentials);
		break;

	case DCERPC_AUTH_LEVEL_CONNECT:
		status = dcerpc_connect_verifier(mem_ctx, &c->security_state.auth_info->credentials);
		break;
		
	case DCERPC_AUTH_LEVEL_NONE:
		c->security_state.auth_info->credentials = data_blob(NULL, 0);
		break;
		
	default:
		status = NT_STATUS_INVALID_LEVEL;
		break;
	}
	
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}	

	/* add the auth verifier */
	status = ndr_push_dcerpc_auth(ndr, NDR_SCALARS|NDR_BUFFERS, c->security_state.auth_info);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}

	/* extract the whole packet as a blob */
	*blob = ndr_push_blob(ndr);

	/* fill in the fragment length and auth_length, we can't fill
	   in these earlier as we don't know the signature length (it
	   could be variable length) */
	dcerpc_set_frag_length(blob, blob->length);
	dcerpc_set_auth_length(blob, c->security_state.auth_info->credentials.length);

	/* sign or seal the packet */
	switch (c->security_state.auth_info->auth_level) {
	case DCERPC_AUTH_LEVEL_PRIVACY:
		status = gensec_seal_packet(c->security_state.generic_state, 
					    mem_ctx, 
					    blob->data + DCERPC_REQUEST_LENGTH, 
					    payload_length,
					    blob->data,
					    blob->length - 
					    c->security_state.auth_info->credentials.length,
					    &creds2);
		if (!NT_STATUS_IS_OK(status)) {
			return status;
		}
		memcpy(blob->data + blob->length - creds2.length, creds2.data, creds2.length);
		break;

	case DCERPC_AUTH_LEVEL_INTEGRITY:
		status = gensec_sign_packet(c->security_state.generic_state, 
					    mem_ctx, 
					    blob->data + DCERPC_REQUEST_LENGTH, 
					    payload_length, 
					    blob->data,
					    blob->length - 
					    c->security_state.auth_info->credentials.length,
					    &creds2);
		if (!NT_STATUS_IS_OK(status)) {
			return status;
		}
		memcpy(blob->data + blob->length - creds2.length, creds2.data, creds2.length);
		break;

	case DCERPC_AUTH_LEVEL_CONNECT:
		break;

	case DCERPC_AUTH_LEVEL_NONE:
		c->security_state.auth_info->credentials = data_blob(NULL, 0);
		break;

	default:
		status = NT_STATUS_INVALID_LEVEL;
		break;
	}

	data_blob_free(&c->security_state.auth_info->credentials);

	return NT_STATUS_OK;
}


/* 
   fill in the fixed values in a dcerpc header 
*/
static void init_ncacn_hdr(struct dcerpc_connection *c, struct ncacn_packet *pkt)
{
	pkt->rpc_vers = 5;
	pkt->rpc_vers_minor = 0;
	if (c->flags & DCERPC_PUSH_BIGENDIAN) {
		pkt->drep[0] = 0;
	} else {
		pkt->drep[0] = DCERPC_DREP_LE;
	}
	pkt->drep[1] = 0;
	pkt->drep[2] = 0;
	pkt->drep[3] = 0;
}

/*
  map a bind nak reason to a NTSTATUS
*/
static NTSTATUS dcerpc_map_reason(uint16_t reason)
{
	switch (reason) {
	case DCERPC_BIND_REASON_ASYNTAX:
		return NT_STATUS_RPC_UNSUPPORTED_NAME_SYNTAX;
	}
	return NT_STATUS_UNSUCCESSFUL;
}

/*
  mark the dcerpc connection dead. All outstanding requests get an error
*/
static void dcerpc_connection_dead(struct dcerpc_connection *conn, NTSTATUS status)
{
	/* all pending requests get the error */
	while (conn->pending) {
		struct rpc_request *req = conn->pending;
		req->state = RPC_REQUEST_DONE;
		req->status = status;
		DLIST_REMOVE(conn->pending, req);
		if (req->async.callback) {
			req->async.callback(req);
		}
	}	

	if (conn->bind_private) {
		/* a bind was in flight - fail it */
		struct composite_context *c = talloc_get_type(conn->bind_private, struct composite_context);
		composite_error(c, status);		
	}

	if (conn->alter_private) {
		/* a alter context was in flight - fail it */
		struct composite_context *c = talloc_get_type(conn->alter_private, struct composite_context);
		composite_error(c, status);		
	}
}

/*
  forward declarations of the recv_data handlers for the 3 types of packets we need
  to handle
*/
static void dcerpc_bind_recv_data(struct dcerpc_connection *conn, struct ncacn_packet *pkt);
static void dcerpc_alter_recv_data(struct dcerpc_connection *conn, struct ncacn_packet *pkt);
static void dcerpc_request_recv_data(struct dcerpc_connection *c, 
				     DATA_BLOB *raw_packet, struct ncacn_packet *pkt);

/*
  receive a dcerpc reply from the transport. Here we work out what
  type of reply it is (normal request, bind or alter context) and
  dispatch to the appropriate handler
*/
static void dcerpc_recv_data(struct dcerpc_connection *conn, DATA_BLOB *blob, NTSTATUS status)
{
	struct ncacn_packet pkt;

	if (NT_STATUS_IS_OK(status) && blob->length == 0) {
		status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
	}

	/* the transport may be telling us of a severe error, such as
	   a dropped socket */
	if (!NT_STATUS_IS_OK(status)) {
		data_blob_free(blob);
		dcerpc_connection_dead(conn, status);
		return;
	}

	/* parse the basic packet to work out what type of response this is */
	status = ncacn_pull(conn, blob, blob->data, &pkt);
	if (!NT_STATUS_IS_OK(status)) {
		data_blob_free(blob);
		dcerpc_connection_dead(conn, status);
	}

	switch (pkt.ptype) {
	case DCERPC_PKT_BIND_NAK:
	case DCERPC_PKT_BIND_ACK:
		if (conn->bind_private) {
			talloc_steal(conn->bind_private, blob->data);
			dcerpc_bind_recv_data(conn, &pkt);
		}
		break;

	case DCERPC_PKT_ALTER_RESP:
		if (conn->alter_private) {
			talloc_steal(conn->alter_private, blob->data);
			dcerpc_alter_recv_data(conn, &pkt);
		}
		break;

	default:
		/* assume its an ordinary request */
		dcerpc_request_recv_data(conn, blob, &pkt);
		break;
	}
}


/*
  Receive a bind reply from the transport
*/
static void dcerpc_bind_recv_data(struct dcerpc_connection *conn, struct ncacn_packet *pkt)
{
	struct composite_context *c;
	struct dcerpc_pipe *pipe;

	c = talloc_get_type(conn->bind_private, struct composite_context);
	pipe = talloc_get_type(c->private_data, struct dcerpc_pipe);

	/* mark the connection as not waiting for a bind reply */
	conn->bind_private = NULL;

	if (pkt->ptype == DCERPC_PKT_BIND_NAK) {
		DEBUG(2,("dcerpc: bind_nak reason %d\n",
			 pkt->u.bind_nak.reject_reason));
		composite_error(c, dcerpc_map_reason(pkt->u.bind_nak.
						     reject_reason));
		return;
	}

	if ((pkt->ptype != DCERPC_PKT_BIND_ACK) ||
	    (pkt->u.bind_ack.num_results == 0) ||
	    (pkt->u.bind_ack.ctx_list[0].result != 0)) {
		composite_error(c, NT_STATUS_UNSUCCESSFUL);
		return;
	}

	conn->srv_max_xmit_frag = pkt->u.bind_ack.max_xmit_frag;
	conn->srv_max_recv_frag = pkt->u.bind_ack.max_recv_frag;

	/* the bind_ack might contain a reply set of credentials */
	if (conn->security_state.auth_info &&
	    pkt->u.bind_ack.auth_info.length) {
		c->status = ndr_pull_struct_blob(
			&pkt->u.bind_ack.auth_info, conn,
			conn->security_state.auth_info,
			(ndr_pull_flags_fn_t)ndr_pull_dcerpc_auth);
		if (!composite_is_ok(c)) return;
	}

	composite_done(c);
}

/*
  handle timeouts of dcerpc bind and alter context requests
*/
static void bind_timeout_handler(struct event_context *ev,
				 struct timed_event *te, 
				 struct timeval t, void *private)
{
	struct composite_context *ctx =
		talloc_get_type(private, struct composite_context);
	struct dcerpc_pipe *pipe = talloc_get_type(ctx->private_data, struct dcerpc_pipe);

	SMB_ASSERT(pipe->conn->bind_private != NULL);
	pipe->conn->bind_private = NULL;
	composite_error(ctx, NT_STATUS_IO_TIMEOUT);
}

/*
  send a async dcerpc bind request
*/
struct composite_context *dcerpc_bind_send(struct dcerpc_pipe *p,
					   TALLOC_CTX *mem_ctx,
					   const struct dcerpc_syntax_id *syntax,
					   const struct dcerpc_syntax_id *transfer_syntax)
{
	struct composite_context *c;
	struct ncacn_packet pkt;
	DATA_BLOB blob;

	c = talloc_zero(mem_ctx, struct composite_context);
	if (c == NULL) return NULL;

	c->state = COMPOSITE_STATE_IN_PROGRESS;
	c->private_data = p;
	c->event_ctx = p->conn->event_ctx;

	p->syntax = *syntax;
	p->transfer_syntax = *transfer_syntax;

	init_ncacn_hdr(p->conn, &pkt);

	pkt.ptype = DCERPC_PKT_BIND;
	pkt.pfc_flags = DCERPC_PFC_FLAG_FIRST | DCERPC_PFC_FLAG_LAST;
	pkt.call_id = p->conn->call_id;
	pkt.auth_length = 0;

	pkt.u.bind.max_xmit_frag = 5840;
	pkt.u.bind.max_recv_frag = 5840;
	pkt.u.bind.assoc_group_id = 0;
	pkt.u.bind.num_contexts = 1;
	pkt.u.bind.ctx_list =
		talloc_array(mem_ctx, struct dcerpc_ctx_list, 1);
	if (pkt.u.bind.ctx_list == NULL) {
		c->status = NT_STATUS_NO_MEMORY;
		goto failed;
	}
	pkt.u.bind.ctx_list[0].context_id = p->context_id;
	pkt.u.bind.ctx_list[0].num_transfer_syntaxes = 1;
	pkt.u.bind.ctx_list[0].abstract_syntax = p->syntax;
	pkt.u.bind.ctx_list[0].transfer_syntaxes = &p->transfer_syntax;
	pkt.u.bind.auth_info = data_blob(NULL, 0);

	/* construct the NDR form of the packet */
	c->status = ncacn_push_auth(&blob, c, &pkt,
				    p->conn->security_state.auth_info);
	if (!NT_STATUS_IS_OK(c->status)) {
		goto failed;
	}

	p->conn->transport.recv_data = dcerpc_recv_data;
	p->conn->bind_private = c;

	c->status = p->conn->transport.send_request(p->conn, &blob,
						    True);
	if (!NT_STATUS_IS_OK(c->status)) {
		goto failed;
	}

	event_add_timed(c->event_ctx, c,
			timeval_current_ofs(DCERPC_REQUEST_TIMEOUT, 0),
			bind_timeout_handler, c);

	return c;

 failed:
	composite_trigger_error(c);
	return c;
}

/*
  recv side of async dcerpc bind request
*/
NTSTATUS dcerpc_bind_recv(struct composite_context *ctx)
{
	NTSTATUS result = composite_wait(ctx);
	talloc_free(ctx);
	return result;
}

/* 
   perform a bind using the given syntax 

   the auth_info structure is updated with the reply authentication info
   on success
*/
NTSTATUS dcerpc_bind(struct dcerpc_pipe *p, 
		     TALLOC_CTX *mem_ctx,
		     const struct dcerpc_syntax_id *syntax,
		     const struct dcerpc_syntax_id *transfer_syntax)
{
	struct composite_context *creq;
	creq = dcerpc_bind_send(p, mem_ctx, syntax, transfer_syntax);
	return dcerpc_bind_recv(creq);
}

/* 
   perform a continued bind (and auth3)
*/
NTSTATUS dcerpc_auth3(struct dcerpc_connection *c, 
		      TALLOC_CTX *mem_ctx)
{
	struct ncacn_packet pkt;
	NTSTATUS status;
	DATA_BLOB blob;

	init_ncacn_hdr(c, &pkt);

	pkt.ptype = DCERPC_PKT_AUTH3;
	pkt.pfc_flags = DCERPC_PFC_FLAG_FIRST | DCERPC_PFC_FLAG_LAST;
	pkt.call_id = next_call_id(c);
	pkt.auth_length = 0;
	pkt.u.auth3._pad = 0;
	pkt.u.auth3.auth_info = data_blob(NULL, 0);

	/* construct the NDR form of the packet */
	status = ncacn_push_auth(&blob, mem_ctx, &pkt, c->security_state.auth_info);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}

	/* send it on its way */
	status = c->transport.send_request(c, &blob, False);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}

	return status;	
}


/*
  return the rpc syntax and transfer syntax given the pipe uuid and version
*/
NTSTATUS dcerpc_init_syntaxes(const char *uuid, uint_t version,
			      struct dcerpc_syntax_id *syntax,
			      struct dcerpc_syntax_id *transfer_syntax)
{
	NTSTATUS status;

	status = GUID_from_string(uuid, &syntax->uuid);
	if (!NT_STATUS_IS_OK(status)) return status;

	syntax->if_version = version;

	status = GUID_from_string(NDR_GUID, &transfer_syntax->uuid);
	if (!NT_STATUS_IS_OK(status)) return status;

	transfer_syntax->if_version = NDR_GUID_VERSION;

	return NT_STATUS_OK;
}

/* perform a dcerpc bind, using the uuid as the key */
NTSTATUS dcerpc_bind_byuuid(struct dcerpc_pipe *p, 
			    TALLOC_CTX *mem_ctx,
			    const char *uuid, uint_t version)
{
	struct dcerpc_syntax_id syntax;
	struct dcerpc_syntax_id transfer_syntax;
	NTSTATUS status;

	status = dcerpc_init_syntaxes(uuid, version,
				      &syntax, &transfer_syntax);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(2,("Invalid uuid string in dcerpc_bind_byuuid\n"));
		return status;
	}

	return dcerpc_bind(p, mem_ctx, &syntax, &transfer_syntax);
}


/*
  process a fragment received from the transport layer during a
  request

  This function frees the data 
*/
static void dcerpc_request_recv_data(struct dcerpc_connection *c, 
				     DATA_BLOB *raw_packet, struct ncacn_packet *pkt)
{
	struct rpc_request *req;
	uint_t length;
	NTSTATUS status = NT_STATUS_OK;

	/*
	  if this is an authenticated connection then parse and check
	  the auth info. We have to do this before finding the
	  matching packet, as the request structure might have been
	  removed due to a timeout, but if it has been we still need
	  to run the auth routines so that we don't get the sign/seal
	  info out of step with the server
	*/
	if (c->security_state.auth_info && c->security_state.generic_state &&
	    pkt->ptype == DCERPC_PKT_RESPONSE) {
		status = ncacn_pull_request_auth(c, raw_packet->data, raw_packet, pkt);
	}

	/* find the matching request */
	for (req=c->pending;req;req=req->next) {
		if (pkt->call_id == req->call_id) break;
	}

	if (req == NULL) {
		DEBUG(2,("dcerpc_request: unmatched call_id %u in response packet\n", pkt->call_id));
		data_blob_free(raw_packet);
		return;
	}

	talloc_steal(req, raw_packet->data);

	if (pkt->ptype == DCERPC_PKT_FAULT) {
		DEBUG(5,("rpc fault: %s\n", dcerpc_errstr(c, pkt->u.fault.status)));
		req->fault_code = pkt->u.fault.status;
		req->status = NT_STATUS_NET_WRITE_FAULT;
		goto req_done;
	}

	if (pkt->ptype != DCERPC_PKT_RESPONSE) {
		DEBUG(2,("Unexpected packet type %d in dcerpc response\n",
			 (int)pkt->ptype)); 
		req->fault_code = DCERPC_FAULT_OTHER;
		req->status = NT_STATUS_NET_WRITE_FAULT;
		goto req_done;
	}

	/* now check the status from the auth routines, and if it failed then fail
	   this request accordingly */
	if (!NT_STATUS_IS_OK(status)) {
		req->status = status;
		goto req_done;
	}

	length = pkt->u.response.stub_and_verifier.length;

	if (length > 0) {
		req->payload.data = talloc_realloc(req, 
						   req->payload.data, 
						   uint8_t,
						   req->payload.length + length);
		if (!req->payload.data) {
			req->status = NT_STATUS_NO_MEMORY;
			goto req_done;
		}
		memcpy(req->payload.data+req->payload.length, 
		       pkt->u.response.stub_and_verifier.data, length);
		req->payload.length += length;
	}

	if (!(pkt->pfc_flags & DCERPC_PFC_FLAG_LAST)) {
		c->transport.send_read(c);
		return;
	}

	if (!(pkt->drep[0] & DCERPC_DREP_LE)) {
		req->flags |= DCERPC_PULL_BIGENDIAN;
	} else {
		req->flags &= ~DCERPC_PULL_BIGENDIAN;
	}


req_done:
	/* we've got the full payload */
	req->state = RPC_REQUEST_DONE;
	DLIST_REMOVE(c->pending, req);

	if (c->request_queue != NULL) {
		/* We have to look at shipping further requests before calling
		 * the async function, that one might close the pipe */
		dcerpc_ship_next_request(c);
	}

	if (req->async.callback) {
		req->async.callback(req);
	}
}

/*
  handle timeouts of individual dcerpc requests
*/
static void dcerpc_timeout_handler(struct event_context *ev, struct timed_event *te, 
				   struct timeval t, void *private)
{
	struct rpc_request *req = talloc_get_type(private, struct rpc_request);

	if (req->state != RPC_REQUEST_PENDING) {
		return;
	}

	req->status = NT_STATUS_IO_TIMEOUT;
	req->state = RPC_REQUEST_DONE;
	DLIST_REMOVE(req->p->conn->pending, req);
	if (req->async.callback) {
		req->async.callback(req);
	}
}


/*
  make sure requests are cleaned up 
 */
static int dcerpc_req_destructor(void *ptr)
{
	struct rpc_request *req = ptr;
	DLIST_REMOVE(req->p->conn->pending, req);
	return 0;
}

/*
  perform the send side of a async dcerpc request
*/
static struct rpc_request *dcerpc_request_send(struct dcerpc_pipe *p, 
					       const struct GUID *object,
					       uint16_t opnum,
					       BOOL async,
					       DATA_BLOB *stub_data)
{
	struct rpc_request *req;

	p->conn->transport.recv_data = dcerpc_recv_data;

	req = talloc(p, struct rpc_request);
	if (req == NULL) {
		return NULL;
	}

	req->p = p;
	req->call_id = next_call_id(p->conn);
	req->status = NT_STATUS_OK;
	req->state = RPC_REQUEST_PENDING;
	req->payload = data_blob(NULL, 0);
	req->flags = 0;
	req->fault_code = 0;
	req->async_call = async;
	req->async.callback = NULL;

	if (object != NULL) {
		req->object = talloc_memdup(req, object, sizeof(*object));
		if (req->object == NULL) {
			talloc_free(req);
			return NULL;
		}
	} else {
		req->object = NULL;
	}

	req->opnum = opnum;
	req->request_data.length = stub_data->length;
	req->request_data.data = talloc_reference(req, stub_data->data);
	if (req->request_data.data == NULL) {
		return NULL;
	}

	DLIST_ADD_END(p->conn->request_queue, req, struct rpc_request *);

	dcerpc_ship_next_request(p->conn);

	if (p->request_timeout) {
		event_add_timed(dcerpc_event_context(p), req, 
				timeval_current_ofs(p->request_timeout, 0), 
				dcerpc_timeout_handler, req);
	}

	talloc_set_destructor(req, dcerpc_req_destructor);
	return req;
}

/*
  Send a request using the transport
*/

static void dcerpc_ship_next_request(struct dcerpc_connection *c)
{
	struct rpc_request *req;
	struct dcerpc_pipe *p;
	DATA_BLOB *stub_data;
	struct ncacn_packet pkt;
	DATA_BLOB blob;
	uint32_t remaining, chunk_size;
	BOOL first_packet = True;

	req = c->request_queue;
	if (req == NULL) {
		return;
	}

	p = req->p;
	stub_data = &req->request_data;

	if (!req->async_call && (c->pending != NULL)) {
		return;
	}

	DLIST_REMOVE(c->request_queue, req);
	DLIST_ADD(c->pending, req);

	init_ncacn_hdr(p->conn, &pkt);

	remaining = stub_data->length;

	/* we can write a full max_recv_frag size, minus the dcerpc
	   request header size */
	chunk_size = p->conn->srv_max_recv_frag - (DCERPC_MAX_SIGN_SIZE+DCERPC_REQUEST_LENGTH);

	pkt.ptype = DCERPC_PKT_REQUEST;
	pkt.call_id = req->call_id;
	pkt.auth_length = 0;
	pkt.pfc_flags = 0;
	pkt.u.request.alloc_hint = remaining;
	pkt.u.request.context_id = p->context_id;
	pkt.u.request.opnum = req->opnum;

	if (req->object) {
		pkt.u.request.object.object = *req->object;
		pkt.pfc_flags |= DCERPC_PFC_FLAG_ORPC;
		chunk_size -= ndr_size_GUID(req->object,0);
	}

	/* we send a series of pdus without waiting for a reply */
	while (remaining > 0 || first_packet) {
		uint32_t chunk = MIN(chunk_size, remaining);
		BOOL last_frag = False;

		first_packet = False;
		pkt.pfc_flags &= ~(DCERPC_PFC_FLAG_FIRST |DCERPC_PFC_FLAG_LAST);

		if (remaining == stub_data->length) {
			pkt.pfc_flags |= DCERPC_PFC_FLAG_FIRST;
		}
		if (chunk == remaining) {
			pkt.pfc_flags |= DCERPC_PFC_FLAG_LAST;
			last_frag = True;
		}

		pkt.u.request.stub_and_verifier.data = stub_data->data + 
			(stub_data->length - remaining);
		pkt.u.request.stub_and_verifier.length = chunk;

		req->status = ncacn_push_request_sign(p->conn, &blob, req, &pkt);
		if (!NT_STATUS_IS_OK(req->status)) {
			req->state = RPC_REQUEST_DONE;
			DLIST_REMOVE(p->conn->pending, req);
			return;
		}
		
		req->status = p->conn->transport.send_request(p->conn, &blob, last_frag);
		if (!NT_STATUS_IS_OK(req->status)) {
			req->state = RPC_REQUEST_DONE;
			DLIST_REMOVE(p->conn->pending, req);
			return;
		}		

		remaining -= chunk;
	}
}

/*
  return the event context for a dcerpc pipe
  used by callers who wish to operate asynchronously
*/
struct event_context *dcerpc_event_context(struct dcerpc_pipe *p)
{
	return p->conn->event_ctx;
}



/*
  perform the receive side of a async dcerpc request
*/
NTSTATUS dcerpc_request_recv(struct rpc_request *req,
			     TALLOC_CTX *mem_ctx,
			     DATA_BLOB *stub_data)
{
	NTSTATUS status;

	while (req->state == RPC_REQUEST_PENDING) {
		struct event_context *ctx = dcerpc_event_context(req->p);
		if (event_loop_once(ctx) != 0) {
			return NT_STATUS_CONNECTION_DISCONNECTED;
		}
	}
	*stub_data = req->payload;
	status = req->status;
	if (stub_data->data) {
		stub_data->data = talloc_steal(mem_ctx, stub_data->data);
	}
	if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
		req->p->last_fault_code = req->fault_code;
	}
	talloc_free(req);
	return status;
}

/*
  perform a full request/response pair on a dcerpc pipe
*/
NTSTATUS dcerpc_request(struct dcerpc_pipe *p, 
			struct GUID *object,
			uint16_t opnum,
			BOOL async,
			TALLOC_CTX *mem_ctx,
			DATA_BLOB *stub_data_in,
			DATA_BLOB *stub_data_out)
{
	struct rpc_request *req;

	req = dcerpc_request_send(p, object, opnum, async, stub_data_in);
	if (req == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	return dcerpc_request_recv(req, mem_ctx, stub_data_out);
}


/*
  this is a paranoid NDR validator. For every packet we push onto the wire
  we pull it back again, then push it again. Then we compare the raw NDR data
  for that to the NDR we initially generated. If they don't match then we know
  we must have a bug in either the pull or push side of our code
*/
static NTSTATUS dcerpc_ndr_validate_in(struct dcerpc_connection *c, 
				       TALLOC_CTX *mem_ctx,
				       DATA_BLOB blob,
				       size_t struct_size,
				       ndr_push_flags_fn_t ndr_push,
				       ndr_pull_flags_fn_t ndr_pull)
{
	void *st;
	struct ndr_pull *pull;
	struct ndr_push *push;
	NTSTATUS status;
	DATA_BLOB blob2;

	st = talloc_size(mem_ctx, struct_size);
	if (!st) {
		return NT_STATUS_NO_MEMORY;
	}

	pull = ndr_pull_init_flags(c, &blob, mem_ctx);
	if (!pull) {
		return NT_STATUS_NO_MEMORY;
	}
	pull->flags |= LIBNDR_FLAG_REF_ALLOC;

	status = ndr_pull(pull, NDR_IN, st);
	if (!NT_STATUS_IS_OK(status)) {
		return ndr_pull_error(pull, NDR_ERR_VALIDATE, 
				      "failed input validation pull - %s",
				      nt_errstr(status));
	}

	push = ndr_push_init_ctx(mem_ctx);
	if (!push) {
		return NT_STATUS_NO_MEMORY;
	}	

	status = ndr_push(push, NDR_IN, st);
	if (!NT_STATUS_IS_OK(status)) {
		return ndr_push_error(push, NDR_ERR_VALIDATE, 
				      "failed input validation push - %s",
				      nt_errstr(status));
	}

	blob2 = ndr_push_blob(push);

	if (!data_blob_equal(&blob, &blob2)) {
		DEBUG(3,("original:\n"));
		dump_data(3, blob.data, blob.length);
		DEBUG(3,("secondary:\n"));
		dump_data(3, blob2.data, blob2.length);
		return ndr_push_error(push, NDR_ERR_VALIDATE, 
				      "failed input validation data - %s",
				      nt_errstr(status));
	}

	return NT_STATUS_OK;
}

/*
  this is a paranoid NDR input validator. For every packet we pull
  from the wire we push it back again then pull and push it
  again. Then we compare the raw NDR data for that to the NDR we
  initially generated. If they don't match then we know we must have a
  bug in either the pull or push side of our code
*/
static NTSTATUS dcerpc_ndr_validate_out(struct dcerpc_connection *c,
					TALLOC_CTX *mem_ctx,
					void *struct_ptr,
					size_t struct_size,
					ndr_push_flags_fn_t ndr_push,
					ndr_pull_flags_fn_t ndr_pull)
{
	void *st;
	struct ndr_pull *pull;
	struct ndr_push *push;
	NTSTATUS status;
	DATA_BLOB blob, blob2;

	st = talloc_size(mem_ctx, struct_size);
	if (!st) {
		return NT_STATUS_NO_MEMORY;
	}
	memcpy(st, struct_ptr, struct_size);

	push = ndr_push_init_ctx(mem_ctx);
	if (!push) {
		return NT_STATUS_NO_MEMORY;
	}	

	status = ndr_push(push, NDR_OUT, struct_ptr);
	if (!NT_STATUS_IS_OK(status)) {
		return ndr_push_error(push, NDR_ERR_VALIDATE, 
				      "failed output validation push - %s",
				      nt_errstr(status));
	}

	blob = ndr_push_blob(push);

	pull = ndr_pull_init_flags(c, &blob, mem_ctx);
	if (!pull) {
		return NT_STATUS_NO_MEMORY;
	}

	pull->flags |= LIBNDR_FLAG_REF_ALLOC;
	status = ndr_pull(pull, NDR_OUT, st);
	if (!NT_STATUS_IS_OK(status)) {
		return ndr_pull_error(pull, NDR_ERR_VALIDATE, 
				      "failed output validation pull - %s",
				      nt_errstr(status));
	}

	push = ndr_push_init_ctx(mem_ctx);
	if (!push) {
		return NT_STATUS_NO_MEMORY;
	}	

	status = ndr_push(push, NDR_OUT, st);
	if (!NT_STATUS_IS_OK(status)) {
		return ndr_push_error(push, NDR_ERR_VALIDATE, 
				      "failed output validation push2 - %s",
				      nt_errstr(status));
	}

	blob2 = ndr_push_blob(push);

	if (!data_blob_equal(&blob, &blob2)) {
		DEBUG(3,("original:\n"));
		dump_data(3, blob.data, blob.length);
		DEBUG(3,("secondary:\n"));
		dump_data(3, blob2.data, blob2.length);
		return ndr_push_error(push, NDR_ERR_VALIDATE, 
				      "failed output validation data - %s",
				      nt_errstr(status));
	}

	return NT_STATUS_OK;
}


/*
 send a rpc request given a dcerpc_call structure 
 */
struct rpc_request *dcerpc_ndr_request_send(struct dcerpc_pipe *p,
						const struct GUID *object,
						const struct dcerpc_interface_table *table,
						uint32_t opnum, 
						TALLOC_CTX *mem_ctx, 
						void *r)
{
	const struct dcerpc_interface_call *call;
	struct ndr_push *push;
	NTSTATUS status;
	DATA_BLOB request;
	struct rpc_request *req;

	call = &table->calls[opnum];

	/* setup for a ndr_push_* call */
	push = ndr_push_init_ctx(mem_ctx);
	if (!push) {
		return NULL;
	}

	if (p->conn->flags & DCERPC_PUSH_BIGENDIAN) {
		push->flags |= LIBNDR_FLAG_BIGENDIAN;
	}

	/* push the structure into a blob */
	status = call->ndr_push(push, NDR_IN, r);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(2,("Unable to ndr_push structure in dcerpc_ndr_request_send - %s\n",
			 nt_errstr(status)));
		talloc_free(push);
		return NULL;
	}

	/* retrieve the blob */
	request = ndr_push_blob(push);

	if (p->conn->flags & DCERPC_DEBUG_VALIDATE_IN) {
		status = dcerpc_ndr_validate_in(p->conn, push, request, call->struct_size, 
						call->ndr_push, call->ndr_pull);
		if (!NT_STATUS_IS_OK(status)) {
			DEBUG(2,("Validation failed in dcerpc_ndr_request_send - %s\n",
				 nt_errstr(status)));
			talloc_free(push);
			return NULL;
		}
	}

	DEBUG(10,("rpc request data:\n"));
	dump_data(10, request.data, request.length);

	/* make the actual dcerpc request */
	req = dcerpc_request_send(p, object, opnum, table->calls[opnum].async,
				  &request);

	if (req != NULL) {
		req->ndr.table = table;
		req->ndr.opnum = opnum;
		req->ndr.struct_ptr = r;
		req->ndr.mem_ctx = mem_ctx;
	}

	talloc_free(push);

	return req;
}

/*
  receive the answer from a dcerpc_ndr_request_send()
*/
NTSTATUS dcerpc_ndr_request_recv(struct rpc_request *req)
{
	struct dcerpc_pipe *p = req->p;
	NTSTATUS status;
	DATA_BLOB response;
	struct ndr_pull *pull;
	uint_t flags;
	TALLOC_CTX *mem_ctx = req->ndr.mem_ctx;
	void *r = req->ndr.struct_ptr;
	uint32_t opnum = req->ndr.opnum;
	const struct dcerpc_interface_table *table = req->ndr.table;
	const struct dcerpc_interface_call *call = &table->calls[opnum];

	/* make sure the recv code doesn't free the request, as we
	   need to grab the flags element before it is freed */
	talloc_increase_ref_count(req);

	status = dcerpc_request_recv(req, mem_ctx, &response);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}

	flags = req->flags;

	/* prepare for ndr_pull_* */
	pull = ndr_pull_init_flags(p->conn, &response, mem_ctx);
	if (!pull) {
		talloc_free(req);
		return NT_STATUS_NO_MEMORY;
	}

	if (pull->data) {
		pull->data = talloc_steal(pull, pull->data);
	}
	talloc_free(req);

	if (flags & DCERPC_PULL_BIGENDIAN) {
		pull->flags |= LIBNDR_FLAG_BIGENDIAN;
	}

	DEBUG(10,("rpc reply data:\n"));
	dump_data(10, pull->data, pull->data_size);

	/* pull the structure from the blob */
	status = call->ndr_pull(pull, NDR_OUT, r);
	if (!NT_STATUS_IS_OK(status)) {
		dcerpc_log_packet(table, opnum, NDR_OUT, 
				  &response);
		return status;
	}

	if (p->conn->flags & DCERPC_DEBUG_VALIDATE_OUT) {
		status = dcerpc_ndr_validate_out(p->conn, pull, r, call->struct_size, 
						 call->ndr_push, call->ndr_pull);
		if (!NT_STATUS_IS_OK(status)) {
			dcerpc_log_packet(table, opnum, NDR_OUT, 
				  &response);
			return status;
		}
	}

	if (pull->offset != pull->data_size) {
		DEBUG(0,("Warning! ignoring %d unread bytes in rpc packet!\n", 
			 pull->data_size - pull->offset));
		/* we used to return NT_STATUS_INFO_LENGTH_MISMATCH here,
		   but it turns out that early versions of NT
		   (specifically NT3.1) add junk onto the end of rpc
		   packets, so if we want to interoperate at all with
		   those versions then we need to ignore this error */
	}

	/* TODO: make pull context independent from the output mem_ctx and free the pull context */

	return NT_STATUS_OK;
}


/*
  a useful helper function for synchronous rpc requests 

  this can be used when you have ndr push/pull functions in the
  standard format
*/
NTSTATUS dcerpc_ndr_request(struct dcerpc_pipe *p,
			    const struct GUID *object,
			    const struct dcerpc_interface_table *table,
			    uint32_t opnum, 
			    TALLOC_CTX *mem_ctx, 
			    void *r)
{
	struct rpc_request *req;

	req = dcerpc_ndr_request_send(p, object, table, opnum, mem_ctx, r);
	if (req == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	return dcerpc_ndr_request_recv(req);
}


/*
  a useful function for retrieving the server name we connected to
*/
const char *dcerpc_server_name(struct dcerpc_pipe *p)
{
	if (!p->conn->transport.peer_name) {
		return "";
	}
	return p->conn->transport.peer_name(p->conn);
}


/*
  get the dcerpc auth_level for a open connection
*/
uint32_t dcerpc_auth_level(struct dcerpc_connection *c) 
{
	uint8_t auth_level;

	if (c->flags & DCERPC_SEAL) {
		auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
	} else if (c->flags & DCERPC_SIGN) {
		auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
	} else if (c->flags & DCERPC_CONNECT) {
		auth_level = DCERPC_AUTH_LEVEL_CONNECT;
	} else {
		auth_level = DCERPC_AUTH_LEVEL_NONE;
	}
	return auth_level;
}

/*
  Receive an alter reply from the transport
*/
static void dcerpc_alter_recv_data(struct dcerpc_connection *conn, struct ncacn_packet *pkt)
{
	struct composite_context *c;
	struct dcerpc_pipe *pipe;

	c = talloc_get_type(conn->alter_private, struct composite_context);
	pipe = talloc_get_type(c->private_data, struct dcerpc_pipe);

	/* mark the connection as not waiting for a alter context reply */
	conn->alter_private = NULL;

	if (pkt->ptype == DCERPC_PKT_ALTER_RESP &&
	    pkt->u.alter_resp.num_results == 1 &&
	    pkt->u.alter_resp.ctx_list[0].result != 0) {
		DEBUG(2,("dcerpc: alter_resp failed - reason %d\n", 
			 pkt->u.alter_resp.ctx_list[0].reason));
		composite_error(c, dcerpc_map_reason(pkt->u.alter_resp.ctx_list[0].reason));
		return;
	}

	if (pkt->ptype != DCERPC_PKT_ALTER_RESP ||
	    pkt->u.alter_resp.num_results == 0 ||
	    pkt->u.alter_resp.ctx_list[0].result != 0) {
		composite_error(c, NT_STATUS_UNSUCCESSFUL);
		return;
	}

	/* the alter_resp might contain a reply set of credentials */
	if (pipe->conn->security_state.auth_info &&
	    pkt->u.alter_resp.auth_info.length) {
		c->status = ndr_pull_struct_blob(
			&pkt->u.alter_resp.auth_info, pipe,
			pipe->conn->security_state.auth_info,
			(ndr_pull_flags_fn_t)ndr_pull_dcerpc_auth);
		if (!composite_is_ok(c)) return;
	}

	composite_done(c);
}

/* 
   send a dcerpc alter_context request
*/
struct composite_context *dcerpc_alter_context_send(struct dcerpc_pipe *p, 
						    TALLOC_CTX *mem_ctx,
						    const struct dcerpc_syntax_id *syntax,
						    const struct dcerpc_syntax_id *transfer_syntax)
{
	struct composite_context *c;
	struct ncacn_packet pkt;
	DATA_BLOB blob;

	c = talloc_zero(mem_ctx, struct composite_context);
	if (c == NULL) return NULL;

	c->state = COMPOSITE_STATE_IN_PROGRESS;
	c->private_data = p;
	c->event_ctx = p->conn->event_ctx;

	p->syntax = *syntax;
	p->transfer_syntax = *transfer_syntax;

	init_ncacn_hdr(p->conn, &pkt);

	pkt.ptype = DCERPC_PKT_ALTER;
	pkt.pfc_flags = DCERPC_PFC_FLAG_FIRST | DCERPC_PFC_FLAG_LAST;
	pkt.call_id = p->conn->call_id;
	pkt.auth_length = 0;

	pkt.u.alter.max_xmit_frag = 5840;
	pkt.u.alter.max_recv_frag = 5840;
	pkt.u.alter.assoc_group_id = 0;
	pkt.u.alter.num_contexts = 1;
	pkt.u.alter.ctx_list = talloc_array(mem_ctx,
						   struct dcerpc_ctx_list, 1);
	if (pkt.u.alter.ctx_list == NULL) {
		c->status = NT_STATUS_NO_MEMORY;
		goto failed;
	}
	pkt.u.alter.ctx_list[0].context_id = p->context_id;
	pkt.u.alter.ctx_list[0].num_transfer_syntaxes = 1;
	pkt.u.alter.ctx_list[0].abstract_syntax = p->syntax;
	pkt.u.alter.ctx_list[0].transfer_syntaxes = &p->transfer_syntax;
	pkt.u.alter.auth_info = data_blob(NULL, 0);

	/* construct the NDR form of the packet */
	c->status = ncacn_push_auth(&blob, mem_ctx, &pkt,
				    p->conn->security_state.auth_info);
	if (!NT_STATUS_IS_OK(c->status)) {
		goto failed;
	}

	p->conn->transport.recv_data = dcerpc_recv_data;
	p->conn->alter_private = c;

	c->status = p->conn->transport.send_request(p->conn, &blob, True);
	if (!NT_STATUS_IS_OK(c->status)) {
		goto failed;
	}

	event_add_timed(c->event_ctx, c,
			timeval_current_ofs(DCERPC_REQUEST_TIMEOUT, 0),
			bind_timeout_handler, c);

	return c;

 failed:
	composite_trigger_error(c);
	return c;
}

NTSTATUS dcerpc_alter_context_recv(struct composite_context *ctx)
{
	NTSTATUS result = composite_wait(ctx);
	talloc_free(ctx);
	return result;
}

/* 
   send a dcerpc alter_context request
*/
NTSTATUS dcerpc_alter_context(struct dcerpc_pipe *p, 
			      TALLOC_CTX *mem_ctx,
			      const struct dcerpc_syntax_id *syntax,
			      const struct dcerpc_syntax_id *transfer_syntax)
{
	struct composite_context *creq;
	creq = dcerpc_alter_context_send(p, mem_ctx, syntax, transfer_syntax);
	return dcerpc_alter_context_recv(creq);
}