libssh2

Форк
0
/
tcpip-forward.c 
351 строка · 10.5 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * SPDX-License-Identifier: BSD-3-Clause
4
 */
5

6
#include "libssh2_setup.h"
7
#include <libssh2.h>
8

9
#ifdef _WIN32
10
#include <ws2tcpip.h>  /* for socklen_t */
11
#define recv(s, b, l, f)  recv((s), (b), (int)(l), (f))
12
#define send(s, b, l, f)  send((s), (b), (int)(l), (f))
13
#endif
14

15
#ifdef HAVE_SYS_SOCKET_H
16
#include <sys/socket.h>
17
#endif
18
#ifdef HAVE_UNISTD_H
19
#include <unistd.h>
20
#endif
21
#ifdef HAVE_NETINET_IN_H
22
#include <netinet/in.h>
23
#endif
24
#ifdef HAVE_ARPA_INET_H
25
#include <arpa/inet.h>
26
#endif
27

28
#include <stdio.h>
29
#include <stdlib.h>
30
#include <string.h>
31

32
#ifndef INADDR_NONE
33
#define INADDR_NONE (in_addr_t)~0
34
#endif
35

36
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
37
static const char *privkey = "/home/username/.ssh/id_rsa";
38
static const char *username = "username";
39
static const char *password = "";
40

41
static const char *server_ip = "127.0.0.1";
42

43
/* resolved by the server */
44
static const char *remote_listenhost = "localhost";
45

46
static int remote_wantport = 2222;
47
static int remote_listenport;
48

49
static const char *local_destip = "127.0.0.1";
50
static int local_destport = 22;
51

52
enum {
53
    AUTH_NONE = 0,
54
    AUTH_PASSWORD = 1,
55
    AUTH_PUBLICKEY = 2
56
};
57

58
int main(int argc, char *argv[])
59
{
60
    int i, auth = AUTH_NONE;
61
    struct sockaddr_in sin;
62
    socklen_t sinlen = sizeof(sin);
63
    const char *fingerprint;
64
    char *userauthlist;
65
    int rc;
66
    LIBSSH2_SESSION *session = NULL;
67
    LIBSSH2_LISTENER *listener = NULL;
68
    LIBSSH2_CHANNEL *channel = NULL;
69
    struct timeval tv;
70
    ssize_t len, wr;
71
    char buf[16384];
72
    libssh2_socket_t sock;
73
    libssh2_socket_t forwardsock = LIBSSH2_INVALID_SOCKET;
74

75
#ifdef _WIN32
76
    WSADATA wsadata;
77

78
    rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
79
    if(rc) {
80
        fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
81
        return 1;
82
    }
83
#endif
84

85
    if(argc > 1)
86
        server_ip = argv[1];
87
    if(argc > 2)
88
        username = argv[2];
89
    if(argc > 3)
90
        password = argv[3];
91
    if(argc > 4)
92
        remote_listenhost = argv[4];
93
    if(argc > 5)
94
        remote_wantport = atoi(argv[5]);
95
    if(argc > 6)
96
        local_destip = argv[6];
97
    if(argc > 7)
98
        local_destport = atoi(argv[7]);
99

100
    rc = libssh2_init(0);
101
    if(rc) {
102
        fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
103
        return 1;
104
    }
105

106
    /* Connect to SSH server */
107
    sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
108
    if(sock == LIBSSH2_INVALID_SOCKET) {
109
        fprintf(stderr, "failed to open socket.\n");
110
        goto shutdown;
111
    }
112

113
    sin.sin_family = AF_INET;
114
    sin.sin_addr.s_addr = inet_addr(server_ip);
115
    if(INADDR_NONE == sin.sin_addr.s_addr) {
116
        fprintf(stderr, "inet_addr: Invalid IP address '%s'\n", server_ip);
117
        goto shutdown;
118
    }
119
    sin.sin_port = htons(22);
120
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
121
        fprintf(stderr, "Failed to connect to %s.\n", inet_ntoa(sin.sin_addr));
122
        goto shutdown;
123
    }
124

125
    /* Create a session instance */
126
    session = libssh2_session_init();
127
    if(!session) {
128
        fprintf(stderr, "Could not initialize SSH session.\n");
129
        goto shutdown;
130
    }
