12 October, 2012

WinRT local network isolation

By default only VS2012 deployed applications have the localhost network isolation in disabled state. All other application can't connect to localhost. There are at least two tools to control which application can connect to localhost which not: CheckNetIsolation and EnableLoopback. Here is the way how to do it from you own program:

void DisableLoopbackNetworkIsolation(LPCWSTR const fullName = nullptr)
{
 DWORD error;
 DWORD appCsSize;
 INET_FIREWALL_APP_CONTAINER_NetworkIsolationFreeAppContainersHolder appCs;

 if (error = NetworkIsolationEnumAppContainers(0, &appCsSize, &appCs), error != ERROR_SUCCESS)
  throw _system_error("Can't enum network isolation app containers", error);

 DWORD publicAppCsSize;
 SID_AND_ATTRIBUTES_NetworkIsolationFreeAppContainersHolder publicAppCs;

 if (error = NetworkIsolationGetAppContainerConfig(&publicAppCsSize, &publicAppCs), error != ERROR_SUCCESS)
  throw _system_error("Can't enum network isolation get app container config", error);

 std::vector<SID_AND_ATTRIBUTES> newPublicAppCs(
  publicAppCs.GetPointer(),
  publicAppCs.GetPointer() + publicAppCsSize);

 std::any_of(
  appCs.GetPointer(),
  appCs.GetPointer() + appCsSize,
  [&] (INET_FIREWALL_APP_CONTAINER const & ifac) -> bool
  {
   if (fullName != nullptr)
    if (ifac.packageFullName == nullptr || wcscmp(fullName, ifac.packageFullName) != 0)
     return false;

   PSID const ifacSid = ifac.appContainerSid;
   bool const noSid = std::none_of(
    publicAppCs.GetPointer(),
    publicAppCs.GetPointer() + publicAppCsSize,
    [&] (SID_AND_ATTRIBUTES const & saa) -> BOOL
    {
     return EqualSid(ifacSid, saa.Sid);
    });

   if (noSid)
   {
    SID_AND_ATTRIBUTES saa;

    memset(&saa, 0, sizeof(saa));
    saa.Sid = ifacSid;
    newPublicAppCs.push_back(saa);
   }

   return fullName != nullptr;
  });

 if (error = NetworkIsolationSetAppContainerConfig((DWORD) newPublicAppCs.size(), &newPublicAppCs.front()), error != ERROR_SUCCESS)
  throw _system_error("Can't enum network isolation get app container config", error);
}
You can see two strange types here: INET_FIREWALL_APP_CONTAINER_NetworkIsolationFreeAppContainersHolder and SID_AND_ATTRIBUTES_NetworkIsolationFreeAppContainersHolder. Please don't afraid, it's only holder to free allocated memory automatically in destructor by NetworkIsolationFreeAppContainers call.

No comments: