Transparent Encryption Layer using EasyHook

Created By Saddam Abu Ghaida and Nicolai Tufar

Hello People,

Previously on Easyhook related topic I mentioned something about using it for creating a transparent encryption Layer for Foxpro, since FoxPro doesn’t support Encryption natively

So what I did is to Create my Encryption Functions and used EasyHook to reference my functions inside the altered windows System calls to be able to manage the buffers and the content of that buffers , and how it should be written and read, so form high level point of view when Foxpro Issues write file call it calls my it calls my  write function, which it self calls the actual function and then encrypt the buffer and write it , and the same process goes for reading file : fox pro issues a read file i interrupt this request and execute the actual read file and then decrypt the content in the buffer and give the handler back to Foxpro

and for Foxpro Zapping and Packing you need to alter move file and delete file because those system calls is being called when you call pack or zap.

A good utility for any body who is doing this kind of work to know exactly which process called which system call and how is found her , I used this utility along with IDA to understand and sort of reverse engineer how Xitech Cryptor works, and try to write my own which has nothing to do with Xitech from similarities point of view.

The only problem in my approach that im limited to memory block bounders which is given to me by the actual System Call, Since speed was my main concern and the security was the second in line. So be  of this issue I have no choice but to use permutation or substitution or both of them which I ended up doing with some modifications to fit my criteria. The other issue is of you are using Block Ciphering algorithm you need to have multiple blocks before and after the block you need to encrypt or decrypt in a different buffer, because you couldn’t tell where exactly in which block your data resides :). the other thing you need to take care of the Block cipher padding technique.

the Algorithm that I will include in the code is for demonstration only. It will give you an idea where to start and how to do transparent encryption layer not only for screwed up database such as fox pro, but for any type of document of file by having also some modification from the caller application 🙂

The algorithm I will attach will do the following

1. I hard coded a random seed  between 0 and 255 hex values which represents the ascii table

2. I take user password and reverse it and then add 8 random bytes to it so i could use it later on for ASCII table rotation

3. I take the resulting password and XOR with every byte in the random ASCII Table.

4. after XOR operations we will have a table where the index number is the actual ASCII value and the replacement is the value of that index. so the same ASCII table is used for encryption and decryption

5. if you want to prevent statistical attack you could use the location of the Character in the file comes in handy, because you could check if the location is od and even to do more operations or you could take the mod of the location to 255 after 255 characters or both of operations.

The code are entirely written in C# and you need EasyHook Libraries to be able to run the code unless you decided to go with windows detour and write the entire code in C/C++. the file complied as DLL/COM+, which you can use from any programming platform.

but you need to register the file before start using it. and I made it like this in order to separate the normal calls from my calls, and inside I have a class which keeps track of the files that it has been registered and unregistered

there is a part where im logging the password to Linux Syslog server encrypted which my own Certificate but im not going to put this library for the time being, because it is a different topic, so you could remove it. The other thing im logging debugging messages as Windows Event. but you need to create the reg key for log under “Local machine -> system -> current version -> services -> eventlog > application > SysHook” and the value should be the path to “EventLogMessages.dll” . i hope that i didn’t forget any thing? .

Please if you have any question or comment don’t hesitate to ask or comment.

 


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
using EasyHook;
using System;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Security.Cryptography;
using System.EnterpriseServices;
using System.Security.Principal;

[assembly: ApplicationName("CryptoLibrary")]
[assembly: Description("Transparent Encryption Library")]
[assembly: ApplicationActivation(ActivationOption.Server)]
[assembly: ApplicationAccessControl(false)]

