summaryrefslogtreecommitdiff
path: root/network/trans/stmedit/sys/StreamEdit.c
blob: e4f91c61ff53a81855dfa2608ea2215322ff17a2 (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
/*++

Copyright (c) Microsoft Corporation. All rights reserved

Abstract:
   Stream Edit Callout Driver Sample.

   This sample demonstrates finding and replacing a string pattern from a
   live TCP stream via the WFP stream API.

   The driver demonstrates the two modes of stream editing/inspection --

      o  Inline Editing where all modification is carried out within the
         WFP ClassifyFn callout function.

      o  Out-of-band (OOB) Editing where all modification is done by a 
         worker thread. (this is the default)

   The mode setting, along with other inspection parameters are configurable
   via the following registry values

  HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\StmEdit\Parameters
      
      o  StringToFind	 (REG_SZ, default = "rainy")
      o  StringX		 (REG_SZ, default = "cloudy")
      o  StringToReplace (REG_SZ, default = "sunny")

      o  InspectionLocalPort (REG_DWORD, default = 8888)

      o  InspectionRemotePort (REG_DWORD, default = 0)
            Note: for this sample, a local or remote port is mandatory. Both cannot be zero.

      o  InspectioDirection (REG_DWORD, default = 2)
            possible values : 2 (inbound + outbound), 0 (FWP_DIRECTION_OUTBOUND), 1 (FWP_DIRECTION_INBOUND)

      o  MultipleCallouts (REG_DWORD, default = true/1)
            controls registration of multiple callouts. Set 0 for false, other for TRUE

      o  BusyThreshold (REG_DWORD, default = 16KB)
            BusyThreshold value is in KBs (e.g. a value of 5 means 5KB)

   The sample is IP version agnostic. It is capable of performing inspections
   on both IPv4 and IPv6 data streams

   Before experimenting with the sample, please be sure to add an exception for
   the InspectionPort configured to the firewall. 

Environment:
    Kernel mode

--*/

#include "Trace.h"
#include "StreamEdit.h"
#include "StreamEdit.tmh"

STMEDIT_GLOBALS         Globals;

DRIVER_INITIALIZE       DriverEntry;
EVT_WDF_DRIVER_UNLOAD   StreamEditEvtDriverUnload;

#if defined _MODULE_ID
#undef _MODULE_ID
#endif
#define _MODULE_ID  'S'

VOID
StmEditReferenceFlow(
    _Inout_ PSTREAM_FLOW_CONTEXT FlowContext,
    _In_    char Module,
    _In_    UINT Line
    )
{
    LONG Count = InterlockedIncrement((LONG *)&FlowContext->RefCount);
    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_REFCOUNT, "FlowCtx %p RefCount++ @ %c/%lu = %lu", FlowContext, Module, Line, Count);
}

VOID
StmEditDeReferenceFlow(
    _Inout_ PSTREAM_FLOW_CONTEXT FlowContext,
    _In_    char Module,
    _In_    UINT Line
    )
{
    LONG Count;
    KLOCK_QUEUE_HANDLE LockHandle;

    NT_ASSERT(FlowContext->RefCount > 0);

    Count = InterlockedDecrement((LONG *)&FlowContext->RefCount);
    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_REFCOUNT, "FlowCtx %p RefCount-- @ %c/%lu = %lu", FlowContext, Module, Line, Count);

    if (Count == 0)
    {
        NT_ASSERT( ! FlowContext->bFlowActive);

        // Remove the context from global context list
        //
        KeAcquireInStackQueuedSpinLock(&Globals.FlowContextListLock, &LockHandle);

        if (!FlowContext->bEntryRemoved) 
		{
            RemoveEntryList(&FlowContext->Link);
            FlowContext->bEntryRemoved = TRUE;
            DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "FlowCtx %p, -- Link removed", FlowContext);
        }
        Count = --Globals.FlowContextCount;

        if (Globals.FlowContextCount == 0)
        {
            NT_ASSERT(IsListEmpty(&Globals.FlowContextList));
            DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "Setting ZeroFlowCountEvent.");
            KeSetEvent(&Globals.ZeroFlowCountEvent, IO_NO_INCREMENT, FALSE);
        }
        KeReleaseInStackQueuedSpinLock(&LockHandle);

        if (!FlowContext->bEditInline) 
		{
            NT_ASSERT(IsListEmpty(&FlowContext->OobInfo.OutgoingDataQueue));
        }

        if (FlowContext->ScratchBuffer) 
		{
            ExFreePoolWithTag(FlowContext->ScratchBuffer, STMEDIT_TAG_FLAT_BUFFER);
        }

        DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "FlowCtx %p is being freed., %lu remain @--", FlowContext, Count);
        ExFreePoolWithTag(FlowContext, STMEDIT_TAG_FLOWCTX);
    }
}


NTSTATUS
StreamEditNotifyFunction(
   _In_ FWPS_CALLOUT_NOTIFY_TYPE NotifyType,
   _In_ const GUID* FilterKey,
   _In_ const FWPS_FILTER* Filter
   )
{
/*
    Notify Function.
*/
    UNREFERENCED_PARAMETER(FilterKey);

#if 0
   UNREFERENCED_PARAMETER(notifyType);
   UNREFERENCED_PARAMETER(filter);
#else
    NT_ASSERT(Filter != NULL);

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT,
                "-><- %!FUNC! invoked with %I64u for Filter ID %I64u",
                       NotifyType, Filter->filterId);

#endif
   return STATUS_SUCCESS;
}

void
NTAPI
StreamEditInjectCompletionFn(
    _In_ VOID* Context,
    _Inout_ NET_BUFFER_LIST* NetBufferList,
    _In_ BOOLEAN DispatchLevel
    )
/*
    Injection completion function for injecting an NBL created using
    FwpsAllocateNetBufferAndNetBufferList.
*/
{
    MDL* mdl = (MDL*)Context;

    UNREFERENCED_PARAMETER(DispatchLevel);

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "-><- %!FUNC!: NBL %p (%!STATUS!), MDL %p", NetBufferList, NetBufferList->Status, mdl);

    // Supress warning 28922: Redundant test against NULL. Pointer is already guaranteed to be non-NULL.
    // Rationale : mdl is not guaranteed to be non-NULL here.
#pragma prefast(push)
#pragma prefast(disable:28922)
 
    if (mdl != NULL) 
	{
        //
        // The MDL mapped over a pool alloc which we need to free here.
        //

        ExFreePoolWithTag(mdl->MappedSystemVa, STMEDIT_TAG_MDL_DATA);

        IoFreeMdl(mdl);
    }
#pragma prefast(pop)

    NT_ASSERT(NetBufferList != NULL);
    FwpsFreeNetBufferList(NetBufferList);
}

NTSTATUS
StreamEditRemoveFlowCtx(
    _In_ PSTREAM_FLOW_CONTEXT Context
    )
/*
    Function to disassociate a previously associated context from a data flow.
    This will cause flowDelete function to be invoked (either synchronously or asynchronously).

    Remarks @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff551169.aspx
    
    If the FwpsFlowRemoveContext0 function returns STATUS_SUCCESS, FwpsFlowRemoveContext0
    calls the flowDeleteFn callout function synchronously.If FwpsFlowRemoveContext0 returns
    STATUS_PENDING, FwpsFlowRemoveContext0 calls flowDeleteFn asynchronously because an
    active callout classification is in progress.
*/
{
    NTSTATUS Status = STATUS_SUCCESS;
    //
    // Possible synchronization problem for accessing bFlowActive...
    // while we are flushing the data, FlowDeleteFn can get invoked.
    //

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "--> %!FUNC!: FlowCtx %p", Context);

    NT_ASSERT(Context);

    if (Context->bEditInline) 
	{
        (VOID) InlineEditFlushData(Context, 0, Context->PartialSFlags);
    }
    else {
        (VOID) StreamOobFlushOutgoingData(Context);
    }

    if (Context->bFlowActive) 
	{

        Status = FwpsFlowRemoveContext(
                        Context->FlowHandle,
                        Context->LayerId,
                        Context->CalloutId);
    }

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "<-- %!FUNC!: FlowCtx %p, %!STATUS!",  Context, Status);
    return Status;
}

