aboutsummaryrefslogtreecommitdiff
path: root/ssh/client.c
blob: fc4ad967576e4053a83dd3dfc6fe1cea3e2d1ba0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <assert.h>
#include <libssh/callbacks.h>
#include <sys/select.h>
#include <poll.h>
#include "util.h"


static bool prompt_yn(const char *text) {
	printf("%s", text);
	fflush(stdout);

	bool response;

	char *line = NULL;
	size_t linelen = 0;
	while (true) {
		ssize_t nr = getline(&line, &linelen, stdin);
		if (nr == -1) {
			perror("getline");
			exit(1);
		}

		while (nr > 0 && isspace(line[nr - 1])) nr--;

		for (ssize_t i = 0; i < nr; i++) line[i] = tolower(line[i]);

		if ((nr == 1 && line[0] == 'y') || (nr == 3 && memcmp(line, "yes", 3) == 0)) {
			response = true;
			break;
		}
		if ((nr == 1 && line[0] == 'n') || (nr == 2 && memcmp(line, "no", 2) == 0)) {
			response = false;
			break;
		}

		printf("Please answer with 'y', 'n', 'yes' or 'no'. [y/n]");
		fflush(stdout);
	}

	free(line);
	return response;
}

struct session_data {
	ssh_session session;
	ssh_channel channel;
	bool should_close;
};

void channel_close_cb(ssh_session session, ssh_channel channel, void *sesdata_) {
	(void)session; (void)channel;
	struct session_data *sesdata = (struct session_data*)sesdata_;
	sesdata->should_close = true;
}

void channel_eof_cb(ssh_session session, ssh_channel channel, void *sesdata_) {
	(void)session; (void)channel;
	struct session_data *sesdata = (struct session_data*)sesdata_;
	sesdata->should_close = true;
}

int channel_data_cb(ssh_session session, ssh_channel channel, void *data, uint32_t len, int is_stderr, void *sesdata_) {
	(void)session; (void)channel; (void)is_stderr;
	struct session_data *sesdata = (struct session_data*)sesdata_;

	const char *start = (const char*)data;
	const char *cursor = start;
	const char *end = cursor + len;

	while (cursor < end) {
		ssize_t nw = write(STDOUT_FILENO, cursor, end - cursor);
		if (nw < 0) {
			if (errno == EINTR) continue;
			perror("write(stdout)");
			sesdata->should_close = true;
			return cursor - start;
		}
		assert(nw > 0);
		cursor += nw;
	}

	return len;
}

int channel_write_wontblock_cb(ssh_session session, ssh_channel channel, size_t bytes, void *sesdata_) {
	(void)session; (void)channel; (void)sesdata_;
	fprintf(stderr, "(write won't block for %zu bytes)\n", bytes);
	return 0;
}

int stdin_data_cb(int fd, int revents, void *sesdata_) {
	(void)fd;
	struct session_data *sesdata = (struct session_data*)sesdata_;

	if (revents & POLLIN) {
		char buffer[1024];
		ssize_t nr = read(STDIN_FILENO, buffer, sizeof buffer);
		if (nr < 0) {
			if (errno == EINTR) return 0;
			perror("read(stdin)");
			sesdata->should_close = true;
			return 0;
		}

		if (nr == 0) {  // eof
			sesdata->should_close = true;
			return 0;
		}

		const char *cursor = buffer;
		while (cursor < buffer + nr) {
			int ret = ssh_channel_write(sesdata->channel, cursor, buffer + nr - cursor);
			if (ret == SSH_ERROR) {
				fprintf(stderr, "Error writing to channel: %s\n",
						ssh_get_error(sesdata->channel));
				sesdata->should_close = true;
				return 0;
			}
			assert(ret > 0);
			cursor += ret;
		}
	}
	return 0;
}

