EaseFilter Demo Project
FilterAPI.cs
Go to the documentation of this file.
1 //
3 // (C) Copyright 2011 EaseFilter Technologies Inc.
4 // All Rights Reserved
5 //
6 // This software is part of a licensed software product and may
7 // only be used or copied in accordance with the terms of that license.
8 //
10 
11 using System;
12 using System.Text;
13 using System.IO;
14 using System.Collections;
15 using System.Collections.Generic;
16 using Microsoft.Win32.SafeHandles;
17 using System.Runtime.InteropServices;
18 using System.Security.Principal;
19 using System.Security.Cryptography;
20 
21 
22 namespace EaseFilter.CommonObjects
23 {
24 
25  static public class FilterAPI
26  {
27  public delegate Boolean FilterDelegate(IntPtr sendData, IntPtr replyData);
28  public delegate void DisconnectDelegate();
29  static GCHandle gchFilter;
30  static GCHandle gchDisconnect;
31  static bool isFilterStarted = false;
32  public const int MAX_FILE_NAME_LENGTH = 1024;
33  public const int MAX_SID_LENGTH = 256;
34  public const int MAX_MESSAGE_LENGTH = 65536;
35  public const int MAX_PATH = 260;
36  public const int MAX_ERROR_MESSAGE_SIZE = 1024;
37  public const uint MESSAGE_SEND_VERIFICATION_NUMBER = 0xFF000001;
38  public const uint GENERIC_WRITE = 0x40000000;
39  public const uint AES_TAG_KEY = 0xccb76e80;
40 
41  static Dictionary<byte[], string> userNameTable = new Dictionary<byte[], string>(new ByteArrayComparer());
42  static Dictionary<uint, string> processNameTable = new Dictionary<uint, string>();
43 
44  //for encryption default IV key
45  public static byte[] DEFAULT_IV_TAG = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
46 
47  public enum FilterType : uint
48  {
55  }
56 
57  public enum BooleanConfig : uint
58  {
59  ENABLE_NO_RECALL_FLAG = 0x00000001, //for easetag, if it is true, after the reparsepoint file was opened, it won't restore data back for read and write.
60  DISABLE_FILTER_UNLOAD_FLAG = 0x00000002, //if it is true, the filter driver can't be unloaded.
61  ENABLE_SET_OFFLINE_FLAG = 0x00000004, //for virtual file, it will set offline attribute if it is true.
62  ENABLE_DEFAULT_IV_TAG = 0x00000008, //for encryption, it is true, it will use the default IV tag to encrypt the files.
63 
64  }
65 
66 
67  public enum FilterCommand
68  {
69  FILTER_SEND_FILE_CHANGED_EVENT = 0x00010001,
70  FILTER_REQUEST_USER_PERMIT = 0x00010002,
71  FILTER_REQUEST_ENCRYPTION_KEY = 0x00010003,
73 
74  }
75 
79  public enum MessageType : uint
80  {
81  PRE_CREATE = 0x00000001,
82  POST_CREATE = 0x00000002,
83  PRE_FASTIO_READ = 0x00000004,
84  POST_FASTIO_READ = 0x00000008,
85  PRE_CACHE_READ = 0x00000010,
86  POST_CACHE_READ = 0x00000020,
87  PRE_NOCACHE_READ = 0x00000040,
88  POST_NOCACHE_READ = 0x00000080,
89  PRE_PAGING_IO_READ = 0x00000100,
90  POST_PAGING_IO_READ = 0x00000200,
91  PRE_FASTIO_WRITE = 0x00000400,
92  POST_FASTIO_WRITE = 0x00000800,
93  PRE_CACHE_WRITE = 0x00001000,
94  POST_CACHE_WRITE = 0x00002000,
95  PRE_NOCACHE_WRITE = 0x00004000,
96  POST_NOCACHE_WRITE = 0x00008000,
97  PRE_PAGING_IO_WRITE = 0x00010000,
98  POST_PAGING_IO_WRITE = 0x00020000,
99  PRE_QUERY_INFORMATION = 0x00040000,
100  POST_QUERY_INFORMATION = 0x00080000,
101  PRE_SET_INFORMATION = 0x00100000,
102  POST_SET_INFORMATION = 0x00200000,
103  PRE_DIRECTORY = 0x00400000,
104  POST_DIRECTORY = 0x00800000,
105  PRE_QUERY_SECURITY = 0x01000000,
106  POST_QUERY_SECURITY = 0x02000000,
107  PRE_SET_SECURITY = 0x04000000,
108  POST_SET_SECURITY = 0x08000000,
109  PRE_CLEANUP = 0x10000000,
110  POST_CLEANUP = 0x20000000,
111  PRE_CLOSE = 0x40000000,
112  POST_CLOSE = 0x80000000,
113 
114  }
115 
116 
117  public enum EVENTTYPE : uint
118  {
119  NONE = 0,
120  CREATED = 0x00000020,
121  WRITTEN = 0x00000040,
122  RENAMED = 0x00000080,
123  DELETED = 0x00000100,
124  SECURITY_CHANGED = 0x00000200,
125  INFO_CHANGED = 0x00000400,
126  READ = 0x00000800,
127  }
128 
129  public enum NTSTATUS : uint
130  {
131  STATUS_SUCCESS = 0,
132  STATUS_UNSUCCESSFUL = 0xc0000001,
133  STATUS_ACCESS_DENIED = 0xC0000022,
134  }
135 
136 
137  public const uint ALLOW_MAX_RIGHT_ACCESS = 0xfffffff0;
138 
142  public enum AccessFlag : uint
143  {
144  EXCLUDE_FILTER_RULE = 0X00000000,
145  EXCLUDE_FILE_ACCESS = 0x00000001,
146  REPARSE_FILE_OPEN = 0x00000002,
148  FILE_ENCRYPTION_RULE = 0x00000008,
150  ALLOW_OPEN_WITH_READ_ACCESS = 0x00000020,
151  ALLOW_OPEN_WITH_WRITE_ACCESS = 0x00000040,
153  ALLOW_OPEN_WITH_DELETE_ACCESS = 0x00000100,
154  ALLOW_READ_ACCESS = 0x00000200,
155  ALLOW_WRITE_ACCESS = 0x00000400,
156  ALLOW_QUERY_INFORMATION_ACCESS = 0x00000800,
157  //allow to change file time and file attributes
158  ALLOW_SET_INFORMATION = 0x00001000,
159  ALLOW_FILE_RENAME = 0x00002000,
160  ALLOW_FILE_DELETE = 0x00004000,
161  ALLOW_FILE_SIZE_CHANGE = 0x00008000,
162  ALLOW_QUERY_SECURITY_ACCESS = 0x00010000,
163  ALLOW_SET_SECURITY_ACCESS = 0x00020000,
164  ALLOW_DIRECTORY_LIST_ACCESS = 0x00040000,
165  ALLOW_FILE_ACCESS_FROM_NETWORK = 0x00080000,
166  ALLOW_NEW_FILE_ENCRYPTION = 0x00100000,
167  ALLOW_ALL_SAVE_AS = 0x00200000,
168  ALLOW_INCLUDE_PROCESS_SAVE_AS = 0x00400000,
169  // ALLOW_MAX_RIGHT_ACCESS = 0xfffffff0,
170  }
171 
172 
176  public enum SecureFileAccessRights : uint
177  {
178  ENABLE_REVOKE_ACCESS_CONTROL = 1,
179  ENABLE_SAVE_AS = 2,
180  ENABLE_EDITING = 4,
181  }
182 
183  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
184  public struct MessageSendData
185  {
186  public uint MessageId; //this is the request sequential number.
187  public IntPtr FileObject; //the address of FileObject,it is equivalent to file handle,it is unique per file stream open.
188  public IntPtr FsContext; //the address of FsContext,it is unique per file.
189  public uint MessageType; //the I/O request type.
190  public uint ProcessId; //the process ID for the process associated with the thread that originally requested the I/O operation.
191  public uint ThreadId; //the thread ID which requested the I/O operation.
192  public long Offset; //the read/write offset.
193  public uint Length; //the read/write length.
194  public long FileSize; //the size of the file for the I/O operation.
195  public long TransactionTime; //the transaction time in UTC of this request.
196  public long CreationTime; //the creation time in UTC of the file.
197  public long LastAccessTime; //the last access time in UTC of the file.
198  public long LastWriteTime; //the last write time in UTC of the file.
199  public uint FileAttributes; //the file attributes.
200  public uint DesiredAccess; //the DesiredAccess for file open, please reference CreateFile windows API.
201  public uint Disposition; //the Disposition for file open, please reference CreateFile windows API.
202  public uint SharedAccess; //the SharedAccess for file open, please reference CreateFile windows API.
203  public uint CreateOptions; //the CreateOptions for file open, please reference CreateFile windows API.
204  public uint CreateStatus; //the CreateStatus after file was openned, please reference CreateFile windows API.
205  public uint InfoClass; //the information class or security information
206  public uint Status; //the I/O status which returned from file system.
207  public uint FileNameLength; //the file name length in byte.
208  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_FILE_NAME_LENGTH)]
209  public string FileName; //the file name of the I/O operation.
210  public uint SidLength; //the length of the security identifier.
211  [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_SID_LENGTH)]
212  public byte[] Sid; //the security identifier data.
213  public uint DataBufferLength; //the data buffer length.
214  [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_MESSAGE_LENGTH)]
215  public byte[] DataBuffer; //the data buffer which contains read/write/query information/set information data.
216  public uint VerificationNumber; //the verification number which verifiys the data structure integerity.
217  }
218 
219  public enum FilterStatus : uint
220  {
221  FILTER_MESSAGE_IS_DIRTY = 0x00000001, //the data buffer was updated.
222  FILTER_COMPLETE_PRE_OPERATION = 0x00000002, //ONLY FOR PRE CALL OPERATION,the IO won't pass down to the lower drivers and file system.
223  FILTER_DATA_BUFFER_IS_UPDATED = 0x00000004, //only for pre create,to reparse the file open to the new file name.
224  BLOCK_DATA_WAS_RETURNED = 0x00000008, //Set this flag if return read block databuffer to filter.
225  WHOLE_FILE_WAS_RESTORED = 0x00000010, //Set this flag if the stub file was restored.
226  }
227 
228  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
229  public struct AESDataBuffer
230  {
231  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
232  public byte[] EncryptionIV;
233  public uint EncryptionKeyLength;
234  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
235  public byte[] EncryptionKey;
236  }
237 
238  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
239  public struct MessageReplyData
240  {
241  public uint MessageId;
242  public uint MessageType;
243  public uint ReturnStatus;
244  public uint FilterStatus;
245  public uint DataBufferLength;
246  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 65536)]
247  public byte[] DataBuffer;
248  }
249 
255  [DllImport("FilterAPI.dll", SetLastError = true)]
256  public static extern bool SetBooleanConfig(uint booleanConfig);
257 
258  [DllImport("FilterAPI.dll", SetLastError = true)]
259  public static extern bool InstallDriver();
260 
261  [DllImport("FilterAPI.dll", SetLastError = true)]
262  public static extern bool UnInstallDriver();
263 
264  [DllImport("FilterAPI.dll", SetLastError = true)]
265  public static extern bool IsDriverServiceRunning();
266 
267  [DllImport("FilterAPI.dll", SetLastError = true)]
268  public static extern bool SetRegistrationKey([MarshalAs(UnmanagedType.LPStr)]string key);
269 
270  [DllImport("FilterAPI.dll", SetLastError = true)]
271  public static extern bool Disconnect();
272 
273  [DllImport("FilterAPI.dll", SetLastError = true)]
274  public static extern bool GetLastErrorMessage(
275  [MarshalAs(UnmanagedType.LPWStr)]
276  string lastError,
277  ref int messageLength);
278 
279  [DllImport("FilterAPI.dll", SetLastError = true)]
280  public static extern bool RegisterMessageCallback(
281  int threadCount,
282  IntPtr filterCallback,
283  IntPtr disconnectCallback);
284 
285  [DllImport("FilterAPI.dll", SetLastError = true)]
286  public static extern bool ResetConfigData();
287 
288  [DllImport("FilterAPI.dll", SetLastError = true)]
289  public static extern bool SetFilterType(uint filterType);
290 
291  [DllImport("FilterAPI.dll", SetLastError = true)]
292  public static extern bool SetConnectionTimeout(uint timeOutInSeconds);
293 
294  [DllImport("FilterAPI.dll", SetLastError = true)]
295  public static extern bool AddNewFilterRule(
296  uint accessFlag,
297  [MarshalAs(UnmanagedType.LPWStr)]string filterMask);
298 
299  [DllImport("FilterAPI.dll", SetLastError = true)]
300  public static extern bool AddEncryptionKeyToFilterRule(
301  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
302  uint encryptionKeyLength,
303  byte[] encryptionKey);
304 
305  [DllImport("FilterAPI.dll", SetLastError = true)]
306  public static extern bool AddExcludeFileMaskToFilterRule(
307  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
308  [MarshalAs(UnmanagedType.LPWStr)]string excludeFileFilterMask);
309 
310  [DllImport("FilterAPI.dll", SetLastError = true)]
311  public static extern bool AddHiddenFileMaskToFilterRule(
312  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
313  [MarshalAs(UnmanagedType.LPWStr)]string hiddenFileFilterMask);
314 
315  [DllImport("FilterAPI.dll", SetLastError = true)]
316  public static extern bool AddReparseFileMaskToFilterRule(
317  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
318  [MarshalAs(UnmanagedType.LPWStr)]string reparseFileFilterMask);
319 
320  [DllImport("FilterAPI.dll", SetLastError = true)]
321  public static extern bool AddIncludeProcessNameToFilterRule(
322  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
323  [MarshalAs(UnmanagedType.LPWStr)]string processName);
324  //process name format: notepad.exe
325 
326  [DllImport("FilterAPI.dll", SetLastError = true)]
327  public static extern bool AddExcludeProcessNameToFilterRule(
328  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
329  [MarshalAs(UnmanagedType.LPWStr)]string processName);
330 
331  [DllImport("FilterAPI.dll", SetLastError = true)]
332  public static extern bool AddIncludeProcessIdToFilterRule(
333  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
334  uint includeProcessId);
335 
336  [DllImport("FilterAPI.dll", SetLastError = true)]
337  public static extern bool AddExcludeProcessIdToFilterRule(
338  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
339  uint excludeProcessId);
340 
341  [DllImport("FilterAPI.dll", SetLastError = true)]
342  public static extern bool AddIncludeUserNameToFilterRule(
343  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
344  [MarshalAs(UnmanagedType.LPWStr)]string userName);
345  //process name format: notepad.exe
346 
347  [DllImport("FilterAPI.dll", SetLastError = true)]
348  public static extern bool AddExcludeUserNameToFilterRule(
349  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
350  [MarshalAs(UnmanagedType.LPWStr)]string userName);
351 
352  [DllImport("FilterAPI.dll", SetLastError = true)]
353  public static extern bool RegisterEventTypeToFilterRule(
354  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
355  uint eventType);
356 
357  [DllImport("FilterAPI.dll", SetLastError = true)]
358  public static extern bool RegisterMoinitorIOToFilterRule(
359  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
360  uint registerIO);
361 
362  [DllImport("FilterAPI.dll", SetLastError = true)]
363  public static extern bool RegisterControlIOToFilterRule(
364  [MarshalAs(UnmanagedType.LPWStr)]string filterMask,
365  uint registerIO);
366 
367  [DllImport("FilterAPI.dll", SetLastError = true)]
368  public static extern bool RemoveFilterRule(
369  [MarshalAs(UnmanagedType.LPWStr)] string filterMask);
370 
371  [DllImport("FilterAPI.dll", SetLastError = true)]
372  public static extern bool AddIncludedProcessId(uint processId);
373 
374  [DllImport("FilterAPI.dll", SetLastError = true)]
375  public static extern bool RemoveIncludeProcessId(uint processId);
376 
377  [DllImport("FilterAPI.dll", SetLastError = true)]
378  public static extern bool AddExcludedProcessId(uint processId);
379 
380  [DllImport("FilterAPI.dll", SetLastError = true)]
381  public static extern bool RemoveExcludeProcessId(uint processId);
382 
388  [DllImport("FilterAPI.dll", SetLastError = true)]
389  public static extern bool AddProtectedProcessId(uint processId);
390 
391  [DllImport("FilterAPI.dll", SetLastError = true)]
392  public static extern bool RemoveProtectedProcessId(uint processId);
393 
399  [DllImport("FilterAPI.dll", SetLastError = true)]
400  public static extern bool AddBlockSaveAsProcessId(uint processId);
401 
402  [DllImport("FilterAPI.dll", SetLastError = true)]
403  public static extern bool RemoveBlockSaveAsProcessId(uint processId);
404 
405  [DllImport("FilterAPI.dll", SetLastError = true)]
406  public static extern bool RegisterIoRequest(uint requestRegistration);
407 
408  [DllImport("FilterAPI.dll", SetLastError = true)]
409  public static extern bool GetFileHandleInFilter(
410  [MarshalAs(UnmanagedType.LPWStr)]string fileName,
411  uint dwDesiredAccess,
412  ref IntPtr fileHandle);
413 
414  [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
415  public static extern bool ConvertSidToStringSid(
416  [In] IntPtr sid,
417  [Out] out IntPtr sidString);
418 
419  [DllImport("kernel32.dll", SetLastError = true)]
420  public static extern IntPtr LocalFree(IntPtr hMem);
421 
422  [DllImport("kernel32", SetLastError = true)]
423  public static extern uint GetCurrentProcessId();
424 
425  [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
426  public static extern int QueryDosDeviceW(
427  [MarshalAs(UnmanagedType.LPWStr)]string dosName,
428  [MarshalAs(UnmanagedType.LPWStr)]ref string volumeName,
429  int volumeNameLength);
430 
431  [DllImport("FilterAPI.dll", SetLastError = true)]
432  private static extern bool CreateFileAPI(
433  [MarshalAs(UnmanagedType.LPWStr)]string fileName,
434  uint dwDesiredAccess,
435  uint dwShareMode,
438  ref IntPtr fileHandle);
439 
440  [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
441  private static extern bool SetFileTime(SafeFileHandle hFile,
442  [In] ref long lpCreationTime,
443  [In] ref long lpLastAccessTime,
444  [In] ref long lpLastWriteTime);
445 
446  [DllImport("FilterAPI.dll", SetLastError = true)]
447  private static extern bool CreateStubFile(
448  [MarshalAs(UnmanagedType.LPWStr)]string fileName,
449  long fileSize, //if it is 0 and the file exist,it will use the current file size.
450  uint fileAttributes, //if it is 0 and the file exist, it will use the current file attributes.
451  uint tagDataLength, //if it is 0, then no reparsepoint will be created.
452  IntPtr tagData,
453  bool overwriteIfExist,
454  ref IntPtr fileHandle);
455 
456  [DllImport("FilterAPI.dll", SetLastError = true)]
457  public static extern bool OpenStubFile(
458  [MarshalAs(UnmanagedType.LPWStr)]string fileName,
459  FileAccess access,
460  FileShare share,
461  ref IntPtr fileHandle);
462 
463  [DllImport("FilterAPI.dll", SetLastError = true)]
464  private static extern bool QueryAllocatedRanges(
465  IntPtr fileHandle,
466  long queryOffset,
467  long queryLength,
468  IntPtr allocatedRangesBuffer,
469  int allocatedRangesBufferSize,
470  ref uint returnedLength);
471 
472  [DllImport("FilterAPI.dll", SetLastError = true)]
473  private static extern bool AESEncryptDecryptBuffer(
474  IntPtr inputBuffer,
475  IntPtr outputBuffer,
476  uint bufferLength,
477  long offset,
478  byte[] encryptionKey,
479  uint keyLength,
480  byte[] iv,
481  uint ivLength);
482 
483 
484  [DllImport("FilterAPI.dll", SetLastError = true)]
485  public static extern bool AESEncryptFile(
486  [MarshalAs(UnmanagedType.LPWStr)]string fileName,
487  uint keyLength,
488  byte[] encryptionKey,
489  uint ivLength,
490  byte[] iv,
491  bool addIVTag);
492 
493  [DllImport("FilterAPI.dll", SetLastError = true)]
494  public static extern bool AESDecryptFile(
495  [MarshalAs(UnmanagedType.LPWStr)]string fileName,
496  uint keyLength,
497  byte[] encryptionKey,
498  uint ivLength,
499  byte[] iv);
500 
501 
502  [DllImport("FilterAPI.dll", SetLastError = true)]
503  public static extern bool AESEncryptFileToFile(
504  [MarshalAs(UnmanagedType.LPWStr)]string sourceFileName,
505  [MarshalAs(UnmanagedType.LPWStr)]string destFileName,
506  uint keyLength,
507  byte[] encryptionKey,
508  uint ivLength,
509  byte[] iv,
510  bool addIVTag);
511 
512  [DllImport("FilterAPI.dll", SetLastError = true)]
513  public static extern bool AESDecryptFileToFile(
514  [MarshalAs(UnmanagedType.LPWStr)]string sourceFileName,
515  [MarshalAs(UnmanagedType.LPWStr)]string destFileName,
516  uint keyLength,
517  byte[] encryptionKey,
518  uint ivLength,
519  byte[] iv);
520 
521  [DllImport("FilterAPI.dll", SetLastError = true)]
522  public static extern bool ProcessEncryptedFile(
523  [MarshalAs(UnmanagedType.LPWStr)]string sourceFileName,
524  [MarshalAs(UnmanagedType.LPWStr)]string destFileName);
525 
526  [DllImport("FilterAPI.dll", SetLastError = true)]
527  public static extern bool AddIVAndExpireTimeTag(
528  [MarshalAs(UnmanagedType.LPWStr)]string fileName,
529  uint ivLength,
530  byte[] iv,
531  long expireTime);
532 
533  [DllImport("FilterAPI.dll", SetLastError = true)]
534  public static extern bool AddReparseTagData(
535  [MarshalAs(UnmanagedType.LPWStr)]string fileName,
536  int tagDataLength,
537  IntPtr tagData);
538 
539  [DllImport("FilterAPI.dll", SetLastError = true)]
540  public static extern bool RemoveTagData(
541  IntPtr fileHandle);
542 
543  [DllImport("FilterAPI.dll", SetLastError = true)]
544  public static extern bool AddTagData(
545  IntPtr fileHandle,
546  int tagDataLength,
547  IntPtr tagData);
548 
549  public static bool EmbedDRPolicyDataToFile(
550  string fileName,
551  byte[] drPolicyData,
552  out string lastError )
553  {
554 
555  bool ret = false;
556  lastError = string.Empty;
557 
558  try
559  {
560  GCHandle pinnedArray = GCHandle.Alloc(drPolicyData, GCHandleType.Pinned);
561  IntPtr pointer = pinnedArray.AddrOfPinnedObject();
562 
563  ret = AddReparseTagData(fileName, drPolicyData.Length, pointer);
564 
565  pinnedArray.Free();
566 
567  if (!ret)
568  {
569  lastError = GetLastErrorMessage();
570  }
571  }
572  catch (Exception ex)
573  {
574  ret = false;
575  lastError = ex.Message;
576  }
577 
578  return ret;
579 
580  }
581 
582  [DllImport("kernel32.dll", SetLastError = true)]
583  public static extern bool CloseHandle(IntPtr handle);
584 
592  [DllImport("FilterAPI.dll", SetLastError = true)]
593  private static extern bool GetIVTag(
594  [MarshalAs(UnmanagedType.LPWStr)]string fileName,
595  ref uint ivLength,
596  IntPtr iv);
597 
604  [DllImport("FilterAPI.dll", SetLastError = true)]
605  public static extern bool GetUniqueComputerId(
606  IntPtr outputBuffer,
607  ref uint outputBufferLength);
608 
609  [DllImport("FilterAPI.dll", SetLastError = true)]
610  public static extern bool ActivateLicense(
611  IntPtr outputBuffer,
612  uint outputBufferLength);
613 
614  public enum EncryptType
615  {
616  Decryption = 0,
617  Encryption ,
618  }
619 
620  public static bool GetUniqueComputerId(ref string myComputerId,ref string lastError)
621  {
622  bool retVal = false;
623 
624  try
625  {
626  byte[] computerId = new byte[52];
627  uint computerIdLength = (uint)computerId.Length;
628  IntPtr computerIdPtr = Marshal.UnsafeAddrOfPinnedArrayElement(computerId, 0);
629  retVal = FilterAPI.GetUniqueComputerId(computerIdPtr, ref computerIdLength);
630 
631  if (!retVal || computerIdLength <= 0)
632  {
633  lastError = GetLastErrorMessage();
634  return false;
635  }
636 
637  Array.Resize(ref computerId, (int)computerIdLength);
638  myComputerId = UnicodeEncoding.Unicode.GetString(computerId);
639 
640  return true;
641  }
642  catch (Exception ex)
643  {
644  lastError = "Get computerId got exception,system return error:" + ex.Message;
645  return false;
646  }
647 
648  }
649 
650 
651  public static bool GetIVTag(string fileName, ref byte[] iv, out string lastError)
652  {
653  bool ret = false;
654  IntPtr tagPtr = IntPtr.Zero;
655  uint ivLength = 16;
656 
657  lastError = string.Empty;
658 
659  tagPtr = Marshal.AllocHGlobal((int)ivLength);
660  ret = GetIVTag(fileName, ref ivLength, tagPtr);
661 
662  if (!ret)
663  {
664  lastError = GetLastErrorMessage();
665  }
666  else if (ivLength > 0)
667  {
668  iv = new byte[ivLength];
669  Marshal.Copy(tagPtr, iv, 0, (int)ivLength);
670  }
671  else
672  {
673  iv = new byte[0]; ;
674  }
675 
676  if (tagPtr != IntPtr.Zero)
677  {
678  Marshal.FreeHGlobal(tagPtr);
679  }
680 
681  return ret;
682  }
683 
684 
685 
686  public static string AESEncryptDecryptStr(string inStr, EncryptType encryptType)
687  {
688 
689  if (string.IsNullOrEmpty(inStr))
690  {
691  return string.Empty;
692  }
693 
694  byte[] inbuffer = null;
695 
696  if (encryptType == EncryptType.Encryption)
697  {
698  inbuffer = ASCIIEncoding.UTF8.GetBytes(inStr);
699  }
700  else if (encryptType == EncryptType.Decryption)
701  {
702  inbuffer = Convert.FromBase64String(inStr);
703  }
704  else
705  {
706  throw new Exception("Failed to encrypt decrypt string, the encryptType " + encryptType.ToString() + " doesn't know.");
707  }
708 
709  byte[] outBuffer = new byte[inbuffer.Length];
710  IntPtr inBufferPtr = Marshal.UnsafeAddrOfPinnedArrayElement(inbuffer, 0);
711  IntPtr outBufferPtr = Marshal.UnsafeAddrOfPinnedArrayElement(outBuffer, 0);
712 
713  bool retVal = AESEncryptDecryptBuffer(inBufferPtr, outBufferPtr, (uint)inbuffer.Length, 0, null, 0, null, 0);
714 
715 
716  if (encryptType == EncryptType.Encryption)
717  {
718  return Convert.ToBase64String(outBuffer);
719  }
720  else //if (encryptType == EncryptType.Decryption)
721  {
722  return ASCIIEncoding.UTF8.GetString(outBuffer);
723  }
724 
725  }
726 
727 
728  public static void AESEncryptDecryptBuffer(byte[] inbuffer, long offset, byte[] key, byte[] IV)
729  {
730  if (null == inbuffer || inbuffer.Length == 0)
731  {
732  throw new Exception("Failed to encrypt decrypt buffer, the input buffer can't be null");
733  }
734 
735  IntPtr inBufferPtr = Marshal.UnsafeAddrOfPinnedArrayElement(inbuffer, 0);
736 
737  uint keyLength = 0;
738  uint IVLength = 0;
739 
740  if (key != null)
741  {
742  keyLength =(uint) key.Length;
743  }
744 
745  if (IV != null)
746  {
747  IVLength = (uint)IV.Length;
748  }
749 
750 
751  bool retVal = AESEncryptDecryptBuffer(inBufferPtr, inBufferPtr, (uint)inbuffer.Length, offset, key, keyLength, IV, IVLength);
752 
753  if (!retVal)
754  {
755  throw new Exception("Failed to encrypt buffer, return error:" + GetLastErrorMessage());
756  }
757 
758  return ;
759  }
760 
761  public static bool DecodeUserName(byte[]sid, out string userName)
762  {
763  bool ret = true;
764 
765  IntPtr sidStringPtr = IntPtr.Zero;
766  string sidString = string.Empty;
767 
768  userName = string.Empty;
769 
770  try
771  {
772  lock (userNameTable)
773  {
774  //check the user name cache table
775  if (userNameTable.ContainsKey(sid))
776  {
777  userName = userNameTable[sid];
778  return ret;
779  }
780  }
781 
782  IntPtr sidBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(sid, 0);
783 
784  if (FilterAPI.ConvertSidToStringSid(sidBuffer, out sidStringPtr))
785  {
786  sidString = Marshal.PtrToStringAuto(sidStringPtr);
787  SecurityIdentifier secIdentifier = new SecurityIdentifier(sidString);
788  IdentityReference reference = secIdentifier.Translate(typeof(NTAccount));
789  userName = reference.Value;
790  }
791  else
792  {
793  string errorMessage = "Convert sid to sid string failed with error " + Marshal.GetLastWin32Error();
794  Console.WriteLine(errorMessage);
795  }
796  }
797  catch (Exception ex)
798  {
799  Console.WriteLine(string.Format("Convert sid to user name got exception:{0}", ex.Message));
800  ret = false;
801 
802  }
803  finally
804  {
805  if (sidStringPtr != null && sidStringPtr != IntPtr.Zero)
806  {
807  FilterAPI.LocalFree(sidStringPtr);
808  }
809  }
810 
811  return ret;
812  }
813 
814  public static bool DecodeProcessName(uint processId, out string processName)
815  {
816  bool ret = true;
817 
818  processName = string.Empty;
819 
820  try
821  {
822  System.Diagnostics.Process requestProcess = System.Diagnostics.Process.GetProcessById((int)processId);
823  processName = requestProcess.ProcessName;
824  }
825  catch (Exception ex)
826  {
827  Console.WriteLine(string.Format("Convert pid to process name got exception:{0}", ex.Message));
828  ret = false;
829 
830  }
831 
832  return ret;
833  }
834 
835 
836  public static string GetLastErrorMessage()
837  {
838  int len = 1024;
839  string lastError = new string((char)0, len);
840 
841  if (!GetLastErrorMessage(lastError, ref len))
842  {
843  lastError = new string((char)0, len);
844  if (!GetLastErrorMessage(lastError, ref len))
845  {
846  return "failed to get last error message.";
847  }
848  }
849 
850  if (lastError.IndexOf((char)0) >= 0)
851  {
852  lastError = lastError.Substring(0, lastError.IndexOf((char)0));
853  }
854 
855  return lastError;
856  }
857 
858  static bool IsDriverChanged()
859  {
860  bool ret = false;
861 
862  try
863  {
864  System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly();
865  string localPath = Path.GetDirectoryName(assembly.Location);
866  string driverName = Path.Combine(localPath, "EaseFlt.sys");
867 
868  if (File.Exists(driverName))
869  {
870  string driverInstalledPath = Path.Combine(Environment.SystemDirectory, "drivers\\easeflt.sys");
871 
872  if (File.Exists(driverInstalledPath))
873  {
874  FileInfo fsInstalled = new FileInfo(driverInstalledPath);
875  FileInfo fsToInstall = new FileInfo(driverName);
876 
877  if (fsInstalled.LastWriteTime < fsToInstall.LastWriteTime)
878  {
879  //it needs to install new the driver.
880  return true;
881  }
882  }
883  else
884  {
885  return true;
886  }
887  }
888 
889  }
890  catch (Exception ex)
891  {
892  ret = false;
893 
894  EventManager.WriteMessage(630, "IsDriverChanged", EventLevel.Error, "Check IsDriverChanged failed with error:" + ex.Message);
895  }
896 
897  return ret;
898  }
899 
900  static public bool StartFilter(int threadCount, string registerKey,FilterDelegate filterCallback, DisconnectDelegate disconnectCallback,ref string lastError)
901  {
902 
903  bool ret = true;
904 
905  try
906  {
907  if (IsDriverChanged() || !FilterAPI.IsDriverServiceRunning() )
908  {
909  FilterAPI.UnInstallDriver();
910 
911  //wait for 3 seconds for the uninstallation completed.
912  System.Threading.Thread.Sleep(3000);
913 
914  ret = FilterAPI.InstallDriver();
915  if (!ret)
916  {
917  lastError = "Installed driver failed with error:" + FilterAPI.GetLastErrorMessage();
918  return false;
919  }
920  else
921  {
922  isFilterStarted = false;
923  EventManager.WriteMessage(59, "InstallDriver", EventLevel.Information, "Install filter driver succeeded.");
924  }
925  }
926 
927 
928  if (!isFilterStarted)
929  {
930  {
931 
932  if (!SetRegistrationKey(registerKey))
933  {
934  lastError = "Set registration key failed with error:" + GetLastErrorMessage();
935  return false;
936  }
937  }
938 
939  gchFilter = GCHandle.Alloc(filterCallback);
940  IntPtr filterCallbackPtr = Marshal.GetFunctionPointerForDelegate(filterCallback);
941 
942  gchDisconnect = GCHandle.Alloc(disconnectCallback);
943  IntPtr disconnectCallbackPtr = Marshal.GetFunctionPointerForDelegate(disconnectCallback);
944 
945  isFilterStarted = RegisterMessageCallback(threadCount, filterCallbackPtr, disconnectCallbackPtr);
946  if (!isFilterStarted)
947  {
948  lastError = "SRegisterMessageCallback failed with error:" + GetLastErrorMessage();
949  return false;
950  }
951 
952  ret = true;
953 
954  }
955  }
956  catch (Exception ex)
957  {
958  ret = false;
959  lastError = "Start filter failed with error " + ex.Message;
960  }
961  finally
962  {
963  if (!ret)
964  {
965  lastError = lastError + " Make sure you run this application as administrator.";
966  }
967  }
968 
969  return ret;
970  }
971 
972  static public void StopFilter()
973  {
974  if (isFilterStarted)
975  {
976  Disconnect();
977  gchFilter.Free();
978  gchDisconnect.Free();
979  isFilterStarted = false;
980  }
981 
982  return;
983  }
984 
985  static public bool IsFilterStarted
986  {
987  get { return isFilterStarted; }
988  }
989 
990  }
991 }
WCHAR * userName
Definition: FilterAPI.h:604
unsigned char key[]
BYTE ULONG bufferLength
Definition: FilterAPI.h:812
#define MAX_SID_LENGTH
Definition: FilterAPI.h:18
ULONG encryptionKeyLength
Definition: FilterAPI.h:561
enum _BooleanConfig BooleanConfig
ULONG PUCHAR encryptionKey
Definition: FilterAPI.h:561
ULONG BYTE ULONG BYTE BOOLEAN addIVTag
Definition: FilterAPI.h:742
LPCTSTR destFileName
Definition: FilterAPI.h:757
DWORD DWORD DWORD dwCreationDisposition
Definition: FilterAPI.h:674
WCHAR WCHAR ULONG keyLength
Definition: FilterAPI.h:553
LONGLONG ULONG ULONG BYTE * tagData
Definition: FilterAPI.h:684
BYTE ULONG LONGLONG offset
Definition: FilterAPI.h:812
enum _FilterType FilterType
#define MAX_FILE_NAME_LENGTH
Definition: FilterAPI.h:17
LONGLONG ULONG fileAttributes
Definition: FilterAPI.h:684
BYTE * outputBuffer
Definition: FilterAPI.h:812
WCHAR * processName
Definition: FilterAPI.h:596
long NTSTATUS
Definition: UnitTest.h:14
#define MAX_PATH
Definition: FilterAPI.h:23
WCHAR * excludeFileFilterMask
Definition: FilterAPI.h:572
WCHAR * filterMask
Definition: FilterAPI.h:557
enum _FilterStatus FilterStatus
DWORD dwDesiredAccess
Definition: FilterAPI.h:666
LONGLONG ULONG ULONG BYTE BOOL overwriteIfExist
Definition: FilterAPI.h:684
#define STATUS_ACCESS_DENIED
Definition: FilterAPI.h:484
enum _AccessFlag AccessFlag
ULONG BYTE ULONG ivLength
Definition: FilterAPI.h:740
LONGLONG ULONG ULONG tagDataLength
Definition: FilterAPI.h:684
#define MESSAGE_SEND_VERIFICATION_NUMBER
Definition: FilterAPI.h:15
unsigned char iv[]
enum _FilterCommand FilterCommand
ULONG eventType
Definition: FilterAPI.h:584
IN LONGLONG IN LONGLONG queryLength
Definition: FilterAPI.h:722
WCHAR * hiddenFileFilterMask
Definition: FilterAPI.h:569
LONGLONG fileSize
Definition: FilterAPI.h:684
ULONG BYTE LONGLONG HANDLE fileHandle
Definition: FilterAPI.h:792
enum _MessageType MessageType
#define MAX_ERROR_MESSAGE_SIZE
ULONG BYTE LONGLONG expireTime
Definition: FilterAPI.h:792
DWORD DWORD DWORD DWORD dwFlagsAndAttributes
Definition: FilterAPI.h:674
DWORD DWORD dwShareMode
Definition: FilterAPI.h:666
ULONG registerIO
Definition: FilterAPI.h:588
#define STATUS_SUCCESS
#define registerKey
IN LONGLONG queryOffset
Definition: FilterAPI.h:722
#define AES_TAG_KEY
Definition: FilterAPI.h:48

Social Network


Services Overview

Architect, implement and test file system filter drivers for a wide range of functionality. We can offer several levels of assistance to meet your specific.

Contact Us

You are welcome to contact us for salse or partnership.

Sales: sales@easefilter.com
Support: support@easefilter.com
Info: info@easefilter.com