VOID
StreamEditSignalShutdown(
)
/*
    This function attempts to Disassociate all active FlowContexts so that
    a shutdown can be performed.
*/
{
    KLOCK_QUEUE_HANDLE LockHandle;
    PSTREAM_FLOW_CONTEXT FlowContext;

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "--> %!FUNC!");

    KeAcquireInStackQueuedSpinLock(&Globals.FlowContextListLock, &LockHandle);
    while ( ! IsListEmpty(&Globals.FlowContextList) )
    {
        PLIST_ENTRY Entry = RemoveHeadList(&Globals.FlowContextList);

        FlowContext = CONTAINING_RECORD(Entry, STREAM_FLOW_CONTEXT, Link);
        FlowContext->bEntryRemoved = TRUE;
        DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "FlowCtx %p, -- Link removed at shutdown", FlowContext);

        if (FlowContext->bFlowActive)
        {
            KeReleaseInStackQueuedSpinLock(&LockHandle);
            (VOID)StreamEditRemoveFlowCtx(FlowContext);
            KeAcquireInStackQueuedSpinLock(&Globals.FlowContextListLock, &LockHandle);
        }
    }
    KeReleaseInStackQueuedSpinLock(&LockHandle);

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "<-- %!FUNC!");
}

VOID
StreamEditFlowDeleteFunction(
    _In_ UINT16 LayerId,
    _In_ UINT32 CalloutId,
    _In_ UINT64 Context
    )
/*
    This is the flowDeleteFn function. This callback is invoked when a flow is
    terminated or due to call to FwpsFlowRemoveContext0.

    We removes the FlowContext from the global FlowcCntextList and releases resources.

    IRQL <= DISPATCH_LEVEL
*/
{
    PSTREAM_FLOW_CONTEXT FlowCtx = (PSTREAM_FLOW_CONTEXT)(ULONG_PTR)Context;

    NT_ASSERT(NULL != FlowCtx);
    NT_ASSERT(TRUE == FlowCtx->bFlowActive);

    InterlockedExchange8(&FlowCtx->bFlowActive, FALSE);

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "--> %!FUNC!: FlowCtx %p, LayerId %hu, CalloutId %u, FlowId %I64u (RefCt = %lu)",
        FlowCtx, LayerId, CalloutId, FlowCtx->FlowHandle, FlowCtx->RefCount );

    // Deref the reference taken in Flow-established when the FlowCtx was allocated
    //
    StmEditDeReferenceFlow(FlowCtx, _MODULE_ID,  __LINE__);

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "<-- %!FUNC!: FlowCtx %p", FlowCtx);
}


VOID
NTAPI
StreamEditCommonStreamClassify(
    _In_ const FWPS_INCOMING_VALUES* InFixedValues,
    _In_ const FWPS_INCOMING_METADATA_VALUES* InMetaValues,
    _In_ PVOID LayerData,
#if(NTDDI_VERSION >= NTDDI_WIN7)
    _In_ const VOID* ClassifyContext,
#endif
    _In_ const FWPS_FILTER* Filter,
    _In_ UINT64 InFlowContext,
    _Inout_ FWPS_CLASSIFY_OUT* ClassifyOut
    )
/*
    Common classifyFn for both Inline and Out-of-band Stream layer callouts.
    Invokes corresponding classify-function based on FlowContext->bEditInline flag.
*/
{
    PSTREAM_FLOW_CONTEXT FlowContext = (PSTREAM_FLOW_CONTEXT)(ULONG_PTR)InFlowContext;

#if(NTDDI_VERSION >= NTDDI_WIN7)
    UNREFERENCED_PARAMETER(ClassifyContext);
#endif

    NT_ASSERT(FlowContext);

    // Reference the flow to keep around while we are in classifyFn
    //
    StmEditReferenceFlow(FlowContext, _MODULE_ID, __LINE__);

    if (FlowContext->bEditInline) 
    {
        InlineEditClassify(
            InFixedValues,
            InMetaValues,
            LayerData,
            Filter,
			InFlowContext,
            ClassifyOut
            );
    }
    else
    {
        OobEditClassify (
            InFixedValues,
            InMetaValues,
            LayerData,
            Filter,
			InFlowContext,
            ClassifyOut
            );
    }

    StmEditDeReferenceFlow(FlowContext, _MODULE_ID, __LINE__);
}

VOID 
StreamEditFlowEstablishedClassify(
    _In_ const FWPS_INCOMING_VALUES* InFixedValues,
    _In_ const FWPS_INCOMING_METADATA_VALUES* InMetaValues,
    _In_ PVOID Packet,
#if(NTDDI_VERSION >= NTDDI_WIN7)
    _In_ const void* ClassifyContext,
#endif  
    _In_ const FWPS_FILTER* Filter,
    _In_ UINT64 InFlowContext,
    _Inout_ FWPS_CLASSIFY_OUT* ClassifyOut
)
/*
    Flow-established call out for IPV4 and IPV6 traffic.
    Allocates and sets up a flow-context, and associate it with the flow.
*/
{
    NTSTATUS Status;
    PSTREAM_FLOW_CONTEXT StreamFlowContext;
    UINT32 StreamCalloutId;
    UINT16  StreamLayerId;
    KLOCK_QUEUE_HANDLE lockHandle;
    USHORT ipProtIndex;

    int CalloutSet = 0;

#if(NTDDI_VERSION >= NTDDI_WIN7)
    UNREFERENCED_PARAMETER(ClassifyContext);
#endif  
    UNREFERENCED_PARAMETER(InFlowContext);
    UNREFERENCED_PARAMETER(Packet);


    if ((Filter->action.calloutId == Globals.FlowEstablishedV4Callout1) ||
        (Filter->action.calloutId == Globals.FlowEstablishedV6Callout1)) 
	{
        CalloutSet = 1;
    }
    else
    if ((Filter->action.calloutId == Globals.FlowEstablishedV4Callout2) ||
        (Filter->action.calloutId == Globals.FlowEstablishedV6Callout2)) 
	{
        CalloutSet = 2;
        NT_ASSERT(TRUE == Globals.MultipleCallouts);
    }
    else
	{
        NT_ASSERT(FALSE);
    }

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "--> %!FUNC!%d: LayerId %hu, CalloutId %u, FlowId %I64u",
        CalloutSet, InFixedValues->layerId, Filter->action.calloutId, InMetaValues->flowHandle);

    ClassifyOut->actionType = FWP_ACTION_CONTINUE;

    // Lets not entertain any new flows if the driver is unloading!
    //
    if (Globals.DriverUnloading) 
	{
        DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT,"<-- %!FUNC!: -- Driver unloading, flow not being associated with");
        return;
    }

    //
    // Setup the flow context for IPV4 Flows
    //
    if (FWPS_LAYER_ALE_FLOW_ESTABLISHED_V4 == InFixedValues->layerId) 
	{
        ipProtIndex = FWPS_FIELD_ALE_FLOW_ESTABLISHED_V4_IP_PROTOCOL;
        StreamLayerId = FWPS_LAYER_STREAM_V4;

        StreamCalloutId = CalloutSet == 1 ? Globals.StreamLayerV4Callout1 : Globals.StreamLayerV4Callout2;
    }
    //
    // Setup the flow context for IPV6 Flows
    //
    else if (FWPS_LAYER_ALE_FLOW_ESTABLISHED_V6 == InFixedValues->layerId) 
	{
        ipProtIndex = FWPS_FIELD_ALE_FLOW_ESTABLISHED_V6_IP_PROTOCOL;
        StreamLayerId = FWPS_LAYER_STREAM_V6;

        StreamCalloutId = CalloutSet == 1 ? Globals.StreamLayerV6Callout1 : Globals.StreamLayerV6Callout2;
    }
    else
    {
        // We should not be here.
        //
        NT_ASSERT(FALSE);
        DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "<-- %!FUNC!: -- Invalid layer.");
        return;
    }

    //
    // Creates a flow context and associate it with the current flow
    // FlowContext gets deleted via flowDeleteFn
    //

    do
    {
        StreamFlowContext = ExAllocatePool2(POOL_FLAG_NON_PAGED, sizeof(STREAM_FLOW_CONTEXT), STMEDIT_TAG_FLOWCTX);

        if (StreamFlowContext == NULL) 
		{
            DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "Unable to allocate flow context");
            Status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        // Initialize the flow-context
        //

        StreamFlowContext->IpProto = InFixedValues->incomingValue[ipProtIndex].value.uint16;
        StreamFlowContext->bFlowActive = TRUE;

        StreamFlowContext->FlowHandle = InMetaValues->flowHandle;
        StreamFlowContext->LayerId = StreamLayerId;
        StreamFlowContext->CalloutId = StreamCalloutId;

        // Reference to take ownership!
        StmEditReferenceFlow(StreamFlowContext, _MODULE_ID, __LINE__);

        // Callout Set #1 is for Out of Band editing
        //
        if (CalloutSet == 1)
        {
            // Initialize OOB editing specific flow context structure fields
            // this includes, creating a worker thread to handle 

            KeInitializeSpinLock(&StreamFlowContext->OobInfo.EditLock);
            InitializeListHead(&StreamFlowContext->OobInfo.OutgoingDataQueue);

            StreamFlowContext->OobInfo.EditState = OOB_EDIT_IDLE;
            StreamFlowContext->OobInfo.QueueNumber = InterlockedIncrement((LONG *)&Globals.QueueIndex) % NUM_WORKITEM_QUEUES;

        }
        // Callout Set #2 is for InLine editing
        //
        else
        {
            // Initialize inline editing specific flow context structure areas
            //
            StreamFlowContext->InlineEditState = INLINE_EDIT_IDLE;
            StreamFlowContext->bEditInline = TRUE;

            StreamFlowContext->CurrentProcessor = INVALID_PROC_NUMBER;
        }

        // Add the newly created context on global context list
        KeAcquireInStackQueuedSpinLock(&Globals.FlowContextListLock, &lockHandle);
        InsertTailList(&Globals.FlowContextList, &StreamFlowContext->Link);
        DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "FlowCtx %p, ++ Link inserted into global list", StreamFlowContext);

        ++Globals.FlowContextCount;
        if (Globals.FlowContextCount == 1) 
		{
            // Reset the shut-down event in case it was set due to no active flows
            //
            DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "Clearing ZeroFlowCountEvent.");
            KeClearEvent(&Globals.ZeroFlowCountEvent);
        }
        DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "FlowCtx %p is allocated., Total %lu @++", StreamFlowContext, Globals.FlowContextCount);

        KeReleaseInStackQueuedSpinLock(&lockHandle);

        Status = FwpsFlowAssociateContext(
                        StreamFlowContext->FlowHandle,
                        StreamLayerId,
                        StreamCalloutId,
                        (UINT64)StreamFlowContext);

        //
        // If not able to associate a flow context, free the memory and return.
        //
        if (!NT_SUCCESS(Status)) 
		{
            DoTraceLevelMessage(TRACE_LEVEL_ERROR, CO_GENERAL, "FlowContext association to FlowId %I64u failed with %!STATUS!", 
				InMetaValues->flowHandle, Status);
            break;
        }

    } while (FALSE);

    if (!NT_SUCCESS(Status) && StreamFlowContext) 
	{
        StmEditDeReferenceFlow(StreamFlowContext, _MODULE_ID, __LINE__);
    }

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "<-- %!FUNC!%d: FlowCtx %p, cOut->Action %#x, %!STATUS!", 
		CalloutSet, StreamFlowContext, ClassifyOut->actionType, Status);
    return;
}

NTSTATUS
StreamEditRegisterFlowEstablishedCallouts(
    _In_  PVOID DeviceObject,
    _In_  const GUID* LayerKey,
    _In_  const GUID* CalloutKey,
    _In_  FWPM_DISPLAY_DATA* DisplayData,
    _Out_ UINT32* CalloutId,
    _In_ int CalloutNum
    )
/*
    This function registers callouts and filters that intercept TCP
    traffic at WFP FWPM_LAYER_STREAM_V4 or FWPM_LAYER_STREAM_V6 layer.
*/
{
    NTSTATUS Status = STATUS_SUCCESS;
    USHORT condIndex = 0;
    BOOLEAN calloutRegistered = FALSE;

    FWPS_CALLOUT sCallout = { 0 };
    FWPM_CALLOUT mCallout = { 0 };

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "--> %!FUNC!%d", CalloutNum);

    sCallout.calloutKey = *CalloutKey; // STREAM_EDITOR_FLOW_ESTABLISHED_CALLOUT_V4 / V6;
    sCallout.notifyFn = StreamEditNotifyFunction;

    sCallout.classifyFn = StreamEditFlowEstablishedClassify;

    Status = FwpsCalloutRegister(DeviceObject, &sCallout, CalloutId);

    if (NT_SUCCESS(Status))
    {
        calloutRegistered = TRUE;

        mCallout.calloutKey = *CalloutKey;
        mCallout.displayData = *DisplayData;
        mCallout.applicableLayer = *LayerKey; // FWPM_LAYER_ALE_FLOW_ESTABLISHED_V4 / V6

        Status = FwpmCalloutAdd(Globals.EngineHandle, &mCallout, NULL, NULL);

        if (NT_SUCCESS(Status))
        {
            FWPM_FILTER filter = { 0 };
            FWPM_FILTER_CONDITION filterConditions[4] = { 0 };

            // Add Filters for StreamEditFlowEstablishedClassify
            //

            filter.layerKey = *LayerKey;
            filter.displayData.name = L"Stream Edit Sample Filter";
            filter.displayData.description = L"Filter that finds and replaces a token from a TCP stream (@ Flow Established)";

            filter.action.type = FWP_ACTION_CALLOUT_INSPECTION; // FWP_ACTION_CALLOUT_TERMINATING;
            filter.action.calloutKey = *CalloutKey;
            filter.filterCondition = filterConditions;

            // In this sample, we edit TCP streams only
            //
            filterConditions[condIndex].fieldKey = FWPM_CONDITION_IP_PROTOCOL;
            filterConditions[condIndex].matchType = FWP_MATCH_EQUAL;
            filterConditions[condIndex].conditionValue.type = FWP_UINT8;
            filterConditions[condIndex].conditionValue.uint8 = IPPROTO_TCP;
            filter.numFilterConditions++;
            condIndex++;

            // Filter according to the direction of the flow we are interested in
            //
            // @ http://msdn.microsoft.com/en-us/library/windows/desktop/aa364005.aspx
            //
            // For stream layers (FWPM_LAYER_STREAM_*) and  flow established layers
            // ( FWPM_LAYER_ALE_FLOW_ESTABLISHED_* ), the value will be the same as
            // direction of the connection.
            //
            // For example, when a local application initiates the connection, an
            // inbound packet has FWPM_CONDITION_DIRECTION set to FWP_DIRECTION_OUTBOUND.
            // 

            if (Globals.InspectionDirection != FWP_DIRECTION_MAX)
            {
                filterConditions[condIndex].fieldKey = FWPM_CONDITION_DIRECTION;
                filterConditions[condIndex].matchType = FWP_MATCH_EQUAL;
                filterConditions[condIndex].conditionValue.type = FWP_UINT32;
                filterConditions[condIndex].conditionValue.uint32 = Globals.InspectionDirection;
                filter.numFilterConditions++;
                condIndex++;
            }

            // Make sure that either the remote or the local port is specified...
            // i.e. both ports are not zero
            //

            if (Globals.InspectionLocalPort > 0)
            {
                filterConditions[condIndex].fieldKey = FWPM_CONDITION_IP_LOCAL_PORT;
                filterConditions[condIndex].matchType = FWP_MATCH_EQUAL;
                filterConditions[condIndex].conditionValue.type = FWP_UINT16;
                filterConditions[condIndex].conditionValue.uint16 = Globals.InspectionLocalPort;
                filter.numFilterConditions++;
                condIndex++;
            }

            if (Globals.InspectionRemotePort > 0)
            {
                filterConditions[condIndex].fieldKey = FWPM_CONDITION_IP_REMOTE_PORT;
                filterConditions[condIndex].matchType = FWP_MATCH_EQUAL;
                filterConditions[condIndex].conditionValue.type = FWP_UINT16;
                filterConditions[condIndex].conditionValue.uint16 = Globals.InspectionRemotePort;
                filter.numFilterConditions++;
            }

            filter.subLayerKey = CalloutNum == 1 ? STREAM_EDITOR_SUBLAYER_1 : STREAM_EDITOR_SUBLAYER_2;
            filter.weight.type = FWP_EMPTY;

            Status = FwpmFilterAdd(Globals.EngineHandle, &filter, NULL, NULL);

        } //FwpmCalloutAdd
    } //FwpsCalloutRegister

    if (!NT_SUCCESS(Status))
    {
        if (calloutRegistered) 
		{
            FwpsCalloutUnregisterById(*CalloutId);
        }
    }

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "<-- %!FUNC!, %!STATUS!", Status);
    return Status;
}