int main(int argc, char **argv) {
	const char *server_host = NULL;
	int port = 2222;

	if (argc != 2) {
		fprintf(stderr, "Usage: %s <server[:port]>\n", argv[0]);
		fprintf(stderr, "If port is not specified, %d is assumed.\n", port);
		return 1;
	}

	if (!parse_host_port(argv[1], &server_host, &port)) {
		fprintf(stderr, "Cannot parse host:port from argument '%s'\n", argv[1]);
		return 1;
	}

	ssh_session session = ssh_new();
	if (!session) {
		fprintf(stderr, "Could not open SSH session\n");
		goto cleanup_unconnected;
	}

	const char *ciphers_str = "aes256-gcm@openssh.com,aes256-ctr,aes256-cbc";
	bool procconfig = false;
	bool ok = true;
	ok &= ssh_options_set(session, SSH_OPTIONS_PROCESS_CONFIG, &procconfig) == SSH_OK;
	ok &= ssh_options_set(session, SSH_OPTIONS_USER, "tomsg") == SSH_OK;
	ok &= ssh_options_set(session, SSH_OPTIONS_HOST, server_host) == SSH_OK;
	ok &= ssh_options_set(session, SSH_OPTIONS_PORT, &port) == SSH_OK;
	ok &= ssh_options_set(session, SSH_OPTIONS_CIPHERS_C_S, ciphers_str) == SSH_OK;
	ok &= ssh_options_set(session, SSH_OPTIONS_CIPHERS_S_C, ciphers_str) == SSH_OK;
	// int loglevel = SSH_LOG_PROTOCOL;
	// ok &= ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &loglevel) == SSH_OK;

	if (!ok) {
		fprintf(stderr, "Could not set options on SSH session: %s\n", ssh_get_error(session));
		goto cleanup_unconnected;
	}

	if (ssh_connect(session) != SSH_OK) {
		fprintf(stderr, "Could not connect to %s:%d: %s\n",
				server_host, port, ssh_get_error(session));
		goto cleanup_unconnected;
	}

	ssh_key host_key;
	if (ssh_get_server_publickey(session, &host_key) != SSH_OK) {
		fprintf(stderr, "Could not get host key from session: %s\n", ssh_get_error(session));
		goto cleanup_connected;
	}

	unsigned char *host_key_hash = NULL;
	size_t host_key_hash_length = 0;
	if (ssh_get_publickey_hash(host_key, SSH_PUBLICKEY_HASH_SHA256, &host_key_hash, &host_key_hash_length) != SSH_OK) {
		fprintf(stderr, "Failed to hash host key!\n");
		goto cleanup_connected;
	}

	printf("Server host key hash: ");
	fflush(stdout);
	ssh_print_hash(SSH_PUBLICKEY_HASH_SHA256, host_key_hash, host_key_hash_length);

	bool response = prompt_yn(
			"Does this hash match the one given to you by the server administrator, or by a\n"
			"member that you trust and is already connected to the server? [y/n] ");
	if (!response) {
		printf("Disconnecting.\n");
		goto cleanup_connected;
	}

	printf("Connected.\n");

retry_userauth:
	switch (ssh_userauth_none(session, NULL)) {
		case SSH_AUTH_ERROR:
			fprintf(stderr, "Error authenticating: %s\n", ssh_get_error(session));
			return 1;

		case SSH_AUTH_DENIED:
		case SSH_AUTH_PARTIAL:
			fprintf(stderr, "Server denied authentication.\n");
			return 1;

		case SSH_AUTH_SUCCESS:
			break;

		case SSH_AUTH_AGAIN:
			if (ssh_get_status(session) & (SSH_CLOSED | SSH_CLOSED_ERROR)) {
				fprintf(stderr, "Socket unexpectedly closed!\n");
				return 1;
			}
			goto retry_userauth;
	}

	printf("Authenticated.\n");

	ssh_channel channel = ssh_channel_new(session);
	if (!channel) {
		fprintf(stderr, "Failed to allocate channel: %s\n", ssh_get_error(session));
		goto cleanup_connected;
	}

	printf("Created channel\n");

	if (ssh_channel_open_session(channel) != SSH_OK) {
		fprintf(stderr, "Failed to open channel: %s\n", ssh_get_error(channel));
		goto cleanup_connected;
	}

	printf("Opened channel\n");

	if (ssh_channel_request_subsystem(channel, "tomsg") != SSH_OK) {
		fprintf(stderr, "Server did not allow opening 'tomsg' channel: %s\n", ssh_get_error(channel));
		goto cleanup_connected;
	}

	printf("Obtained tomsg subsystem on channel\n");

	struct session_data *sesdata = malloc(sizeof(struct session_data));
	if (!sesdata) {
		fprintf(stderr, "Out of memory (allocating session_data)!\n");
		return 1;
	}

	sesdata->session = session;
	sesdata->channel = channel;
	sesdata->should_close = false;

	struct ssh_channel_callbacks_struct chan_cb;
	memset(&chan_cb, 0, sizeof chan_cb);
	ssh_callbacks_init(&chan_cb);
	chan_cb.userdata = sesdata;
	chan_cb.channel_close_function = channel_close_cb;
	chan_cb.channel_eof_function = channel_eof_cb;
	chan_cb.channel_data_function = channel_data_cb;
	chan_cb.channel_write_wontblock_function = channel_write_wontblock_cb;

	if (ssh_set_channel_callbacks(channel, &chan_cb) != SSH_OK) {
		fprintf(stderr, "Failed to set channel callbacks\n");
		goto cleanup_connected;
	}

	printf("Set callbacks\n");

	ssh_event event = ssh_event_new();
	if (!event
			|| ssh_event_add_session(event, session) != SSH_OK
			|| ssh_event_add_fd(event, STDIN_FILENO, POLLIN, stdin_data_cb, sesdata) != SSH_OK) {
		fprintf(stderr, "Failed to create ssh event context\n");
		goto cleanup_connected;
	}

	printf("Created event object\n");

	while (!sesdata->should_close) {
		// printf("poll loop...\n");
		ssh_event_dopoll(event, -1);
		int status = ssh_get_status(session);
		if (status & (SSH_CLOSED | SSH_CLOSED_ERROR)) goto cleanup_connected;
		if (status & SSH_READ_PENDING) {
			printf("read pending?\n");
		}
	}

cleanup_connected:
	ssh_disconnect(session);
cleanup_unconnected:
	ssh_free(session);
}