namespace Test.SystemHook
{

[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[Guid("231d685b-6e22-49ef-a046-74e187ed0d21")]
public interface SystemHookInterface : EasyHook.IEntryPoint
{
bool RegisterFile(string filePath, string Password);
bool UnRegisterFile(string filePath);
//byte[] PaddPassword(string password);
byte[] maskASCIITable(string password);
bool encodeFile(string decodedSrcPath, string encodedDstPath, string passowrd);
bool decodeFile(string encodeSrcPath, string decodedDstPath, string passowrd);

//Debug
bool setDebug(bool status);

}

[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("Cryptor.SystemHook")]
[Guid("54c0c685-4ef2-4a1a-8693-b5773dbed295")]
//[Transaction(TransactionOption.Required)]
public unsafe class SystemHook : SystemHookInterface
{

LocalHook ReadHook = null;
LocalHook WriteHook = null;
LocalHook CreateWHook = null;
LocalHook CreateAHook = null;
LocalHook CloseHook = null;
LocalHook MoveAHook = null;
LocalHook MoveWHook = null;
LocalHook DeleteAHook = null;
LocalHook DeleteWHook = null;

static bool DEBUG = false;
static Dictionary<IntPtr, FilesInfo> hFileDict = new Dictionary<IntPtr, FilesInfo>();
static List FilesInfoList = new List();
// static CryptorService cryptorService = new CryptorService();
static string sSource = "SysHook";
static string sLog = "Application";

static bool alreadyHooked = false;

public static byte[] RandomAsciiTable =
{
0x52,0x91,0x3b,0xf5,0x5f,0x9f,0x99,0x6c,0xfd,0xb4,0xe6,0xee,
0xfc,0xdf,0xd8,0xe1,0x64,0x4e,0x75,0x43,0x5a,0x56,0x84,0xa8,
0xa0,0x5d,0x34,0xb5,0xc7,0x58,0xc4,0x12,0x19,0xbf,0x4 ,0xab,
0xea,0x2c,0xb2,0x51,0x27,0xb9,0x73,0xe2,0xfa,0x3 ,0xc ,0xf7,
0x3f,0xed,0xca,0xf2,0x98,0x6e,0xda,0x6a,0x55,0xd7,0x85,0x71,
0x36,0x8b,0xfb,0x54,0xbb,0xc0,0xe ,0x87,0xf3,0x9b,0xd6,0x62,
0x8 ,0x7c,0x6 ,0xd1,0xbe,0x4c,0x5b,0x96,0x93,0x7b,0x60,0x70,
0xff,0xdb,0x22,0x44,0x16,0x5e,0x17,0xa9,0xad,0x9d,0x9 ,0x9e,
0x94,0xf8,0x3a,0xb7,0x4d,0x1c,0x1d,0x2b,0x9a,0x92,0x65,0x4b,
0x5c,0x81,0xf4,0x4f,0x21,0x15,0x40,0xb3,0x49,0x4a,0x23,0xd3,
0x6b,0xb8,0xcd,0x5 ,0x29,0x78,0xa4,0x7e,0xef,0xce,0x2d,0xb ,
0x8e,0xe3,0xa7,0x32,0x25,0x77,0xa3,0xe8,0xe4,0xcc,0x74,0x18,
0x89,0xdd,0x0 ,0x88,0x67,0x66,0x61,0x3d,0x1 ,0xf ,0xc8,0xd9,
0x8f,0x6d,0x10,0x82,0xde,0x83,0x37,0x79,0x45,0x33,0x63,0x11,
0x59,0xae,0xba,0x86,0xa ,0x95,0x7d,0xbd,0xf6,0x7f,0x90,0xa2,
0x57,0xec,0xc3,0xc2,0x42,0xf0,0xd0,0x48,0xc9,0xc5,0xcf,0xb1,
0x8a,0x2a,0x2 ,0x46,0x26,0x8c,0x1b,0xa6,0xaa,0xac,0xeb,0xf1,
0x76,0x69,0x1f,0xe9,0x7a,0xe7,0x8d,0x53,0x28,0x38,0xa1,0x6f,
0xa5,0x50,0xb0,0xd2,0x20,0x2e,0xc1,0x97,0x2f,0x13,0x39,0x24,
0xaf,0x9c,0xd4,0x41,0xd5,0x31,0xe0,0xe5,0x72,0x3c,0x47,0x30,
0xb6,0x3e,0x7 ,0xbc,0x35,0xdc,0x14,0x1e,0xd ,0xcb,0xfe,0xf9,
0xc6,0x80,0x1a,0x68
};

static byte[] passwordPad = { 0x3d, 0x44, 0xa3, 0x5f, 0x23, 0x27, 0x3b, 0x61 };

static byte[] maskedAsciiTable = new byte[RandomAsciiTable.Length];

///
/// hooks to CreateFile,ReadFile,WriteFile in kernel32.dll
///

///exception stack trace /// excpetion stack trace or null for sucess
protected bool Hook()
{

if (alreadyHooked == true)
return true;

alreadyHooked = true;
try
{
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);

}
catch (Exception)
{
}

try
{
if (DEBUG) EventLog.WriteEntry(sSource, "Hooking ");

//Initialize Hooks
CreateWHook = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "CreateFileW"), new DCreateFileW(CreateFileWHook), this);
CreateWHook.ThreadACL.SetExclusiveACL(new Int32[0]);

CreateAHook = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "CreateFileA"), new DCreateFileA(CreateFileAHook), this);
CreateAHook.ThreadACL.SetExclusiveACL(new Int32[0]);