NTSTATUS
StreamEditRegisterStreamLayerCallouts(
    _In_  PVOID DeviceObject,
    _In_  const GUID* LayerKey,
    _In_  const GUID* CalloutKey,
    _In_  FWPM_DISPLAY_DATA* DisplayData,
    _Out_ UINT32* CalloutId,
    _In_  const int CalloutNum
    )
/*
    This function registers callouts that intercept TCP traffic
    at WFP FWPM_LAYER_STREAM_V4 or FWPM_LAYER_STREAM_V6 layer.
*/
{
    NTSTATUS Status = STATUS_SUCCESS;
    FWPS_CALLOUT sCallout = {0};
    FWPM_CALLOUT mCallout = {0};
    BOOLEAN calloutRegistered = FALSE;

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "--> %!FUNC!%d", CalloutNum);

    sCallout.calloutKey     = *CalloutKey;
    sCallout.classifyFn     = StreamEditCommonStreamClassify;
    sCallout.notifyFn       = StreamEditNotifyFunction;
    sCallout.flowDeleteFn   = StreamEditFlowDeleteFunction;
    
    // http://msdn.microsoft.com/en-us/library/windows/hardware/ff551224.aspx
    //
    // FWPS_CALLOUT0 structure
    //
    // FWP_CALLOUT_FLAG_CONDITIONAL_ON_FLOW
    // If this flag is specified, the filter engine calls the callout driver's
    // classifyFn callout function only if there is a context associated with
    // the data flow.
    //

    sCallout.flags = FWP_CALLOUT_FLAG_CONDITIONAL_ON_FLOW;

    Status = FwpsCalloutRegister(
                        DeviceObject,
                        &sCallout,
                        CalloutId );

    if (NT_SUCCESS(Status))
    {
        calloutRegistered = TRUE;

        mCallout.calloutKey = *CalloutKey;
        mCallout.displayData = *DisplayData;
        mCallout.applicableLayer = *LayerKey; // FWPM_LAYER_STREAM_V4 / V6

        Status = FwpmCalloutAdd(
                    Globals.EngineHandle,
                    &mCallout,
                    NULL,
                    NULL );

        if (NT_SUCCESS(Status))
        {
            //
            //  Add Filters for Stream Classify
            //
            //  Note : we are adding a filter with no filter conditions -- i.e. this classifyFn callout
            //  will be classified for ALL streams/flows.
            //  However, due to FWP_CALLOUT_FLAG_CONDITIONAL_ON_FLOW set above,
            //  the classifyFn will be classified only for flows that have a context associated.
            //

            FWPM_FILTER filter = { 0 };

            filter.layerKey = *LayerKey;
            filter.displayData.name = L"Stream Edit Sample Filter";
            filter.displayData.description = L"Filter that finds and replaces a token from a TCP stream (@ Stream Layer)";

            filter.action.type = FWP_ACTION_CALLOUT_TERMINATING;
            filter.action.calloutKey = *CalloutKey;
            filter.numFilterConditions = 0;
            filter.filterCondition = 0;

            filter.subLayerKey = CalloutNum == 1 ? STREAM_EDITOR_SUBLAYER_1 : STREAM_EDITOR_SUBLAYER_2;
            filter.weight.type = FWP_EMPTY; // auto-weight

            Status = FwpmFilterAdd(Globals.EngineHandle, &filter, NULL, NULL);
        }
    }

    if (!NT_SUCCESS(Status)) 
	{
        if (calloutRegistered)  
		{
            FwpsCalloutUnregisterById(*CalloutId);
        }
    }

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "<-- %!FUNC!, %!STATUS!", Status);
    return Status;
}


NTSTATUS
StreamEditRegisterCallouts(
_In_  PVOID DeviceObject
    )
