进程间通信- C#和C++。拒绝访问路径。

4

我有一个C#客户端应用程序,它使用管道连接到一个C++服务器应用程序。当我尝试连接时,会出现错误:System.UnauthorizedAccessException:拒绝访问路径。

在查找此问题时,我发现可以通过创建PipeSecurity对象并添加PipeAccessRule来解决它。但是,这仅适用于服务器也是C#应用程序的情况。

如果我的服务器是C++应用程序,你有什么解决办法吗?

我已经搜索过了,但找不到解决方案。

C#:

      int timeOut = 500;
      NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.Asynchronous);
      pipeStream.Connect(timeOut);  

      byte[] buffer = Encoding.UTF8.GetBytes(sendStr);
      pipeStream.BeginWrite(buffer, 0, buffer.Length, new AsyncCallback(AsyncSend), pipeStream);

C++:

   _hPipe = ::CreateNamedPipe(configurePipeName(getPipeName()).c_str(),
                            PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED,
                            PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
                            1,
                            bufferSize,
                            bufferSize,
                            NMPWAIT_USE_DEFAULT_WAIT,
                            NULL);

  if (_hPipe == INVALID_HANDLE_VALUE)
  {
    logStream << "CreateNamedPipe failed for " << sys::OperatingSystem::getLastErrorMessage() << blog::over;
    return;
  }

  HANDLE ioEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  overlapped.hEvent = ioEvent;

  assert(overlapped.hEvent);
  if (ioEvent == INVALID_HANDLE_VALUE)
  {
    logStream << "CreateEvent failed for " << sys::OperatingSystem::getLastErrorMessage() << blog::over;
    return;
  }

  while (!terminating())
  {
    BOOL connected = false;
    DWORD waitMessage;
    DWORD timeOut = 700;

    if (!::ConnectNamedPipe(_hPipe, &overlapped))
    {
      switch (::GetLastError()) 
      {
        case ERROR_PIPE_CONNECTED:
          connected = true;
          break;

        case ERROR_IO_PENDING:
          waitMessage = ::WaitForSingleObject(overlapped.hEvent, timeOut);
          if (waitMessage == WAIT_OBJECT_0)
          {
            DWORD dwIgnore;
            BOOL conn = (::GetOverlappedResult(_hPipe, &overlapped, &dwIgnore, TRUE));
            if (conn)
              connected = true;
            else
              logStream << "ConnectedNamedPipe reported an error: " << sys::OperatingSystem::getLastErrorMessage() << blog::over;
          }
          else
            ::CancelIo(_hPipe);
          break;

        default:
          logStream << "ConnectedNamedPipe reported an error: " << sys::OperatingSystem::getLastErrorMessage() << blog::over;
      }
    }

    if(connected)
    {
      if (::ReadFile(_hPipe, buffer, sizeof(buffer) - 1, &size, NULL))
      {
        buffer[size] = '\0';
        std::string receivedMessage(buffer);
        // if message is received from client, setdirty to call detectDisplay.
        if (clientUniqueMessage.compare(receivedMessage) == 0)
          setDirty();
        else
          logStream << "Incoming message from client does not match with the expected message." << blog::over;
      }
      else
        logStream << "ReadFile failed. " << sys::OperatingSystem::getLastErrorMessage() << blog::over;

    }
    ::DisconnectNamedPipe(_hPipe);
  }
}

1
C++服务器应用程序作为Windows服务运行吗? - Garland
是的,我正在Windows上将C++应用程序作为服务运行。 - Tee
@orhtej2 如果客户端和服务器都是C#应用程序,那么这实际上只解决了问题。请始终清楚地阅读问题。 - Tee
1个回答

1
[CreateNamedPipe函数]的最后一个参数意味着:

lpSecurityAttributes [in, optional]:指向SECURITY_ATTRIBUTES结构体的指针,该结构体指定新命名管道的安全描述符,并确定子进程是否可以继承返回的句柄。如果lpSecurityAttributes为NULL,则命名管道获得默认安全描述符并且句柄不能被继承。命名管道的默认安全描述符中的访问控制项(ACLs)授予LocalSystem账户、管理员和创建者所有者完全控制权限。它们还授予Everyone组和匿名账户的成员读取权限。