ReadHook = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "ReadFile"), new DReadFile(ReadFileHook), this);
ReadHook.ThreadACL.SetExclusiveACL(new Int32[0]);

WriteHook = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "WriteFile"), new DWriteFile(WriteFileHook), this);
WriteHook.ThreadACL.SetExclusiveACL(new Int32[0]);

CloseHook = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "CloseHandle"), new DCloseHandle(CloseHandleHook), this);
CloseHook.ThreadACL.SetExclusiveACL(new Int32[0]);

MoveAHook = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "MoveFileA"), new DMoveFileA(MoveFileAHook), this);
MoveAHook.ThreadACL.SetExclusiveACL(new Int32[0]);

MoveWHook = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "MoveFileW"), new DMoveFileW(MoveFileWHook), this);
MoveWHook.ThreadACL.SetExclusiveACL(new Int32[0]);

DeleteAHook = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "DeleteFileA"), new DDeleteFileA(DeleteFileAHook), this);
DeleteAHook.ThreadACL.SetExclusiveACL(new Int32[0]);

DeleteWHook = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "DeleteFileW"), new DDeleteFileW(DeleteFileWHook), this);
DeleteWHook.ThreadACL.SetExclusiveACL(new Int32[0]);

return true;
}
catch (Exception e)
{
EventLog.WriteEntry(sSource, "Hooking Error:\n\n" + e.Message + "\n" + e.StackTrace);
//CreateHook.Dispose();
//ReadHook.Dispose();
//WriteHook.Dispose();

return false;
}
}

///
/// Unhook CreateFile,ReadFile,WriteFile
///

///exception stack trace /// excpetion stack trace or null for sucess
protected bool unHook()
{
//alreadyHooked = false;
return true; //no unhooking
/*
try
{
EventLog.WriteEntry(sSource, "UnHooking");
CreateWHook.Dispose();
CreateAHook.Dispose();
ReadHook.Dispose();
WriteHook.Dispose();

FilesInfoList.Clear();
hFileDict.Clear();

return true;
}
catch (Exception)
{
return false;
}
*/


}

public SystemHook()
{
EventLog.WriteEntry(sSource, "SystemHook() -- Constructor -- SystemHook Loaded");
Hook();
}

~SystemHook()
{
EventLog.WriteEntry(sSource, "~SystemHook() -- Destructor -- SystemHook Unloaded");
unHook();
}

///
/// CreateFileW Wrapper
///

////////////////////////
[UnmanagedFunctionPointer(CallingConvention.StdCall,
CharSet = CharSet.Unicode, SetLastError = true)]

delegate IntPtr DCreateFileW(String InFileName, UInt32 InDesiredAccess, UInt32 InShareMode,
IntPtr InSecurityAttributes, UInt32 InCreationDisposition,
UInt32 InFlagsAndAttributes, IntPtr InTemplateFile);

///
/// Kernel32 CreateFileW
///

////////////////////////
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true,
CallingConvention = CallingConvention.StdCall)]

static extern IntPtr CreateFileW(String InFileName, UInt32 InDesiredAccess, UInt32 InShareMode,
IntPtr InSecurityAttributes, UInt32 InCreationDisposition,
UInt32 InFlagsAndAttributes, IntPtr InTemplateFile);

///
/// CreateFileA Wrapper
///

////////////////////////
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi, SetLastError = true)]

delegate IntPtr DCreateFileA(String InFileName, UInt32 InDesiredAccess, UInt32 InShareMode,
IntPtr InSecurityAttributes, UInt32 InCreationDisposition,
UInt32 InFlagsAndAttributes, IntPtr InTemplateFile);