/* 
    This function registers dynamic callouts and filters that intercept
    TCP traffic at WFP FWPM_LAYER_STREAM_V4 and FWPM_LAYER_STREAM_V6 
    layer.

    Callouts and filters will be removed during DriverUnload.
*/
{
    NTSTATUS Status = STATUS_SUCCESS;

    BOOLEAN EngineOpened = FALSE;
    BOOLEAN InTransaction = FALSE;

    FWPM_SESSION session = {0};


    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT,"--> %!FUNC!");

    session.flags = FWPM_SESSION_FLAG_DYNAMIC;

    Status = FwpmEngineOpen(
                    NULL,
                    RPC_C_AUTHN_WINNT,
                    NULL,
                    &session,
                    &Globals.EngineHandle
                    );

    if (NT_SUCCESS(Status))
    {
        EngineOpened = TRUE;

        Status = FwpmTransactionBegin(Globals.EngineHandle, 0);
        if (NT_SUCCESS(Status))
        {
            FWPM_SUBLAYER0 StreamEditSubLayer = { 0 };
            FWPM_DISPLAY_DATA DisplayData;
            NTSTATUS StatusV6;

            InTransaction = TRUE;

            // Add SubLayer for Callout Set 1 (OoB V4/V6 callouts)
            // Register the first set of callouts at Flow-established V4 and V6 layers
            //
            StreamEditSubLayer.subLayerKey = STREAM_EDITOR_SUBLAYER_1;
            StreamEditSubLayer.displayData.name = L"Stream Edit Sample Sub-Layer 1";
            StreamEditSubLayer.displayData.description = L"Sub-Layer for use by Stream Edit Sample callouts";
            StreamEditSubLayer.weight = 0x40;

            Status = FwpmSubLayerAdd(Globals.EngineHandle, &StreamEditSubLayer, NULL);

            if (NT_SUCCESS(Status))
            {
                DisplayData.name = L"Stream Editor Sample ALE Flow Established V4 Callout #1";
                DisplayData.description = L"Flow Established V4 Callout to associate flow-contexts with flows";

                Status = StreamEditRegisterFlowEstablishedCallouts(
                                DeviceObject,
                                &FWPM_LAYER_ALE_FLOW_ESTABLISHED_V4,
                                &STREAM_EDITOR_FLOW_ESTABLISHED_CALLOUT_V4,
                                &DisplayData,
                                &Globals.FlowEstablishedV4Callout1,
                                1);

                DisplayData.name = L"Stream Editor Sample ALE Flow Established V6 Callout #1";
                DisplayData.description = L"Flow Established V6 Callout to associate flow-contexts with flows";

                StatusV6 = StreamEditRegisterFlowEstablishedCallouts(
                                DeviceObject,
                                &FWPM_LAYER_ALE_FLOW_ESTABLISHED_V6,
                                &STREAM_EDITOR_FLOW_ESTABLISHED_CALLOUT_V6,
                                &DisplayData,
                                &Globals.FlowEstablishedV6Callout1,
                                1);

                if (NT_SUCCESS(Status) || NT_SUCCESS(StatusV6))
                {
                    DisplayData.name = L"Stream Editor Sample Stream Layer V4 Callout #1";
                    DisplayData.description = L"Stream-Layer V4 Callout finds and replaces token(s) from a TCP stream";

                    Status = StreamEditRegisterStreamLayerCallouts(
                                DeviceObject,
                                &FWPM_LAYER_STREAM_V4,
                                &STREAM_EDITOR_STREAM_CALLOUT_V4,
                                &DisplayData,
                                &Globals.StreamLayerV4Callout1,
                                1);

                    DisplayData.name = L"Stream Editor Sample Stream Layer V6 Callout #1";
                    DisplayData.description = L"Stream-Layer V6 Callout finds and replaces token(s) from a TCP stream";

                    StatusV6 = StreamEditRegisterStreamLayerCallouts(
                                DeviceObject,
                                &FWPM_LAYER_STREAM_V6,
                                &STREAM_EDITOR_STREAM_CALLOUT_V6,
                                &DisplayData,
                                &Globals.StreamLayerV6Callout1,
                                1);

                    if (!(NT_SUCCESS(Status) || NT_SUCCESS(StatusV6))) 
					{
                        NT_ASSERT(FALSE);
                    }
                } // RegisterStreamLayerCallouts 
            }//FwpmSubLayerAdd




            if (Globals.MultipleCallouts)
            {
                // Add SubLayer for Callout Set 2 (OoB V4/V6 callouts)
                // Register the second set of callouts at Flow-established V4 and V6 layers
                //

                StreamEditSubLayer.subLayerKey = STREAM_EDITOR_SUBLAYER_2;
                StreamEditSubLayer.displayData.name = L"Stream Edit Sample Sub-Layer 2";
                StreamEditSubLayer.displayData.description = L"Sub-Layer for use by Stream Edit Sample callouts";
                StreamEditSubLayer.flags = 0;
                StreamEditSubLayer.weight = 0x20;

                Status = FwpmSubLayerAdd(Globals.EngineHandle, &StreamEditSubLayer, NULL);

                if (NT_SUCCESS(Status))
                {
                    // Register second set of callouts at Flow-established V4 and V6 layers
                    //
                    DisplayData.name = L"Stream Editor Sample ALE Flow Established V4 Callout #2";
                    DisplayData.description = L"Flow Established V4 Callout to associate flow-contexts with flows";

                    Status = StreamEditRegisterFlowEstablishedCallouts(
                        DeviceObject,
                        &FWPM_LAYER_ALE_FLOW_ESTABLISHED_V4,
                        &STREAM_EDITOR_FLOW_ESTABLISHED_CALLOUT_V4_2,
                        &DisplayData,
                        &Globals.FlowEstablishedV4Callout2,
                        2);

                    DisplayData.name = L"Stream Editor Sample ALE Flow Established V6 Callout #2";
                    DisplayData.description = L"Flow Established V6 Callout to associate flow-contexts with flows";

                    StatusV6 = StreamEditRegisterFlowEstablishedCallouts(
                        DeviceObject,
                        &FWPM_LAYER_ALE_FLOW_ESTABLISHED_V6,
                        &STREAM_EDITOR_FLOW_ESTABLISHED_CALLOUT_V6_2,
                        &DisplayData,
                        &Globals.FlowEstablishedV6Callout2,
                        2);

                    if (NT_SUCCESS(Status) || NT_SUCCESS(StatusV6))
                    {
                        DisplayData.name = L"Stream Editor Sample Stream Layer V4 Callout #2";
                        DisplayData.description = L"Stream-Layer V4 Callout finds and replaces token(s) from a TCP stream";

                        Status = StreamEditRegisterStreamLayerCallouts(
                            DeviceObject,
                            &FWPM_LAYER_STREAM_V4,
                            &STREAM_EDITOR_STREAM_CALLOUT_V4_2,
                            &DisplayData,
                            &Globals.StreamLayerV4Callout2,
                            2);

                        DisplayData.name = L"Stream Editor Sample Stream Layer V6 Callout #2";
                        DisplayData.description = L"Stream-Layer V6 Callout finds and replaces token(s) from a TCP stream";

                        StatusV6 = StreamEditRegisterStreamLayerCallouts(
                            DeviceObject,
                            &FWPM_LAYER_STREAM_V6,
                            &STREAM_EDITOR_STREAM_CALLOUT_V6_2,
                            &DisplayData,
                            &Globals.StreamLayerV6Callout2,
                            2);

                        if (!(NT_SUCCESS(Status) || NT_SUCCESS(StatusV6))) 
						{
                            NT_ASSERT(FALSE);
                        }
                    }
                }
            } // MultiCallout.

            Status = FwpmTransactionCommit(Globals.EngineHandle);

            if (NT_SUCCESS(Status)) 
			{
                InTransaction = FALSE;
            }
        } // FwpmTransactionBegin
    } // FwpmEngineOpen

    if (!NT_SUCCESS(Status))
    {
        if (InTransaction) 
		{
            NTSTATUS AbortStatus;
            AbortStatus = FwpmTransactionAbort(Globals.EngineHandle);
            _Analysis_assume_(NT_SUCCESS(AbortStatus));
        }

        if (EngineOpened) 
		{
            FwpmEngineClose(Globals.EngineHandle);
            Globals.EngineHandle = NULL;
        }
    }

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "<-- %!FUNC!, %!STATUS!", Status);
    return Status;
}

