named-pipe-client.c 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Windows support module which deals with being a named-pipe client.
  3. */
  4. #include <stdio.h>
  5. #include <assert.h>
  6. #include "tree234.h"
  7. #include "putty.h"
  8. #include "network.h"
  9. #include "proxy/proxy.h"
  10. #include "ssh.h"
  11. #include "security-api.h"
  12. HANDLE connect_to_named_pipe(const char *pipename, char **err)
  13. {
  14. HANDLE pipehandle;
  15. PSID usersid, pipeowner;
  16. PSECURITY_DESCRIPTOR psd;
  17. assert(strncmp(pipename, "\\\\.\\pipe\\", 9) == 0);
  18. assert(strchr(pipename + 9, '\\') == NULL);
  19. while (1) {
  20. pipehandle = CreateFile(pipename, GENERIC_READ | GENERIC_WRITE,
  21. 0, NULL, OPEN_EXISTING,
  22. FILE_FLAG_OVERLAPPED, NULL);
  23. if (pipehandle != INVALID_HANDLE_VALUE)
  24. break;
  25. if (GetLastError() != ERROR_PIPE_BUSY) {
  26. *err = dupprintf(
  27. "Unable to open named pipe '%s': %s",
  28. pipename, win_strerror(GetLastError()));
  29. return INVALID_HANDLE_VALUE;
  30. }
  31. /*
  32. * If we got ERROR_PIPE_BUSY, wait for the server to create a
  33. * new pipe instance. (Since the server is expected to be
  34. * named-pipe-server.c, which will do that immediately after a
  35. * previous connection is accepted, that shouldn't take
  36. * excessively long.)
  37. */
  38. if (!WaitNamedPipe(pipename, NMPWAIT_USE_DEFAULT_WAIT)) {
  39. *err = dupprintf(
  40. "Error waiting for named pipe '%s': %s",
  41. pipename, win_strerror(GetLastError()));
  42. return INVALID_HANDLE_VALUE;
  43. }
  44. }
  45. if ((usersid = get_user_sid()) == NULL) {
  46. CloseHandle(pipehandle);
  47. *err = dupprintf(
  48. "Unable to get user SID: %s", win_strerror(GetLastError()));
  49. return INVALID_HANDLE_VALUE;
  50. }
  51. if (p_GetSecurityInfo(pipehandle, SE_KERNEL_OBJECT,
  52. OWNER_SECURITY_INFORMATION,
  53. &pipeowner, NULL, NULL, NULL,
  54. &psd) != ERROR_SUCCESS) {
  55. CloseHandle(pipehandle);
  56. *err = dupprintf(
  57. "Unable to get named pipe security information: %s",
  58. win_strerror(GetLastError()));
  59. return INVALID_HANDLE_VALUE;
  60. }
  61. if (!EqualSid(pipeowner, usersid)) {
  62. CloseHandle(pipehandle);
  63. LocalFree(psd);
  64. *err = dupprintf(
  65. "Owner of named pipe '%s' is not us", pipename);
  66. return INVALID_HANDLE_VALUE;
  67. }
  68. LocalFree(psd);
  69. return pipehandle;
  70. }
  71. Socket *new_named_pipe_client(const char *pipename, Plug *plug)
  72. {
  73. char *err = NULL;
  74. HANDLE pipehandle = connect_to_named_pipe(pipename, &err);
  75. if (pipehandle == INVALID_HANDLE_VALUE)
  76. return new_error_socket_consume_string(plug, err);
  77. else
  78. return make_handle_socket(pipehandle, pipehandle, NULL, NULL, 0,
  79. plug, true);
  80. }