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