VOID
StreamEditUnregisterCallout(VOID)
{
    // Unregister the callouts for Callout #1
    //
    FwpsCalloutUnregisterById(Globals.FlowEstablishedV4Callout1);
    FwpsCalloutUnregisterById(Globals.StreamLayerV4Callout1);

    FwpsCalloutUnregisterById(Globals.FlowEstablishedV6Callout1);
    FwpsCalloutUnregisterById(Globals.StreamLayerV6Callout1);

    FwpmSubLayerDeleteByKey(Globals.EngineHandle, &STREAM_EDITOR_SUBLAYER_1);

    // Unregister the callouts for Callout #2
    //
    if (Globals.MultipleCallouts)
    {
        FwpsCalloutUnregisterById(Globals.FlowEstablishedV4Callout2);
        FwpsCalloutUnregisterById(Globals.StreamLayerV4Callout2);

        FwpsCalloutUnregisterById(Globals.FlowEstablishedV6Callout2);
        FwpsCalloutUnregisterById(Globals.StreamLayerV6Callout2);

        FwpmSubLayerDeleteByKey(Globals.EngineHandle, &STREAM_EDITOR_SUBLAYER_2);
    }

    NT_ASSERT(Globals.EngineHandle != NULL);
    FwpmEngineClose(Globals.EngineHandle);
    Globals.EngineHandle = NULL;
}

_Function_class_(EVT_WDF_DRIVER_UNLOAD)
_IRQL_requires_same_
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
StreamEditEvtDriverUnload(
   _In_ WDFDRIVER DriverObject
   )
{
    ULONG nCount;

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "--> %!FUNC!: (DrvObj %p)", DriverObject);
    InterlockedExchange8( &Globals.DriverUnloading, TRUE);

    StreamEditSignalShutdown();

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "DriverUnload -- Waiting for all the flows to terminate");
    KeWaitForSingleObject(&Globals.ZeroFlowCountEvent, Executive, KernelMode, FALSE, NULL);


    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "DriverUnload -- Calling FwpsInjectionHandleDestroy");
    // FwpsInjectionHandleDestroy will _not_ return to the
    // caller until all pending injections are completed.
    //
    if (Globals.InjectionHandle != NULL)
        FwpsInjectionHandleDestroy(Globals.InjectionHandle);

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "DriverUnload -- Now, uninitializing LW Queues");
    for (nCount = 0; nCount < NUM_WORKITEM_QUEUES; ++nCount)
    {
        LwUninitializeQueue(&Globals.ProcessingQueues[nCount]);
    }

    if (Globals.LookasideCreated)
        ExDeleteLookasideListEx(&Globals.LookasideList);

    if (Globals.EngineHandle != NULL)
        StreamEditUnregisterCallout();

    if (Globals.NetBufferListPool != NULL)
        NdisFreeNetBufferListPool(Globals.NetBufferListPool);

    if (Globals.NdisGenericObj != NULL)
        NdisFreeGenericObject(Globals.NdisGenericObj);

    if (Globals.StringToReplaceMdl != NULL)
        IoFreeMdl(Globals.StringToReplaceMdl);

    if (Globals.StringXMdl != NULL)
        IoFreeMdl(Globals.StringXMdl);

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "<-- %!FUNC!");
    WPP_CLEANUP(DriverObject);
}

VOID
StreamEditInitConfig(
    _In_ const WDFDRIVER driver
    )
/*
    This function loads the default StreamEditor configuration values,
    then overrides any values specified in the registry.
*/
{

    NTSTATUS Status = STATUS_SUCCESS;
    DECLARE_CONST_UNICODE_STRING(stringToFindKey, L"StringToFind");
    DECLARE_CONST_UNICODE_STRING(stringInMiddleKey, L"StringX");
    DECLARE_CONST_UNICODE_STRING(stringToReplaceKey, L"StringToReplace");
    DECLARE_CONST_UNICODE_STRING(inspectionLocalPortKey, L"InspectionLocalPort");
    DECLARE_CONST_UNICODE_STRING(inspectionRemotePortKey, L"InspectionRemotePort");
    DECLARE_CONST_UNICODE_STRING(multiCalloutKey, L"MultipleCallouts");
    DECLARE_CONST_UNICODE_STRING(inspectionDirectionKey, L"InspectionDirection");
    DECLARE_CONST_UNICODE_STRING(thresholdKey, L"BusyThreshold");

    UNICODE_STRING stringValue;
    WCHAR buffer[STR_MAX_SIZE];
    USHORT requiredSize;
    ULONG valueSize;
    ULONG ulongValue;
    WDFKEY hKey;

    // Initialize with default values.
    // String lengths will be initialized later (below).
    //
    Globals.InspectionLocalPort = CFG_LOCAL_PORT;
    Globals.InspectionRemotePort = 0;
    Globals.InspectionDirection = FWP_DIRECTION_MAX; // Inbound + outbound
    Globals.BusyThreshold = 0x4000; // == 16K;
    Globals.MultipleCallouts = TRUE;

    Globals.StringToFind[0] = Globals.StringX[0] = Globals.StringToReplace[0] = '\0';

    Status = WdfDriverOpenParametersRegistryKey(driver, KEY_READ, WDF_NO_OBJECT_ATTRIBUTES, &hKey);
	if (NT_SUCCESS(Status))
	{

		if (NT_SUCCESS(WdfRegistryQueryULong(hKey, &inspectionLocalPortKey, &ulongValue)))
		{
			Globals.InspectionLocalPort = (USHORT)ulongValue;
		}

		if (NT_SUCCESS(WdfRegistryQueryULong(hKey, &inspectionRemotePortKey, &ulongValue)))
		{
			Globals.InspectionRemotePort = (USHORT)ulongValue;
		}

		if (NT_SUCCESS(WdfRegistryQueryULong(hKey, &inspectionDirectionKey, &ulongValue)))
		{
			Globals.InspectionDirection = (UCHAR)ulongValue;
			NT_ASSERT((Globals.InspectionDirection >= 0 && Globals.InspectionDirection <= FWP_DIRECTION_MAX));

			if (Globals.InspectionDirection > FWP_DIRECTION_MAX)
				Globals.InspectionDirection = FWP_DIRECTION_MAX;
		}

		if (NT_SUCCESS(WdfRegistryQueryULong(hKey, &multiCalloutKey, &ulongValue)))
		{
			Globals.MultipleCallouts = !(ulongValue == 0);
		}


		// Attempt to read StringToFind value from registry
		//
		stringValue.Buffer = buffer;
		stringValue.Length = 0;
		stringValue.MaximumLength = sizeof(buffer);			

		Status = WdfRegistryQueryUnicodeString(hKey, &stringToFindKey, &requiredSize, &stringValue);
		if (NT_SUCCESS(Status))
		{
		    // stringValue is NULL terminated.

		    // Translate Unicode string
		    Status = RtlUnicodeToMultiByteN(
		                    Globals.StringToFind,
		                    sizeof(Globals.StringToFind),
		                    &valueSize,
		                    stringValue.Buffer,
		                    (ULONG)requiredSize);

		    if (NT_SUCCESS(Status)) 
			{
		        valueSize -= sizeof(char);
		        Globals.StringToFindLength = valueSize;
		        NT_ASSERT(Globals.StringToFind[valueSize] == '\0');
		    }
		}

		stringValue.MaximumLength = sizeof(buffer);
		//Attempt to read StringX value from registry
		// 
		Status = WdfRegistryQueryUnicodeString(hKey, &stringInMiddleKey, &requiredSize, &stringValue);
		if (NT_SUCCESS(Status))
		{
		    // Translate Unicode string
		    Status = RtlUnicodeToMultiByteN(
		                    Globals.StringX,
		                    sizeof(Globals.StringX),
		                    &valueSize,
		                    stringValue.Buffer,
		                    (ULONG)requiredSize);

		    if (NT_SUCCESS(Status)) 
			{
		        valueSize -= sizeof(char); // NULL terminator.
		        Globals.StringXLength = valueSize;
		        NT_ASSERT(Globals.StringX[valueSize] == '\0');
		    }
		}

		stringValue.MaximumLength = sizeof(buffer);
		// Attempt to read StringToReplace value from registry
		//
        Status = WdfRegistryQueryUnicodeString(hKey, &stringToReplaceKey, &requiredSize, &stringValue);
        if (NT_SUCCESS(Status))
        {
            // Translate Unicode string
            Status = RtlUnicodeToMultiByteN(
                            Globals.StringToReplace,
                            sizeof(Globals.StringToReplace),
                            &valueSize,
                            stringValue.Buffer,
                            (ULONG)requiredSize);

            if (NT_SUCCESS(Status)) 
			{
                valueSize -= sizeof(char);
                Globals.StringToReplaceLength = valueSize;
                NT_ASSERT(Globals.StringToReplace[valueSize] == '\0');
            }
        }

        if (NT_SUCCESS(WdfRegistryQueryULong(hKey, &thresholdKey, &ulongValue))) 
		{
            Globals.BusyThreshold = (size_t)ulongValue << 10;
            NT_ASSERT(Globals.BusyThreshold != 0);
        }

        WdfRegistryClose(hKey);
    }
    else
    {
        DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "WdfDriverOpenParametersRegistryKey failed with %!STATUS!", Status);
    }

    // Calculate the length of tokens to be found/replaced.
    //
	if (Globals.StringToFindLength == 0)
	{
		NT_ASSERT(Globals.StringToFind[0] == 0);

		RtlStringCchCopyA(Globals.StringToFind, STR_MAX_SIZE, "rainy");
		Status = RtlStringCchLengthA(Globals.StringToFind, STR_MAX_SIZE, &Globals.StringToFindLength);

		//Handle Error.
		NT_ASSERT(NT_SUCCESS(Status));
	}

    if (Globals.StringXLength == 0)
    {
        NT_ASSERT(Globals.StringX[0] == 0);

        RtlStringCchCopyA(Globals.StringX, STR_MAX_SIZE, "cloudy");
        Status = RtlStringCchLengthA(Globals.StringX, STR_MAX_SIZE, &Globals.StringXLength);
	
		//Handle Error.
		NT_ASSERT(NT_SUCCESS(Status));
	}

    if (Globals.StringToReplaceLength == 0)
    {
        NT_ASSERT(Globals.StringToReplace[0] == 0);

        RtlStringCchCopyA(Globals.StringToReplace, STR_MAX_SIZE, "sunny");
        Status = RtlStringCchLengthA(Globals.StringToReplace, STR_MAX_SIZE, &Globals.StringToReplaceLength);

		//Handle Error.
		NT_ASSERT(NT_SUCCESS(Status));
    }

    NT_ASSERT(Globals.StringToFindLength != 0);
    NT_ASSERT(Globals.StringXLength != 0);
    NT_ASSERT(Globals.StringToReplaceLength != 0);

    // In this sample, we want to make sure that at least one port (either local or remote) is non-zero.
    //
    if ((Globals.InspectionLocalPort == 0) && (Globals.InspectionRemotePort == 0)) 
	{
        Globals.InspectionLocalPort = CFG_LOCAL_PORT;
    }

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL,"StreamEdit Configuration\r"
                            "\tStringToFind: %s\r\tStringToReplace: %s\r\tStringX: %s\r"
                            "\tInspectionLocalPort: %hu\r\tInspectionRemotePort: %hu\r"
                            "\tInspectionDirection: %!FWP_DIRECTION!\r\tBusyThreshold: 0x%IX\r\tMultiple Callouts: %!bool!",
                            Globals.StringToFind,
                            Globals.StringToReplace,
                            Globals.StringX,
                            Globals.InspectionLocalPort,
                            Globals.InspectionRemotePort,
                            Globals.InspectionDirection,
                            Globals.BusyThreshold,
                            Globals.MultipleCallouts );

}