///
/// Kernel32 CreateFileA
///

////////////////////////
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true,
CallingConvention = CallingConvention.StdCall)]

static extern IntPtr CreateFileA(String InFileName, UInt32 InDesiredAccess, UInt32 InShareMode,
IntPtr InSecurityAttributes, UInt32 InCreationDisposition,
UInt32 InFlagsAndAttributes, IntPtr InTemplateFile);

///
/// ReadFile Wrapper
///

///handle to file ///data buffer ///number of bytes to read ///number of bytes read ///overlapped buffer ///

[UnmanagedFunctionPointer(CallingConvention.StdCall,
CharSet = CharSet.Ansi, SetLastError = true)]

unsafe delegate bool DReadFile(IntPtr hFile, void* pBuffer, int NumberOfBytesToRead,
int* pNumberOfBytesRead, int Overlapped);

///
/// Kernel32 ReadFile
///

//////////////////
[DllImport("kernel32", SetLastError = true)]

static extern unsafe bool ReadFile(IntPtr hFile, void* pBuffer, int NumberOfBytesToRead,
int* pNumberOfBytesRead, int Overlapped);

///
/// WriteFile Wrapper
///

//////////////////
///
[UnmanagedFunctionPointer(CallingConvention.StdCall,
CharSet = CharSet.Unicode, SetLastError = true)]

delegate bool DWriteFile(IntPtr hFile, void* lpBuffer, uint nNumberOfBytesToWrite,
out uint lpNumberOfBytesWritten, [In]
ref System.Threading.NativeOverlapped lpOverlapped);

///
/// Kernel32 WriteFile
///

//////////////////
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true,
CallingConvention = CallingConvention.StdCall)]

static extern bool WriteFile(IntPtr hFile, void* lpBuffer, uint nNumberOfBytesToWrite,
out uint lpNumberOfBytesWritten,
[In] ref System.Threading.NativeOverlapped lpOverlapped);

///
/// CloseHandle Wrapper
///

//////
[UnmanagedFunctionPointer(CallingConvention.StdCall,
CharSet = CharSet.Unicode, SetLastError = true)]

delegate bool DCloseHandle(IntPtr hObject);

///
/// Kernel32 CloseHandle
///

//////
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true,
CallingConvention = CallingConvention.StdCall)]

static extern bool CloseHandle(IntPtr hObject);

///
/// Kernel32 MoveFileA
///

/////////