131

132
    /* ... start it up. This will trade welcome banners, exchange keys,
133
     * and setup crypto, compression, and MAC layers
134
     */
135
    rc = libssh2_session_handshake(session, sock);
136
    if(rc) {
137
        fprintf(stderr, "Error when starting up SSH session: %d\n", rc);
138
        goto shutdown;
139
    }
140

141
    /* At this point we have not yet authenticated.  The first thing to do
142
     * is check the hostkey's fingerprint against our known hosts Your app
143
     * may have it hard coded, may go to a file, may present it to the
144
     * user, that's your call
145
     */
146
    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
147
    fprintf(stderr, "Fingerprint: ");
148
    for(i = 0; i < 20; i++)
149
        fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
150
    fprintf(stderr, "\n");
151

152
    /* check what authentication methods are available */
153
    userauthlist = libssh2_userauth_list(session, username,
154
                                         (unsigned int)strlen(username));
155
    if(userauthlist) {
156
        fprintf(stderr, "Authentication methods: %s\n", userauthlist);
157
        if(strstr(userauthlist, "password"))
158
            auth |= AUTH_PASSWORD;
159
        if(strstr(userauthlist, "publickey"))
160
            auth |= AUTH_PUBLICKEY;
161

162
        /* check for options */
163
        if(argc > 8) {
164
            if((auth & AUTH_PASSWORD) && !strcmp(argv[8], "-p"))
165
                auth = AUTH_PASSWORD;
166
            if((auth & AUTH_PUBLICKEY) && !strcmp(argv[8], "-k"))
167
                auth = AUTH_PUBLICKEY;
168
        }
169

170
        if(auth & AUTH_PASSWORD) {
171
            if(libssh2_userauth_password(session, username, password)) {
172
                fprintf(stderr, "Authentication by password failed.\n");
173
                goto shutdown;
174
            }
175
        }
176
        else if(auth & AUTH_PUBLICKEY) {
177
            if(libssh2_userauth_publickey_fromfile(session, username,
178
                                                   pubkey, privkey,
179
                                                   password)) {
180
                fprintf(stderr, "Authentication by public key failed.\n");
181
                goto shutdown;
182
            }
183
            else {
184
                fprintf(stderr, "Authentication by public key succeeded.\n");
185
            }
186
        }
187
        else {
188
            fprintf(stderr, "No supported authentication methods found.\n");
189
            goto shutdown;
190
        }
191
    }
192

193
    fprintf(stderr, "Asking server to listen on remote %s:%d\n",
194
            remote_listenhost, remote_wantport);
195

196
    listener = libssh2_channel_forward_listen_ex(session, remote_listenhost,
197
                                                 remote_wantport,
198
                                                 &remote_listenport, 1);
199
    if(!listener) {
200
        fprintf(stderr, "Could not start the tcpip-forward listener.\n"
201
                        "(Note that this can be a problem at the server."
202
                        " Please review the server logs.)\n");
203
        goto shutdown;
204
    }
205

206
    fprintf(stderr, "Server is listening on %s:%d\n", remote_listenhost,
207
            remote_listenport);
208

209
    fprintf(stderr, "Waiting for remote connection\n");
210
    channel = libssh2_channel_forward_accept(listener);
211
    if(!channel) {
212
        fprintf(stderr, "Could not accept connection.\n"
213
                        "(Note that this can be a problem at the server."
214
                        " Please review the server logs.)\n");
215
        goto shutdown;
216
    }
217

218
    fprintf(stderr,
219
            "Accepted remote connection. Connecting to local server %s:%d\n",
220
            local_destip, local_destport);
221
    forwardsock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
222
    if(forwardsock == LIBSSH2_INVALID_SOCKET) {
223
        fprintf(stderr, "failed to open forward socket.\n");
224
        goto shutdown;
225
    }
226

227
    sin.sin_family = AF_INET;
228
    sin.sin_port = htons((unsigned short)local_destport);
229
    sin.sin_addr.s_addr = inet_addr(local_destip);
230
    if(INADDR_NONE == sin.sin_addr.s_addr) {
231
        fprintf(stderr, "failed in inet_addr().\n");
232
        goto shutdown;
233
    }