NTSTATUS
StreamEditInitDriverObjects(
   _Inout_ DRIVER_OBJECT* driverObject,
   _In_ const UNICODE_STRING* registryPath,
   _Out_ WDFDRIVER* pDriver,
   _Out_ WDFDEVICE* pDevice
   )
{
   NTSTATUS Status;
   WDF_DRIVER_CONFIG config;
   PWDFDEVICE_INIT pInit = NULL;

   WDF_DRIVER_CONFIG_INIT(&config, WDF_NO_EVENT_CALLBACK);

   config.DriverInitFlags |= WdfDriverInitNonPnpDriver;
   config.EvtDriverUnload = StreamEditEvtDriverUnload;

   Status = WdfDriverCreate(
               driverObject,
               registryPath,
               WDF_NO_OBJECT_ATTRIBUTES,
               &config,
               pDriver
               );

   if (NT_SUCCESS(Status))
   {
       Status = STATUS_INSUFFICIENT_RESOURCES;
       pInit = WdfControlDeviceInitAllocate(*pDriver, &SDDL_DEVOBJ_KERNEL_ONLY);

       if (pInit)
       {
           WdfDeviceInitSetCharacteristics(pInit, FILE_AUTOGENERATED_DEVICE_NAME, TRUE);
           //WdfDeviceInitSetDeviceType(pInit, FILE_DEVICE_NETWORK);
		   WdfDeviceInitSetDeviceClass(pInit, &WFP_DRIVER_CLASS_GUID);
           WdfDeviceInitSetCharacteristics(pInit, FILE_DEVICE_SECURE_OPEN, TRUE);
           
		   Status = WdfDeviceCreate(&pInit, WDF_NO_OBJECT_ATTRIBUTES, pDevice);

           if (NT_SUCCESS(Status))
           {
               WdfControlFinishInitializing(*pDevice);
           }
       }
   }

   if (!NT_SUCCESS(Status))
   {
       if ( pInit)
			WdfDeviceInitFree(pInit);
   }

   return Status;
}