[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int MoveFileA(String lpExistingFileName, String lpNewFileName);

[UnmanagedFunctionPointer(CallingConvention.StdCall,
CharSet = CharSet.Ansi, SetLastError = true)]
delegate int DMoveFileA(String lpExistingFileName, String lpNewFileName);

///
/// Kernel32 MoveFileW
///

/////////
[UnmanagedFunctionPointer(CallingConvention.StdCall,
CharSet = CharSet.Unicode, SetLastError = true)]
delegate int DMoveFileW(String lpExistingFileName, String lpNewFileName);

[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int MoveFileW(String lpExistingFileName, String lpNewFileName);

///
/// Kernel32 DeleteFileA
///

//////
[UnmanagedFunctionPointer(CallingConvention.StdCall,
CharSet = CharSet.Ansi, SetLastError = true)]
delegate bool DDeleteFileA(string path);

[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
static extern bool DeleteFileA(string path);

///
/// Kernel32 DeleteFileW
///

//////
[UnmanagedFunctionPointer(CallingConvention.StdCall,
CharSet = CharSet.Unicode, SetLastError = true)]
delegate bool DDeleteFileW(string path);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool DeleteFileW(string path);

/****************************************************************************************/
///
/// CreateFileWHook
///

////////////////////////
protected static unsafe IntPtr CreateFileWHook(String InFileName, UInt32 InDesiredAccess,
UInt32 InShareMode, IntPtr InSecurityAttributes,
UInt32 InCreationDisposition, UInt32 InFlagsAndAttributes,
IntPtr InTemplateFile)
{

IntPtr results = CreateFileW(InFileName, InDesiredAccess, InShareMode, InSecurityAttributes,
InCreationDisposition, InFlagsAndAttributes, InTemplateFile);

try
{
// Add new entry to hFileDict
string x = Path.GetFullPath(InFileName).ToLower();
foreach (FilesInfo fi in FilesInfoList)
{
if (fi.getFilePath().Equals(x))
{
if (DEBUG) EventLog.WriteEntry(sSource, "CreateFileW(): " + InFileName + " hFile=" + results);
if (hFileDict.ContainsKey(results) == false)
hFileDict.Add(results, fi);
break;
}
}

}
catch (Exception e)
{
EventLog.WriteEntry(sSource, "CreateFileW() error: " + InFileName + "\n\n" + e.StackTrace);

}

return results;
}

protected static unsafe IntPtr CreateFileAHook(String InFileName, UInt32 InDesiredAccess,
UInt32 InShareMode, IntPtr InSecurityAttributes,
UInt32 InCreationDisposition, UInt32 InFlagsAndAttributes,
IntPtr InTemplateFile)
{

IntPtr results = CreateFileA(InFileName, InDesiredAccess, InShareMode, InSecurityAttributes,
InCreationDisposition, InFlagsAndAttributes, InTemplateFile);

try
{
// Add new entry to hFileDict

string x = Path.GetFullPath(InFileName).ToLower();
foreach (FilesInfo fi in FilesInfoList)
{
if (fi.getFilePath().Equals(x))
{
if (DEBUG) EventLog.WriteEntry(sSource, "CreateFileA() : " + InFileName + " hFile=" + results);
if (hFileDict.ContainsKey(results) == false)
hFileDict.Add(results, fi);
break;
}
}

}
catch (Exception e)
{
EventLog.WriteEntry(sSource, "CreateFileA() error: " + InFileName + "\n\n" + e.StackTrace);

}

return results;
}

///
/// ReadFileHook
///

//////////////////
protected unsafe bool ReadFileHook(IntPtr hFile, void* pBuffer, int NumberOfBytesToRead,
int* pNumberOfBytesRead, int Overlapped)
{

bool results = ReadFile(hFile, pBuffer, NumberOfBytesToRead, pNumberOfBytesRead, Overlapped);

if (results != false && hFileDict.ContainsKey(hFile))
{
if (DEBUG) EventLog.WriteEntry(sSource, "ReadFile(hFile=" + hFile + ", pBuffer=, NumberOfBytesToRead=" + NumberOfBytesToRead + ", pNumberOfBytesRead=" + (*pNumberOfBytesRead) + ", Overlapped=" + Overlapped + ")");
FilesInfo fi = hFileDict[hFile];
try
{
byte* x = (byte*)pBuffer;
for (uint i = 0; i < *pNumberOfBytesRead; i++)
{
*(x + i) = decodeByte(*(x + i), fi.maskedAsciiTable);
}

}
catch (Exception) { }
}

return results;
}

///
/// WriteFileHook
///

//////////////////
protected bool WriteFileHook(IntPtr hFile, void* lpBuffer, uint nNumberOfBytesToWrite,
out uint lpNumberOfBytesWritten,
[In] ref System.Threading.NativeOverlapped lpOverlapped)
{

bool results = false;
lpNumberOfBytesWritten = 0; //so that Visual Studio would not complain
if (hFileDict.ContainsKey(hFile)) //file is registered
{
if (DEBUG) EventLog.WriteEntry(sSource, "Writing File: hFile=" + hFile);
FilesInfo fi = hFileDict[hFile];
try //encrypt
{
byte* x = (byte*)lpBuffer;
for (uint i = 0; i < nNumberOfBytesToWrite; i++)
{
*(x + i) = encodeByte(*(x + i), fi.maskedAsciiTable);
}

results = WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite,
out lpNumberOfBytesWritten, ref lpOverlapped);

//Unencrypt the buffer before returning. We do not want to mess with application's buffer
x = (byte*)lpBuffer;
for (uint i = 0; i < nNumberOfBytesToWrite; i++)
{
*(x + i) = decodeByte(*(x + i), fi.maskedAsciiTable);
}

}
catch (Exception e)
{
EventLog.WriteEntry(sSource, "Error in WriteFileHook\n\n" + e.StackTrace);
}
}
else //file is not registered
{
results = WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite,
out lpNumberOfBytesWritten, ref lpOverlapped);
}

return results;
}

///
/// CloseHandleHook removes the handle from hFileDict object
///

//////
protected bool CloseHandleHook(IntPtr hObject)
{
if (hFileDict.ContainsKey(hObject))
{
if (DEBUG) EventLog.WriteEntry(sSource, "Closing File: hFile=" + hObject);
hFileDict.Remove(hObject);
}
return CloseHandle(hObject);
}

//FileLocalHook fileLocalHook = new FileLocalHook();

//public bool RegisterFile(string filePath, string password)
//{
// return fileLocalHook.RegisterFile(filePath, password);
//}

//public bool UnRegisterFile(string filePath)
//{
// return fileLocalHook.UnRegisterFile(filePath);
//}

///
/// MoveFileA Hook
///

/////////
protected int MoveFileAHook(String lpExistingFileName, String lpNewFileName)
{
string x = Path.GetFullPath(lpNewFileName).ToLower();
foreach (FilesInfo fi in FilesInfoList)
{
if (fi.getFilePath().Equals(x))
{
encodeFile(lpExistingFileName, fi.getFilePath() + ".tmp", fi.getPassword());

if (File.Exists(lpExistingFileName))
{
DeleteFileA(lpExistingFileName);
if (DEBUG) EventLog.WriteEntry(sSource, lpExistingFileName + " has been deleted");
}
//UnRegisterFile(fi.getFilePath());
MoveFileA(fi.getFilePath() + ".tmp", lpExistingFileName);
//RegisterFile(fi.getFilePath(), fi.getPassword());

if (DEBUG) EventLog.WriteEntry(sSource, "MoveFileA " +fi.getFilePath() + ".tmp has been moved to " + lpExistingFileName);
}

}
//if (DEBUG) EventLog.WriteEntry(sSource, "MoveFileA -> lpExistingFileName : " + lpExistingFileName + " " + "lpNewFileName : " + lpNewFileName);
return MoveFileA(lpExistingFileName, lpNewFileName);
}

///
/// MoveFileWHook
///

/////////
protected int MoveFileWHook(String lpExistingFileName, String lpNewFileName)
{
string x = Path.GetFullPath(lpNewFileName).ToLower();
foreach (FilesInfo fi in FilesInfoList)
{
if (fi.getFilePath().Equals(x))
{
if (DEBUG) EventLog.WriteEntry(sSource, "MoveFileW : file is registered " + fi.getFilePath());

encodeFile(lpExistingFileName, fi.getFilePath() + ".tmp", fi.getPassword());

if (File.Exists(lpExistingFileName))
{
DeleteFileW(lpExistingFileName);
if (DEBUG) EventLog.WriteEntry(sSource, lpExistingFileName + " has been deleted");
}

MoveFileW(fi.getFilePath() + ".tmp", lpExistingFileName);
if (DEBUG) EventLog.WriteEntry(sSource,"MoveFileW" + fi.getFilePath() + ".tmp has been moved to " + lpExistingFileName);

}
}
//if (DEBUG) EventLog.WriteEntry(sSource, "MoveFileW -> lpExistingFileName : " + lpExistingFileName + " " + "lpNewFileName : " + lpNewFileName);
return MoveFileW(lpExistingFileName, lpNewFileName);
}

///
/// DeleteFileA Hook
///

//////
protected bool DeleteFileAHook(string path)
{
string x = Path.GetFullPath(path).ToLower();
foreach (FilesInfo fi in FilesInfoList)
{
if (fi.getFilePath().Equals(x))
{
return DeleteFileA(path);
//return true;
}
}
return DeleteFileA(path);
}

///
/// DeleteFileW Hook
///

//////
protected bool DeleteFileWHook(string path)
{
string x = Path.GetFullPath(path).ToLower();
foreach (FilesInfo fi in FilesInfoList)
{
if (fi.getFilePath().Equals(x))
{
return DeleteFileW(path);
//return true;
}
}
return DeleteFileW(path);
}

///
/// Converts password to bytes -> reverse it -> add password padd
///

//////
protected byte[] PaddPassword(string password)
{
byte[] passwordInBytes = ASCIIEncoding.ASCII.GetBytes(password);
byte[] PaddedPassword = new byte[passwordInBytes.Length + passwordPad.Length];

Array.Reverse(passwordInBytes);
// PaddedPassword = passwordInBytes;
Buffer.BlockCopy(passwordInBytes, 0, PaddedPassword, 0, passwordInBytes.Length);
Buffer.BlockCopy(passwordPad, 0, PaddedPassword, PaddedPassword.Length - passwordPad.Length, passwordPad.Length);

return PaddedPassword;

}

///
/// Randomize the substitution table by Xor ing it with the password
///

//////
public byte[] maskASCIITable(string password)
{

// byte[] randomizedMask = RandomAsciiTable;
//byte[] randomizedMask = new byte[RandomAsciiTable.Length];
Buffer.BlockCopy(RandomAsciiTable, 0, maskedAsciiTable, 0, RandomAsciiTable.Length);

byte[] paddedPassword = PaddPassword(password);

for (int i = 0; i < paddedPassword.Length; i++)
{
for (int j = 0; j < maskedAsciiTable.Length; j++)
{
maskedAsciiTable[j] ^= paddedPassword[i];
}
}

byte[] result = new byte[RandomAsciiTable.Length];
Buffer.BlockCopy(maskedAsciiTable, 0, result, 0, RandomAsciiTable.Length);

return result;
}

///
/// Encodes byte based on the random ASCII table
///

/////////
protected byte encodeByte(byte decodedByte, string password)
{
//byte[] maskedAsciiTable = maskASCIITable(password);

int aphaIndicimal = Convert.ToInt32(decodedByte);

return (maskedAsciiTable[aphaIndicimal]);

}

///
/// Encodes byte based on the given ASCII table
///

/////////
protected byte encodeByte(byte decodedByte, byte[] theAsciiTable)
{
//byte[] maskedAsciiTable = maskASCIITable(password);

int aphaIndicimal = Convert.ToInt32(decodedByte);

return (theAsciiTable[aphaIndicimal]);

}

///
/// Decode byte based on the random ASCII table
///

/////////
protected byte decodeByte(byte encodedByte, string password)
{
//byte[] maskedAsciiTable = maskASCIITable(password);
byte decodedByte = 0;

for (int i = 0; i < maskedAsciiTable.Length; i++)
{
if (maskedAsciiTable[i] == encodedByte)
{
decodedByte = Convert.ToByte(i);
break;
}
}
return decodedByte;
}

///
/// Decode byte based on the given ASCII table
///

/////////
protected byte decodeByte(byte encodedByte, byte[] theAsciiTable)
{
//byte[] maskedAsciiTable = maskASCIITable(password);
byte decodedByte = 0;

for (int i = 0; i < theAsciiTable.Length; i++)
{
if (theAsciiTable[i] == encodedByte)
{
decodedByte = Convert.ToByte(i);
break;
}
}
return decodedByte;
}

///
/// Encodes file
///

/////////public bool encodeFile(string decodedSrcPath, string encodedDstPath, string passowrd)
{
if (DEBUG) EventLog.WriteEntry(sSource, "encodeFile("+decodedSrcPath+","+encodedDstPath+")");
maskASCIITable(passowrd);
FileStream fsRead = new FileStream(decodedSrcPath, FileMode.Open, FileAccess.Read);
FileStream fsWrite = new FileStream(encodedDstPath, FileMode.OpenOrCreate, FileAccess.Write);

if (DEBUG) EventLog.WriteEntry(sSource, "encodeFilec --- readbuffer");
byte[] readBuffer = new byte[fsRead.Length];

int numBytesToRead = (int)fsRead.Length;
int numBytesRead = 0;

if (DEBUG) EventLog.WriteEntry(sSource, "encodeFilec --- beforewhileloop");
while (numBytesToRead > 0)
{
int n = fsRead.Read(readBuffer, numBytesRead, numBytesToRead);

if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
if (DEBUG) EventLog.WriteEntry(sSource, "encodeFilec --- finished readeing, closing");

fsRead.Close();

numBytesToRead = readBuffer.Length;

if (DEBUG) EventLog.WriteEntry(sSource, "encodeFilec --- before writing buff");
foreach (byte character in readBuffer)
fsWrite.WriteByte(encodeByte(character, passowrd));

if (DEBUG) EventLog.WriteEntry(sSource, "encodeFilec --- finished writing, closing");
fsWrite.Close();
// Log the encrypted password

if (DEBUG) EventLog.WriteEntry(sSource, "encodeFilec --- before get current user");
try
{

WindowsIdentity LoggedUser = WindowsIdentity.GetCurrent();
string syslogMessage = encodedDstPath + " has been encrypted with " + "[" +
passowrd + "]" + " by " + LoggedUser.Name;

if (DEBUG) EventLog.WriteEntry(sSource, "encodeFilec --- create syslog object");
SysLog.SysLog syslog = new SysLog.SysLog("10.1.46.10", SysLog.SysLog.Facility.Local5);

if (DEBUG) EventLog.WriteEntry(sSource, "encodeFilec --- send syslog");
syslog.Send(SysLog.SysLog.Priority.Informational, DateTime.Now, syslog.EncryptSyslog(syslogMessage));
}
catch (Exception e)
{
if (DEBUG) EventLog.WriteEntry(sSource, e.StackTrace);
}

return true;
}

///
/// Decode file
///

/////////public bool decodeFile(string encodeSrcPath, string decodedDstPath, string passowrd)
{
maskASCIITable(passowrd);
FileStream fsRead = new FileStream(encodeSrcPath, FileMode.Open, FileAccess.Read);
FileStream fsWrite = new FileStream(decodedDstPath, FileMode.OpenOrCreate, FileAccess.Write);

byte[] readBuffer = new byte[fsRead.Length];

int numBytesToRead = (int)fsRead.Length;
int numBytesRead = 0;

while (numBytesToRead > 0)
{
int n = fsRead.Read(readBuffer, numBytesRead, numBytesToRead);

if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}

fsRead.Close();

numBytesToRead = readBuffer.Length;

foreach (byte character in readBuffer)
fsWrite.WriteByte(decodeByte(character, passowrd));

fsWrite.Close();
return true;
}

//#region SystemHookInterface Members

///
/// registers user to the file inorder to start transperant Enc/Dec
///

///file path ///user password ///
[AutoComplete]
public bool RegisterFile(string filePath, string password)
{
//bool hookResult = Hook();

string x = Path.GetFullPath(filePath).ToLower();
byte[] theAsciiTable = maskASCIITable(password);

// see if the file already registered
foreach (FilesInfo fi in FilesInfoList)
{
if (fi.getFilePath().Equals(x))
{
return true;
//return hookResult; // do not register if it is already registered
}
}

if (DEBUG) EventLog.WriteEntry(sSource, "Registering File: " + filePath + ", FullPath: " + x);

FilesInfo fileInfo = new FilesInfo();
fileInfo.setFilePath(x);
fileInfo.setPassword(password);
fileInfo.maskedAsciiTable = theAsciiTable;
FilesInfoList.Add(fileInfo);

return true;
}

///
/// Unregisters user From the File
///

///file path ///
[AutoComplete]
public bool UnRegisterFile(string filePath)
{

string x = Path.GetFullPath(filePath).ToLower();
if (DEBUG) EventLog.WriteEntry(sSource, "Unregestering File: " + filePath + ", FullPath: " + x);

foreach (FilesInfo fi in FilesInfoList)
{
if (fi.getFilePath().Equals(x))
{
FilesInfoList.Remove(fi);
break;
}
}

//bool unhookResult = unHook();
return true;
}

///
/// Enable/Disable Debuging
///

//////
[AutoComplete]
public bool setDebug(bool status)
{
DEBUG = status;
return status;
}
//#endregion
}

///
/// This class holds file information objects
///

public class FilesInfo
{
private string filePath;
private string passowrd;
public byte[] maskedAsciiTable { get; set; }

public void setFilePath(string filePath) { this.filePath = filePath; }

public string getFilePath() { return filePath; }

public void setPassword(string password) { this.passowrd = password; }

public string getPassword() { return passowrd; }

}
}
Posted in Cryptography, Programming and tagged , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink. RSS feed for this post. Leave a trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

Swedish Greys - a WordPress theme from Nordic Themepark.