234
    if(-1 == connect(forwardsock, (struct sockaddr *)&sin, sinlen)) {
235
        fprintf(stderr, "failed to connect().\n");
236
        goto shutdown;
237
    }
238

239
    fprintf(stderr, "Forwarding connection from remote %s:%d to local %s:%d\n",
240
            remote_listenhost, remote_listenport,
241
            local_destip, local_destport);
242

243
    /* Must use non-blocking IO hereafter due to the current libssh2 API */
244
    libssh2_session_set_blocking(session, 0);
245

246
    for(;;) {
247
        fd_set fds;
248
        FD_ZERO(&fds);
249
#if defined(__GNUC__)
250
#pragma GCC diagnostic push
251
#pragma GCC diagnostic ignored "-Wsign-conversion"
252
#endif
253
        FD_SET(forwardsock, &fds);
254
#if defined(__GNUC__)
255
#pragma GCC diagnostic pop
256
#endif
257
        tv.tv_sec = 0;
258
        tv.tv_usec = 100000;
259
        rc = select((int)(forwardsock + 1), &fds, NULL, NULL, &tv);
260
        if(-1 == rc) {
261
            fprintf(stderr, "failed to select().\n");
262
            goto shutdown;
263
        }
264
#if defined(__GNUC__)
265
#pragma GCC diagnostic push
266
#pragma GCC diagnostic ignored "-Wsign-conversion"
267
#endif
268
        if(rc && FD_ISSET(forwardsock, &fds)) {
269
#if defined(__GNUC__)
270
#pragma GCC diagnostic pop
271
#endif
272
            ssize_t nwritten;
273
            len = recv(forwardsock, buf, sizeof(buf), 0);
274
            if(len < 0) {
275
                fprintf(stderr, "failed to recv().\n");
276
                goto shutdown;
277
            }
278
            else if(len == 0) {
279
                fprintf(stderr, "The local server at %s:%d disconnected.\n",
280
                        local_destip, local_destport);
281
                goto shutdown;
282
            }
283
            wr = 0;
284
            do {
285
                nwritten = libssh2_channel_write(channel, buf, (size_t)len);
286
                if(nwritten < 0) {
287
                    fprintf(stderr, "libssh2_channel_write: %ld\n",
288
                            (long)nwritten);
289
                    goto shutdown;
290
                }
291
                wr += nwritten;
292
            } while(nwritten > 0 && wr < len);
293
        }
294
        for(;;) {
295
            ssize_t nsent;
296
            len = libssh2_channel_read(channel, buf, sizeof(buf));
297
            if(LIBSSH2_ERROR_EAGAIN == len)
298
                break;
299
            else if(len < 0) {
300
                fprintf(stderr, "libssh2_channel_read: %ld",
301
                        (long)len);
302
                goto shutdown;
303
            }
304
            wr = 0;
305
            while(wr < len) {
306
                nsent = send(forwardsock, buf + wr, (size_t)(len - wr), 0);
307
                if(nsent <= 0) {
308
                    fprintf(stderr, "failed to send().\n");
309
                    goto shutdown;
310
                }
311
                wr += nsent;
312
            }
313
            if(libssh2_channel_eof(channel)) {
314
                fprintf(stderr, "The remote client at %s:%d disconnected.\n",
315
                        remote_listenhost, remote_listenport);
316
                goto shutdown;
317
            }
318
        }
319
    }
320

321
shutdown:
322

323
    if(forwardsock != LIBSSH2_INVALID_SOCKET) {
324
        shutdown(forwardsock, 2);
325
        LIBSSH2_SOCKET_CLOSE(forwardsock);
326
    }
327

328
    if(channel)
329
        libssh2_channel_free(channel);
330

331
    if(listener)
332
        libssh2_channel_forward_cancel(listener);
333

334
    if(session) {
335
        libssh2_session_disconnect(session, "Normal Shutdown");
336
        libssh2_session_free(session);
337
    }
338

339
    if(sock != LIBSSH2_INVALID_SOCKET) {
340
        shutdown(sock, 2);
341
        LIBSSH2_SOCKET_CLOSE(sock);
342
    }
343

344
    libssh2_exit();
345

346
#ifdef _WIN32
347
    WSACleanup();
348
#endif
349

350
    return 0;
351
}
352

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.