NTSTATUS
DriverEntry(
    _In_ DRIVER_OBJECT* DriverObject,
    _In_ UNICODE_STRING* RegistryPath
    )
{
   NTSTATUS Status;
   WDFDEVICE WdfDevice;
   WDFDRIVER WdfDriver;
   NET_BUFFER_LIST_POOL_PARAMETERS nblPoolParams = {0};

   WPP_INIT_TRACING(DriverObject, RegistryPath);

   DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT,"--> %!FUNC!: DrvObj %p, Regpath %wZ",  DriverObject, RegistryPath);

   do {

       // Request NX Non-Paged Pool when available
       ExInitializeDriverRuntime(DrvRtPoolNxOptIn);

        //
        // Initialize globals and Configuration structures.
        //

        RtlZeroMemory(&Globals, sizeof(Globals));
        Globals.QueueIndex = (ULONG)-1;

        InitializeListHead(&Globals.FlowContextList);
        KeInitializeSpinLock(&Globals.FlowContextListLock);

        // Initialize DriverUnload/Shutdown Event (to a signalled state)
        //
        KeInitializeEvent(&Globals.ZeroFlowCountEvent, NotificationEvent, TRUE);

        Status = StreamEditInitDriverObjects(
                        DriverObject,
                        RegistryPath,
                        &WdfDriver,
                        &WdfDevice);

        if (!NT_SUCCESS(Status)) 
		{
            DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "StreamEditInitDriverObjects failed with 0x%X", Status);
            break;
        }

        Globals.WdmDevice = WdfDeviceWdmGetDeviceObject(WdfDevice);

        // Initialize and read driver configuration overrides.
        //
        StreamEditInitConfig(WdfDriver);

        Globals.StringToReplaceMdl = IoAllocateMdl(
                                            Globals.StringToReplace,
                                            (ULONG)Globals.StringToReplaceLength,
                                            FALSE,
                                            FALSE,
                                            NULL);
        
		if (Globals.StringToReplaceMdl == NULL) 
		{
            DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "Unable to allocate StringToReplace Mdl");
            Status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        MmBuildMdlForNonPagedPool(Globals.StringToReplaceMdl);

        Globals.StringXMdl = IoAllocateMdl(
                                            Globals.StringX,
                                            (ULONG)Globals.StringXLength,
                                            FALSE,
                                            FALSE,
                                            NULL);

        if (Globals.StringXMdl == NULL) 
		{
            DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "Unable to allocate Mdl#2");
            Status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }
        MmBuildMdlForNonPagedPool(Globals.StringXMdl);

        Globals.NdisGenericObj = NdisAllocateGenericObject(DriverObject, STMEDIT_TAG_NDIS_OBJ, 0);
        if (Globals.NdisGenericObj == NULL)
		{
            DoTraceLevelMessage(TRACE_LEVEL_ERROR, CO_GENERAL, "NdisAllocateGenericObject failed.");
            Status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        //
        // Allocate a NDIS/NBL Pool

        nblPoolParams.Header.Type       = NDIS_OBJECT_TYPE_DEFAULT;
        nblPoolParams.Header.Revision   = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1;
        nblPoolParams.Header.Size       = NDIS_SIZEOF_NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1;
        nblPoolParams.fAllocateNetBuffer    = TRUE;
        nblPoolParams.DataSize          = 0;
        nblPoolParams.PoolTag           = STMEDIT_TAG_NBL_POOL;

        Globals.NetBufferListPool = NdisAllocateNetBufferListPool(
                                        Globals.NdisGenericObj,
                                        &nblPoolParams);

        if (Globals.NetBufferListPool == NULL)
		{
            DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "NdisAllocateNetBufferListPool failed.");
            Status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        Status = ExInitializeLookasideListEx(
                        &Globals.LookasideList,
                        NULL,
                        NULL,
                        NonPagedPool, // POOL_NX_OPTIN_AUTO ==> NonPagedPool := NonPagedPoolNx
                        0,
                        max(sizeof(TASK_ENTRY), sizeof(OUTGOING_STREAM_DATA)),
                        STMEDIT_TAG_TASK_ENTRY,
                        0);

        if (!NT_SUCCESS(Status)) 
		{
            DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "Task LookasideList Creation failed with %!STATUS!", Status);
            break;
        }

        Globals.LookasideCreated = TRUE;

        Status = StreamEditInitializeWorkitemPool();

        if (!NT_SUCCESS(Status)) 
		{
            DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "InitializeWorkerPool failed with %!STATUS!", Status);
            break;
        }

       // Create WFP Injection handle
       //
       Status = FwpsInjectionHandleCreate(AF_UNSPEC, FWPS_INJECTION_TYPE_STREAM, &Globals.InjectionHandle);
       if (!NT_SUCCESS(Status)) 
	   {
           DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "FwpsInjectionHandleCreate failed with %!STATUS!", Status);
           break;
       }

       //
       // Finally, register the sublayer(s) and callouts with WFP
       //
       Status = StreamEditRegisterCallouts(Globals.WdmDevice);
       if (!NT_SUCCESS(Status)) 
	   {
           DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "StreamEditRegisterCallouts failed with %!STATUS!", Status);
           break;
       }

   } while (FALSE);

   DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT, "<-- %!FUNC!, %!STATUS!", Status);

   if (!NT_SUCCESS(Status)) 
   {
	   StreamEditEvtDriverUnload(WdfDriver);
   }

   return Status;
}

BOOLEAN
StreamEditCopyDataForInspection(
_In_ STREAM_FLOW_CONTEXT *FlowContext,
_In_ const FWPS_STREAM_DATA* StreamData,
_In_ SIZE_T BytesToCopy
)
/*
   This function copies stream data described by the FWPS_STREAM_DATA
   structure into a flat buffer.

   Return : TRUE if able to copy stream-data to a flat buffer successfully, FALSE otherwise.

*/
{
    SIZE_T BytesCopied;
    size_t ExistingDataLength = FlowContext->ScratchDataLength;

    NT_ASSERT(BytesToCopy > 0);

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT,
            "--> %!FUNC!: FlowCtx %p, streamData %p, copy %Iu of %Iu, old ScratchLength %Iu",
                    FlowContext,
					StreamData,
                    BytesToCopy,
					StreamData->dataLength,
                    ExistingDataLength);

    NT_ASSERT(FlowContext->ScratchDataOffset == 0);

    // If the existing scratch buffer is not sufficient to accommodate the new data
    // try to allocate a bigger buffer (so that we don't have to keep allocating
    // these for some time.
    //
    if (FlowContext->ScratchBufferSize - ExistingDataLength < BytesToCopy)
    {
        size_t NewBufferSize = BytesToCopy + ExistingDataLength;

        PVOID  NewBuffer = ExAllocatePool2(
                                    POOL_FLAG_NON_PAGED,
                                    (NewBufferSize + (NewBufferSize >> 1) ), // 1.5 times the needed size.
                                    STMEDIT_TAG_FLAT_BUFFER);

        if (NewBuffer == NULL)
		{

            // We are not able to allocate a much bigger buffer ... lets try an exact fit.
            //
            NewBuffer = ExAllocatePool2(POOL_FLAG_NON_PAGED, NewBufferSize, STMEDIT_TAG_FLAT_BUFFER);
        }

        if (NewBuffer != NULL) 
		{

            // Move the existing contents of scratch buffer over to newly allocated buffer
            //
            if (ExistingDataLength > 0) 
			{

                NT_ASSERT(FlowContext->ScratchBuffer != NULL);
                RtlCopyMemory(NewBuffer, FlowContext->ScratchBuffer, ExistingDataLength);
            }
        }

        // Free the old scratch buffer...
        //
        if (FlowContext->ScratchBuffer) 
		{

            ExFreePoolWithTag(FlowContext->ScratchBuffer, STMEDIT_TAG_FLAT_BUFFER);

            FlowContext->ScratchBuffer = NULL;
            FlowContext->ScratchBufferSize = 0;
            FlowContext->ScratchDataLength = 0;
        }

        if (NewBuffer) 
		{

            FlowContext->ScratchBuffer = NewBuffer;
            FlowContext->ScratchBufferSize = NewBufferSize;
            FlowContext->ScratchDataLength = ExistingDataLength;
        }
        else 
		{

            DoTraceLevelMessage(TRACE_LEVEL_ERROR, CO_ENTER_EXIT,
                    "<-- %!FUNC!: FlowCtx %p, Failed to allocate flat buffer for NBL %p",
                            FlowContext, StreamData->netBufferListChain);
            return FALSE;
        }
    }

    // Append the NBL chain data on to (any) existing data in scratch buffer
    //
    FwpsCopyStreamDataToBuffer(
				StreamData,
                (BYTE*)FlowContext->ScratchBuffer + FlowContext->ScratchDataLength,
                BytesToCopy,
                &BytesCopied
                );
    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL,
            "FlowCtx %p, FwpsCopyStreamDataToBuffer flattened %Iu of %Iu bytes",
                FlowContext, BytesCopied, StreamData->dataLength);

    NT_ASSERT(BytesCopied == BytesToCopy);
    FlowContext->ScratchDataLength += BytesCopied;

    DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_ENTER_EXIT,
            "<-- %!FUNC!: FlowCtx %p, new ScratchLength %Iu, return TRUE", FlowContext, FlowContext->ScratchDataLength);
    return TRUE;
}