FileAipManager.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Claims;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Web;
  9. using Microsoft.Identity.Client;
  10. using Microsoft.InformationProtection;
  11. using Microsoft.InformationProtection.File;
  12. using Microsoft.InformationProtection.Policy;
  13. using LogLevel = Microsoft.InformationProtection.LogLevel;
  14. namespace AipGateway.AIP
  15. {
  16. public class FileAipManager
  17. {
  18. private static string _mipData;
  19. private string _mipPath;
  20. private readonly ApplicationInfo _appInfo;
  21. private readonly AuthDelegateImplementation _authDelegate;
  22. private IFileProfile _fileProfile = null;
  23. private IFileEngine _fileEngine = null;
  24. private IPolicyProfile _policyProfile = null;
  25. private IPolicyEngine _policyEngine = null;
  26. private MipContext _mipContext = null;
  27. public FileAipManager(
  28. string clientId,
  29. string applicationName,
  30. string applicationVersion,
  31. string tenantId,
  32. string clientSecret,
  33. string mipData,
  34. string eamil,
  35. ClaimsPrincipal claimsPrincipal)
  36. {
  37. _appInfo = new ApplicationInfo()
  38. {
  39. ApplicationId = clientId,
  40. ApplicationName = applicationName,
  41. ApplicationVersion = applicationVersion
  42. };
  43. _mipData = mipData;
  44. _mipPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _mipData);
  45. _authDelegate = new AuthDelegateImplementation(clientId, clientSecret, claimsPrincipal);
  46. // var path = Path.Combine(
  47. // Directory.GetParent(Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath)).FullName,
  48. // Environment.Is64BitProcess ? "x64" : "x86");
  49. var path = Path.Combine(
  50. Directory.GetParent(Path.GetDirectoryName(new Uri(Environment.CurrentDirectory).LocalPath)).FullName,
  51. Environment.Is64BitProcess ? "x64" : "x86");
  52. MIP.Initialize(MipComponent.File);//, path);
  53. MipConfiguration mipConfiguration = new MipConfiguration(_appInfo, _mipData, LogLevel.Trace, false);
  54. _mipContext = MIP.CreateMipContext(mipConfiguration);
  55. Identity identity = new Identity(eamil);
  56. // _policyProfile = CreatePolicyProfile(_appInfo, ref _authDelegate);
  57. // _policyEngine = CreatePolicyEngine(identity);
  58. _fileProfile = CreateFileProfile();
  59. // _fileEngine = CreateFileEngine(ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value, "", "en-US");
  60. _fileEngine = CreateFileEngine(identity, "", "en-US");
  61. }
  62. public void Dispose()
  63. {
  64. _policyProfile.UnloadEngineAsync(_policyEngine.Settings.Id).Wait();
  65. _policyEngine.Dispose();
  66. _policyProfile.Dispose();
  67. _fileEngine.Dispose();
  68. _fileEngine.Dispose();
  69. _mipContext.ShutDown();
  70. _mipContext.Dispose();
  71. }
  72. private IPolicyProfile CreatePolicyProfile(ApplicationInfo appInfo, ref AuthDelegateImplementation authDelegate)
  73. {
  74. var profileSettings = new PolicyProfileSettings(_mipContext, CacheStorageType.OnDiskEncrypted);
  75. var profile = Task.Run(async () => await MIP.LoadPolicyProfileAsync(profileSettings)).Result;
  76. return profile;
  77. }
  78. private IPolicyEngine CreatePolicyEngine(Identity identity)
  79. {
  80. var engineSettings = new PolicyEngineSettings(identity.Email, _authDelegate, "", "en-US")
  81. {
  82. Identity = identity
  83. };
  84. var engine = Task.Run(async () => await _policyProfile.AddEngineAsync(engineSettings)).Result;
  85. return engine;
  86. }
  87. private IFileProfile CreateFileProfile()
  88. {
  89. try
  90. {
  91. var profileSettings = new FileProfileSettings(_mipContext, CacheStorageType.OnDisk, new ConsentDelegateImplementation());
  92. // var profileSettings = new FileProfileSettings(_mipContext, CacheStorageType.OnDiskEncrypted, new ConsentDelegateImplementation());
  93. var fileProfile = Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;
  94. return fileProfile;
  95. }
  96. catch (Exception ex)
  97. {
  98. //throw ex;
  99. }
  100. return null;
  101. }
  102. // public Identity GetUserIdentity()
  103. // {
  104. // //AuthenticationResult result = AcquireTokenAsync("https://login.microsoftonline.com/common", "https://graph.microsoft.com", null).Result;
  105. // return new Identity(result.Account.Username);
  106. // }
  107. private IFileEngine CreateFileEngine(Identity identity, string clientData, string locale)
  108. {
  109. try
  110. {
  111. var configuredFunctions = new Dictionary<FunctionalityFilterType, bool>();
  112. configuredFunctions.Add(FunctionalityFilterType.DoubleKeyProtection, true);
  113. var engineSettings = new FileEngineSettings(identity.Email, _authDelegate, clientData, locale)
  114. {
  115. Identity = identity,
  116. ConfiguredFunctionality = configuredFunctions,
  117. ProtectionOnlyEngine = true
  118. };
  119. var fileEngine = Task.Run(async () => await _fileProfile.AddEngineAsync(engineSettings)).Result;
  120. return fileEngine;
  121. }
  122. catch (Exception ex)
  123. {
  124. //throw ex;
  125. }
  126. return null;
  127. }
  128. private IFileHandler CreateFileHandler(Stream stream, string fileName)
  129. {
  130. IFileHandler handler;
  131. try
  132. {
  133. if (stream != null)
  134. {
  135. handler = Task.Run(async () => await _fileEngine.CreateFileHandlerAsync(stream, fileName, true)).Result;
  136. }
  137. else
  138. {
  139. handler = Task.Run(async () => await _fileEngine.CreateFileHandlerAsync(fileName, fileName, true)).Result;
  140. }
  141. return handler;
  142. }
  143. catch (Exception ex)
  144. {
  145. throw ex;
  146. }
  147. }
  148. public bool ApplyLabel(Stream stream, Stream outputStream, string fileName, string labelId, string justificationMessage)
  149. {
  150. IFileHandler handler;
  151. try
  152. {
  153. // Try to create an IFileHandler using private CreateFileHandler().
  154. if (stream != null)
  155. {
  156. handler = CreateFileHandler(stream, fileName);
  157. }
  158. // Try to create an IFileHandler using private CreateFileHandler().
  159. else
  160. {
  161. handler = CreateFileHandler(null, fileName);
  162. }
  163. // Applying a label requires LabelingOptions. Hard coded values here, but could be provided by user.
  164. LabelingOptions labelingOptions = new LabelingOptions()
  165. {
  166. JustificationMessage = justificationMessage,
  167. AssignmentMethod = AssignmentMethod.Standard,
  168. ExtendedProperties = new List<KeyValuePair<string, string>>()
  169. };
  170. // Set the label on the input stream or file.
  171. handler.SetLabel(_fileEngine.GetLabelById(labelId), labelingOptions, new ProtectionSettings());
  172. // Call CommitAsync to write result to output stream.
  173. // Returns a bool to indicate true or false.
  174. var result = Task.Run(async () => await handler.CommitAsync(outputStream)).Result;
  175. if (result)
  176. {
  177. // Submit an audit event if the change was successful.
  178. handler.NotifyCommitSuccessful(fileName);
  179. }
  180. return result;
  181. }
  182. catch (Exception ex)
  183. {
  184. throw ex;
  185. }
  186. }
  187. public List<AipLabel> ListAllLabels()
  188. {
  189. try
  190. {
  191. //var labels = _policyEngine.ListSensitivityLabels();
  192. var labels = _fileEngine.SensitivityLabels;
  193. var returnLabels = new List<AipLabel>();
  194. foreach (var label in labels)
  195. {
  196. var _label = new AipLabel()
  197. {
  198. Name = label.Name,
  199. Id = label.Id,
  200. Description = label.Description,
  201. Sensitivity = label.Sensitivity
  202. };
  203. _label.Children = new List<AipLabel>();
  204. // If the label has an children, iterate through each.
  205. if (label.Children.Count > 0)
  206. {
  207. foreach (var child in label.Children)
  208. {
  209. var _child = new AipLabel()
  210. {
  211. Name = child.Name,
  212. Id = child.Id,
  213. Description = child.Description,
  214. Sensitivity = child.Sensitivity
  215. };
  216. _label.Children.Add(_child);
  217. }
  218. }
  219. returnLabels.Add(_label);
  220. }
  221. return returnLabels;
  222. }
  223. catch (Exception ex)
  224. {
  225. throw ex;
  226. }
  227. }
  228. }
  229. }