C++命名管道服务器应用程序拥有管理员特权,因为它作为Windows服务在LocalSystem帐户下运行。C#客户端应用程序作为标准用户运行,没有管理员特权。默认情况下(lpSecurityAttributesNULL),C#客户端应用程序只能读取由作为服务运行的C++服务器创建的命名管道。
快速测试,如果您将C#客户端应用程序以管理员身份运行,它应该能够成功与C++服务器应用程序通信。
要解决问题,C++服务器应用程序需要为命名管道对象创建安全描述符,并为所有人授予写访问权限。请参见MSDN example以获取创建安全描述符的示例。
我之前为我的作为服务运行的C++服务器应用程序编写了一个class NamedPipeServerStream。以下是与创建命名管道相关的代码部分供您参考。
NamedPipeServerStream::NamedPipeServerStream(const std::string & pipeName, const unsigned pipeBufferSize /*= PIPE_BUFFER_SIZE*/)
    : m_hPipe(INVALID_HANDLE_VALUE)
    , m_pipeName(PIPE_NAME_ROOT + pipeName)
    , m_bConnected(false)
{
    PSID pEveryoneSID = NULL;
    PSID pAdminSID = NULL;
    PACL pACL = NULL;
    EXPLICIT_ACCESS ea[2];
    SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
    SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY;
    SECURITY_ATTRIBUTES sa;
    SCOPE_GUARD{
        if (pEveryoneSID) { FreeSid(pEveryoneSID); }
        if (pAdminSID) { FreeSid(pAdminSID); }
        if (pACL) { LocalFree(pACL); }
    };

    // Create a well-known SID for the Everyone group.
    if (!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID))
    {
        throw std::runtime_error("AllocateAndInitializeSid failed, GLE=" + std::to_string(GetLastError()));
    }
    // Initialize an EXPLICIT_ACCESS structure for an ACE.
    SecureZeroMemory(&ea, 2 * sizeof(EXPLICIT_ACCESS));
    // The ACE will allow Everyone full access to the key.
    ea[0].grfAccessPermissions = FILE_ALL_ACCESS | GENERIC_WRITE | GENERIC_READ;  
    ea[0].grfAccessMode = SET_ACCESS;
    ea[0].grfInheritance = NO_INHERITANCE;
    ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
    ea[0].Trustee.ptstrName = (LPTSTR)pEveryoneSID;

    // Create a SID for the BUILTIN\Administrators group.
    if (!AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pAdminSID))
    {
        throw std::runtime_error("AllocateAndInitializeSid failed, GLE=" + std::to_string(GetLastError()));
    }
    // The ACE will allow the Administrators group full access to the key.
    ea[1].grfAccessPermissions = FILE_ALL_ACCESS | GENERIC_WRITE | GENERIC_READ;   
    ea[1].grfAccessMode = SET_ACCESS;
    ea[1].grfInheritance = NO_INHERITANCE;
    ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ea[1].Trustee.TrusteeType = TRUSTEE_IS_GROUP;
    ea[1].Trustee.ptstrName = (LPTSTR)pAdminSID;

    // Create a new ACL that contains the new ACEs.
    DWORD dwRes = SetEntriesInAclW(2, ea, NULL, &pACL);
    if (ERROR_SUCCESS != dwRes)
    {
        throw std::runtime_error("SetEntriesInAcl failed, GLE=" + std::to_string(GetLastError()));
    }
    // Initialize a security descriptor.  
    auto secDesc = std::vector<unsigned char>(SECURITY_DESCRIPTOR_MIN_LENGTH);
    PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)(&secDesc[0]);
    if (nullptr == pSD)
    {
        throw std::runtime_error("LocalAlloc failed, GLE=" + std::to_string(GetLastError()));
    }
    if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION))
    {
        throw std::runtime_error("InitializeSecurityDescriptor failed, GLE=" + std::to_string(GetLastError()));
    }
    // Add the ACL to the security descriptor. 
    if (!SetSecurityDescriptorDacl(pSD, TRUE, pACL, FALSE))   // not a default DACL 
    {
        throw std::runtime_error("SetSecurityDescriptorDacl failed, GLE=" + std::to_string(GetLastError()));
    }
    // Initialize a security attributes structure.
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = pSD;
    sa.bInheritHandle = FALSE;

    // Finally to create the pipe.
    m_hPipe = CreateNamedPipeA(
        m_pipeName.c_str(),             // pipe name 
        PIPE_ACCESS_DUPLEX,       // read/write access 
        PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE |        // Byte Stream type pipe 
        PIPE_WAIT,                // blocking mode 
        PIPE_UNLIMITED_INSTANCES, // max. instances  
        pipeBufferSize,                  // output buffer size 
        pipeBufferSize,                  // input buffer size 
        0,                        // client time-out 
        &sa);                    // default security attribute 

    if (!IsPipeCreated())
    {
        throw std::runtime_error("CreateNamedPipe failed, GLE=" + std::to_string(GetLastError()));
    }
}

bool NamedPipeServerStream::IsPipeCreated() const
{
    return (INVALID_HANDLE_VALUE != m_hPipe);
}

这实际上解决了问题,通过创建一个安全描述符。谢谢! - Tee
我的同事遇到了一個類似於這個(https://stackoverflow.com/questions/60431348/ipc-uwp-c-sharp-pipe-client-fails-on-connect-c-server)的棘手程序。它是在UWP客戶端和C++服務器之間使用命名管道。你能看一下並給些建議嗎?謝謝!@Garland - Tom Xue
SCOPE_GUARD是从哪里来的?有没有定义这个的Windows头文件?谢谢。 - Mark Uebel
SCOPE_GUARD是我自己编写的作用域保护类和宏,早于GSL。现在你可以使用GSL,例如:auto scopeGuard = gsl::finally([&]() noexcept { LocalFree(imageInfoBuffer); }); - Garland

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接