LoopUtil.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. /*
  8. * Important - Even though this will compile in the shared projects, it will cause build failures within the mono runtime
  9. */
  10. namespace MediaBrowser.ServerApplication.Native
  11. {
  12. /// <summary>
  13. /// http://blogs.msdn.com/b/fiddler/archive/2011/12/10/fiddler-windows-8-apps-enable-LoopUtil-network-isolation-exemption.aspx
  14. /// </summary>
  15. public class LoopUtil
  16. {
  17. //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379595(v=vs.85).aspx
  18. [StructLayout(LayoutKind.Sequential)]
  19. internal struct SID_AND_ATTRIBUTES
  20. {
  21. public IntPtr Sid;
  22. public uint Attributes;
  23. }
  24. [StructLayoutAttribute(LayoutKind.Sequential)]
  25. internal struct INET_FIREWALL_AC_CAPABILITIES
  26. {
  27. public uint count;
  28. public IntPtr capabilities; //SID_AND_ATTRIBUTES
  29. }
  30. [StructLayoutAttribute(LayoutKind.Sequential)]
  31. internal struct INET_FIREWALL_AC_BINARIES
  32. {
  33. public uint count;
  34. public IntPtr binaries;
  35. }
  36. [StructLayoutAttribute(LayoutKind.Sequential)]
  37. internal struct INET_FIREWALL_APP_CONTAINER
  38. {
  39. internal IntPtr appContainerSid;
  40. internal IntPtr userSid;
  41. [MarshalAs(UnmanagedType.LPWStr)]
  42. public string appContainerName;
  43. [MarshalAs(UnmanagedType.LPWStr)]
  44. public string displayName;
  45. [MarshalAs(UnmanagedType.LPWStr)]
  46. public string description;
  47. internal INET_FIREWALL_AC_CAPABILITIES capabilities;
  48. internal INET_FIREWALL_AC_BINARIES binaries;
  49. [MarshalAs(UnmanagedType.LPWStr)]
  50. public string workingDirectory;
  51. [MarshalAs(UnmanagedType.LPWStr)]
  52. public string packageFullName;
  53. }
  54. // Call this API to free the memory returned by the Enumeration API
  55. [DllImport("FirewallAPI.dll")]
  56. internal static extern void NetworkIsolationFreeAppContainers(IntPtr pACs);
  57. // Call this API to load the current list of LoopUtil-enabled AppContainers
  58. [DllImport("FirewallAPI.dll")]
  59. internal static extern uint NetworkIsolationGetAppContainerConfig(out uint pdwCntACs, out IntPtr appContainerSids);
  60. // Call this API to set the LoopUtil-exemption list
  61. [DllImport("FirewallAPI.dll")]
  62. private static extern uint NetworkIsolationSetAppContainerConfig(uint pdwCntACs, SID_AND_ATTRIBUTES[] appContainerSids);
  63. // Use this API to convert a string SID into an actual SID
  64. [DllImport("advapi32.dll", SetLastError = true)]
  65. internal static extern bool ConvertStringSidToSid(string strSid, out IntPtr pSid);
  66. [DllImport("advapi32", /*CharSet = CharSet.Auto,*/ SetLastError = true)]
  67. static extern bool ConvertSidToStringSid(
  68. [MarshalAs(UnmanagedType.LPArray)] byte[] pSID,
  69. out IntPtr ptrSid);
  70. [DllImport("advapi32", /*CharSet = CharSet.Auto,*/ SetLastError = true)]
  71. static extern bool ConvertSidToStringSid(IntPtr pSid, out string strSid);
  72. // Use this API to convert a string reference (e.g. "@{blah.pri?ms-resource://whatever}") into a plain string
  73. [DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
  74. internal static extern int SHLoadIndirectString(string pszSource, StringBuilder pszOutBuf);
  75. // Call this API to enumerate all of the AppContainers on the system
  76. [DllImport("FirewallAPI.dll")]
  77. internal static extern uint NetworkIsolationEnumAppContainers(uint Flags, out uint pdwCntPublicACs, out IntPtr ppACs);
  78. // DWORD NetworkIsolationEnumAppContainers(
  79. // _In_ DWORD Flags,
  80. // _Out_ DWORD *pdwNumPublicAppCs,
  81. // _Out_ PINET_FIREWALL_APP_CONTAINER *ppPublicAppCs
  82. //);
  83. //http://msdn.microsoft.com/en-gb/library/windows/desktop/hh968116.aspx
  84. enum NETISO_FLAG
  85. {
  86. NETISO_FLAG_FORCE_COMPUTE_BINARIES = 0x1,
  87. NETISO_FLAG_MAX = 0x2
  88. }
  89. public class AppContainer
  90. {
  91. public String appContainerName { get; set; }
  92. public String displayName { get; set; }
  93. public String workingDirectory { get; set; }
  94. public String StringSid { get; set; }
  95. public List<uint> capabilities { get; set; }
  96. public bool LoopUtil { get; set; }
  97. public AppContainer(String _appContainerName, String _displayName, String _workingDirectory, IntPtr _sid)
  98. {
  99. this.appContainerName = _appContainerName;
  100. this.displayName = _displayName;
  101. this.workingDirectory = _workingDirectory;
  102. String tempSid;
  103. ConvertSidToStringSid(_sid, out tempSid);
  104. this.StringSid = tempSid;
  105. }
  106. }
  107. internal List<LoopUtil.INET_FIREWALL_APP_CONTAINER> _AppList;
  108. internal List<LoopUtil.SID_AND_ATTRIBUTES> _AppListConfig;
  109. public List<AppContainer> Apps = new List<AppContainer>();
  110. internal IntPtr _pACs;
  111. public LoopUtil()
  112. {
  113. LoadApps();
  114. }
  115. public void LoadApps()
  116. {
  117. Apps.Clear();
  118. _pACs = IntPtr.Zero;
  119. //Full List of Apps
  120. _AppList = PI_NetworkIsolationEnumAppContainers();
  121. //List of Apps that have LoopUtil enabled.
  122. _AppListConfig = PI_NetworkIsolationGetAppContainerConfig();
  123. foreach (var PI_app in _AppList)
  124. {
  125. AppContainer app = new AppContainer(PI_app.appContainerName, PI_app.displayName, PI_app.workingDirectory, PI_app.appContainerSid);
  126. app.LoopUtil = CheckLoopback(PI_app.appContainerSid);
  127. Apps.Add(app);
  128. }
  129. }
  130. private bool CheckLoopback(IntPtr intPtr)
  131. {
  132. foreach (SID_AND_ATTRIBUTES item in _AppListConfig)
  133. {
  134. string left, right;
  135. ConvertSidToStringSid(item.Sid, out left);
  136. ConvertSidToStringSid(intPtr, out right);
  137. if (left == right)
  138. {
  139. return true;
  140. }
  141. }
  142. return false;
  143. }
  144. private bool CreateExcemptions(string appName)
  145. {
  146. var hasChanges = false;
  147. foreach (var app in Apps)
  148. {
  149. if ((app.appContainerName ?? string.Empty).IndexOf(appName, StringComparison.OrdinalIgnoreCase) != -1 ||
  150. (app.displayName ?? string.Empty).IndexOf(appName, StringComparison.OrdinalIgnoreCase) != -1)
  151. {
  152. if (!app.LoopUtil)
  153. {
  154. app.LoopUtil = true;
  155. hasChanges = true;
  156. }
  157. }
  158. }
  159. return hasChanges;
  160. }
  161. public static void Run(string appName)
  162. {
  163. var util = new LoopUtil();
  164. util.LoadApps();
  165. var hasChanges = util.CreateExcemptions(appName);
  166. if (hasChanges)
  167. {
  168. util.SaveLoopbackState();
  169. }
  170. util.SaveLoopbackState();
  171. }
  172. private static List<SID_AND_ATTRIBUTES> PI_NetworkIsolationGetAppContainerConfig()
  173. {
  174. IntPtr arrayValue = IntPtr.Zero;
  175. uint size = 0;
  176. var list = new List<SID_AND_ATTRIBUTES>();
  177. // Pin down variables
  178. GCHandle handle_pdwCntPublicACs = GCHandle.Alloc(size, GCHandleType.Pinned);
  179. GCHandle handle_ppACs = GCHandle.Alloc(arrayValue, GCHandleType.Pinned);
  180. uint retval = NetworkIsolationGetAppContainerConfig(out size, out arrayValue);
  181. var structSize = Marshal.SizeOf(typeof(SID_AND_ATTRIBUTES));
  182. for (var i = 0; i < size; i++)
  183. {
  184. var cur = (SID_AND_ATTRIBUTES)Marshal.PtrToStructure(arrayValue, typeof(SID_AND_ATTRIBUTES));
  185. list.Add(cur);
  186. arrayValue = new IntPtr((long)(arrayValue) + (long)(structSize));
  187. }
  188. //release pinned variables.
  189. handle_pdwCntPublicACs.Free();
  190. handle_ppACs.Free();
  191. return list;
  192. }
  193. private List<INET_FIREWALL_APP_CONTAINER> PI_NetworkIsolationEnumAppContainers()
  194. {
  195. IntPtr arrayValue = IntPtr.Zero;
  196. uint size = 0;
  197. var list = new List<INET_FIREWALL_APP_CONTAINER>();
  198. // Pin down variables
  199. GCHandle handle_pdwCntPublicACs = GCHandle.Alloc(size, GCHandleType.Pinned);
  200. GCHandle handle_ppACs = GCHandle.Alloc(arrayValue, GCHandleType.Pinned);
  201. //uint retval2 = NetworkIsolationGetAppContainerConfig( out size, out arrayValue);
  202. uint retval = NetworkIsolationEnumAppContainers((Int32)NETISO_FLAG.NETISO_FLAG_MAX, out size, out arrayValue);
  203. _pACs = arrayValue; //store the pointer so it can be freed when we close the form
  204. var structSize = Marshal.SizeOf(typeof(INET_FIREWALL_APP_CONTAINER));
  205. for (var i = 0; i < size; i++)
  206. {
  207. var cur = (INET_FIREWALL_APP_CONTAINER)Marshal.PtrToStructure(arrayValue, typeof(INET_FIREWALL_APP_CONTAINER));
  208. list.Add(cur);
  209. arrayValue = new IntPtr((long)(arrayValue) + (long)(structSize));
  210. }
  211. //release pinned variables.
  212. handle_pdwCntPublicACs.Free();
  213. handle_ppACs.Free();
  214. return list;
  215. }
  216. public bool SaveLoopbackState()
  217. {
  218. var countEnabled = CountEnabledLoopUtil();
  219. SID_AND_ATTRIBUTES[] arr = new SID_AND_ATTRIBUTES[countEnabled];
  220. int count = 0;
  221. for (int i = 0; i < Apps.Count; i++)
  222. {
  223. if (Apps[i].LoopUtil)
  224. {
  225. arr[count].Attributes = 0;
  226. //TO DO:
  227. IntPtr ptr;
  228. ConvertStringSidToSid(Apps[i].StringSid, out ptr);
  229. arr[count].Sid = ptr;
  230. count++;
  231. }
  232. }
  233. if (NetworkIsolationSetAppContainerConfig((uint)countEnabled, arr) == 0)
  234. {
  235. return true;
  236. }
  237. else
  238. { return false; }
  239. }
  240. private int CountEnabledLoopUtil()
  241. {
  242. var count = 0;
  243. for (int i = 0; i < Apps.Count; i++)
  244. {
  245. if (Apps[i].LoopUtil)
  246. {
  247. count++;
  248. }
  249. }
  250. return count;
  251. }
  252. public void FreeResources()
  253. {
  254. NetworkIsolationFreeAppContainers(_pACs);
  255. }
  256. }
  257. }