libssh2

Форк
0
517 строк · 13.1 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * Sample showing how to makes SSH2 with X11 Forwarding works.
4
 *
5
 * $ ./x11 host user password [DEBUG]
6
 *
7
 * SPDX-License-Identifier: BSD-3-Clause
8
 */
9

10
#include "libssh2_setup.h"
11
#include <libssh2.h>
12

13
#include <stdio.h>
14

15
#ifdef HAVE_SYS_UN_H
16

17
#ifdef HAVE_SYS_IOCTL_H
18
#include <sys/ioctl.h>
19
#endif
20
#ifdef HAVE_NETINET_IN_H
21
#include <netinet/in.h>
22
#endif
23
#ifdef HAVE_SYS_SOCKET_H
24
#include <sys/socket.h>
25
#endif
26
#ifdef HAVE_UNISTD_H
27
#include <unistd.h>
28
#endif
29
#ifdef HAVE_ARPA_INET_H
30
#include <arpa/inet.h>
31
#endif
32
#ifdef HAVE_SYS_UN_H
33
#include <sys/un.h>
34
#endif
35

36
#include <stdlib.h>
37
#include <string.h>
38

39
#include <termios.h>
40

41
#define _PATH_UNIX_X "/tmp/.X11-unix/X%d"
42

43
/*
44
 * Chained list that contains channels and associated X11 socket for each X11
45
 * connections
46
 */
47
struct chan_X11_list {
48
    LIBSSH2_CHANNEL  *chan;
49
    libssh2_socket_t  sock;
50
    struct chan_X11_list *next;
51
};
52

53
static struct chan_X11_list * gp_x11_chan = NULL;
54
static struct termios         _saved_tio;
55

56
/*
57
 * Utility function to remove a Node of the chained list
58
 */
59
static void remove_node(struct chan_X11_list *elem)
60
{
61
    struct chan_X11_list *current_node = NULL;
62

63
    current_node = gp_x11_chan;
64

65
    if(gp_x11_chan == elem) {
66
        gp_x11_chan = gp_x11_chan->next;
67
        free(current_node);
68
        return;
69
    }
70

71
    while(current_node->next) {
72
        if(current_node->next == elem) {
73
            current_node->next = current_node->next->next;
74
            current_node = current_node->next;
75
            free(current_node);
76
            break;
77
        }
78
    }
79
}
80

81

82
static void session_shutdown(LIBSSH2_SESSION *session)
83
{
84
    libssh2_session_disconnect(session, "Normal Shutdown");
85
    libssh2_session_free(session);
86
}
87

88
static int _raw_mode(void)
89
{
90
    int rc;
91
    struct termios tio;
92

93
    rc = tcgetattr(fileno(stdin), &tio);
94
    if(rc != -1) {
95
        _saved_tio = tio;
96
        /* do the equivalent of cfmakeraw() manually, to build on Solaris */
97
        tio.c_iflag &= ~(tcflag_t)(IGNBRK|BRKINT|PARMRK|ISTRIP|
98
                                   INLCR|IGNCR|ICRNL|IXON);
99
        tio.c_oflag &= ~(tcflag_t)OPOST;
100
        tio.c_lflag &= ~(tcflag_t)(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
101
        tio.c_cflag &= ~(tcflag_t)(CSIZE|PARENB);
102
        tio.c_cflag |= CS8;
103
        rc = tcsetattr(fileno(stdin), TCSADRAIN, &tio);
104
    }
105
    return rc;
106
}
107

108
static int _normal_mode(void)
109
{
110
    int rc;
111
    rc = tcsetattr(fileno(stdin), TCSADRAIN, &_saved_tio);
112
    return rc;
113
}
114

115
/*
116
 * CallBack to initialize the forwarding.
117
 * Save the channel to loop on it, save the X11 forwarded socket to send
118
 * and receive info from our X server.
119
 */
120
static void x11_callback(LIBSSH2_SESSION *session, LIBSSH2_CHANNEL *channel,
121
                         char *shost, int sport, void **abstract)
122
{
123
    const char *display;
124
    char *ptr;
125
    char *temp_buff;
126
    int display_port;
127
    int rc;
128
    libssh2_socket_t sock = LIBSSH2_INVALID_SOCKET;
129
    struct sockaddr_un addr;
130
    struct chan_X11_list *new;
131
    struct chan_X11_list *chan_iter;
132
    (void)session;
133
    (void)shost;
134
    (void)sport;
135
    (void)abstract;
136
    /*
137
     * Connect to the display
138
     * Inspired by x11_connect_display in openssh
139
     */
140
    display = getenv("DISPLAY");
141
    if(display) {
142
        if(strncmp(display, "unix:", 5) == 0 ||
143
            display[0] == ':') {
144
            /* Connect to the local unix domain */
145
            ptr = strrchr(display, ':');
146
            temp_buff = (char *)calloc(strlen(ptr + 1) + 1, sizeof(char));
147
            if(!temp_buff) {
148
                fprintf(stderr, "failed to calloc().\n");
149
                return;
150
            }
151
            memcpy(temp_buff, ptr + 1, strlen(ptr + 1));
152
            display_port = atoi(temp_buff);
153
            free(temp_buff);
154

155
            sock = socket(AF_UNIX, SOCK_STREAM, 0);
156
            if(sock == LIBSSH2_INVALID_SOCKET)
157
                return;
158
            memset(&addr, 0, sizeof(addr));
159
            addr.sun_family = AF_UNIX;
160
            snprintf(addr.sun_path, sizeof(addr.sun_path),
161
                     _PATH_UNIX_X, display_port);
162
            rc = connect(sock, (struct sockaddr *) &addr, sizeof(addr));
163

164
            if(rc != -1) {
165
                /* Connection Successful */
166
                if(!gp_x11_chan) {
167
                    /* Calloc ensure that gp_X11_chan is full of 0 */
168
                    gp_x11_chan = (struct chan_X11_list *)
169
                        calloc(1, sizeof(struct chan_X11_list));
170
                    gp_x11_chan->sock = sock;
171
                    gp_x11_chan->chan = channel;
172
                    gp_x11_chan->next = NULL;
173
                }
174
                else {
175
                    chan_iter = gp_x11_chan;
176
                    while(chan_iter->next)
177
                        chan_iter = chan_iter->next;
178
                    /* Create the new Node */
179
                    new = (struct chan_X11_list *)
180
                        malloc(sizeof(struct chan_X11_list));
181
                    new->sock = sock;
182
                    new->chan = channel;
183
                    new->next = NULL;
184
                    chan_iter->next = new;
185
                }
186
            }
187
            else {
188
                shutdown(sock, SHUT_RDWR);
189
                LIBSSH2_SOCKET_CLOSE(sock);
190
            }
191
        }
192
    }
193
    return;
194
}
195

196
/*
197
 * Send and receive Data for the X11 channel.
198
 * If the connection is closed, returns -1, 0 either.
199
 */
200
static int x11_send_receive(LIBSSH2_CHANNEL *channel, libssh2_socket_t sock)
201
{
202
    char *buf;
203
    unsigned int bufsize = 8192;
204
    int rc;
205
    unsigned int nfds = 1;
206
    LIBSSH2_POLLFD *fds = NULL;
207
    fd_set set;
208
    struct timeval timeval_out;
209
    timeval_out.tv_sec = 0;
210
    timeval_out.tv_usec = 0;
211

212
    FD_ZERO(&set);
213
#if defined(__GNUC__)
214
#pragma GCC diagnostic push
215
#pragma GCC diagnostic ignored "-Wsign-conversion"
216
#endif
217
    FD_SET(sock, &set);
218
#if defined(__GNUC__)
219
#pragma GCC diagnostic pop
220
#endif
221

222
    buf = calloc(bufsize, sizeof(char));
223
    if(!buf)
224
        return 0;
225

226
    fds = malloc(sizeof(LIBSSH2_POLLFD));
227
    if(!fds) {
228
        free(buf);
229
        return 0;
230
    }
231

232
    fds[0].type = LIBSSH2_POLLFD_CHANNEL;
233
    fds[0].fd.channel = channel;
234
    fds[0].events = LIBSSH2_POLLFD_POLLIN;
235
    fds[0].revents = LIBSSH2_POLLFD_POLLIN;
236

237
    rc = libssh2_poll(fds, nfds, 0);
238
    if(rc > 0) {
239
        ssize_t nread;
240
        nread = libssh2_channel_read(channel, buf, bufsize);
241
        if(nread > 0)
242
            write(sock, buf, (size_t)nread);
243
    }
244

245
    rc = select((int)(sock + 1), &set, NULL, NULL, &timeval_out);
246
    if(rc > 0) {
247
        ssize_t nread;
248

249
        memset(buf, 0, bufsize);
250

251
        /* Data in sock */
252
        nread = read(sock, buf, bufsize);
253
        if(nread > 0) {
254
            libssh2_channel_write(channel, buf, (size_t)nread);
255
        }
256
        else {
257
            free(buf);
258
            return -1;
259
        }
260
    }
261

262
    free(fds);
263
    free(buf);
264
    if(libssh2_channel_eof(channel) == 1) {
265
        return -1;
266
    }
267
    return 0;
268
}
269

270
/*
271
 * Main, more than inspired by ssh2.c by Bagder
272
 */
273
int main(int argc, char *argv[])
274
{
275
    uint32_t hostaddr = 0;
276
    int rc;
277
    libssh2_socket_t sock = LIBSSH2_INVALID_SOCKET;
278
    struct sockaddr_in sin;
279
    LIBSSH2_SESSION *session = NULL;
280
    LIBSSH2_CHANNEL *channel;
281
    char *username = NULL;
282
    char *password = NULL;
283
    size_t bufsiz = 8193;
284
    char *buf = NULL;
285
    int set_debug_on = 0;
286
    unsigned int nfds = 1;
287
    LIBSSH2_POLLFD *fds = NULL;
288

289
    /* Chan List struct */
290
    struct chan_X11_list *current_node = NULL;
291

292
    /* Struct winsize for term size */
293
    struct winsize w_size;
294
    struct winsize w_size_bck;
295

296
    /* For select on stdin */
297
    fd_set set;
298
    struct timeval timeval_out;
299
    timeval_out.tv_sec = 0;
300
    timeval_out.tv_usec = 10;
301

302
    if(argc > 3) {
303
        hostaddr = inet_addr(argv[1]);
304
        username = argv[2];
305
        password = argv[3];
306
    }
307
    else {
308
        fprintf(stderr, "Usage: %s destination username password",
309
                argv[0]);
310
        return -1;
311
    }
312

313
    if(argc > 4) {
314
        set_debug_on = 1;
315
        fprintf(stderr, "DEBUG is ON: %d\n", set_debug_on);
316
    }
317

318
    rc = libssh2_init(0);
319
    if(rc) {
320
        fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
321
        return 1;
322
    }
323

324
    sock = socket(AF_INET, SOCK_STREAM, 0);
325
    if(sock == LIBSSH2_INVALID_SOCKET) {
326
        fprintf(stderr, "failed to open socket.\n");
327
        return -1;
328
    }
329

330
    sin.sin_family = AF_INET;
331
    sin.sin_port = htons(22);
332
    sin.sin_addr.s_addr = hostaddr;
333

334
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
335
        fprintf(stderr, "Failed to established connection.\n");
336
        return -1;
337
    }
338
    /* Open a session */
339
    session = libssh2_session_init();
340
    rc      = libssh2_session_handshake(session, sock);
341
    if(rc) {
342
        fprintf(stderr, "Failed Start the SSH session\n");
343
        return -1;
344
    }
345

346
    if(set_debug_on == 1)
347
        libssh2_trace(session, LIBSSH2_TRACE_CONN);
348

349
    /* Set X11 Callback */
350
    libssh2_session_callback_set2(session, LIBSSH2_CALLBACK_X11,
351
                                  (libssh2_cb_generic *)x11_callback);
352

353
    /* Authenticate via password */
354
    rc = libssh2_userauth_password(session, username, password);
355
    if(rc) {
356
        fprintf(stderr, "Failed to authenticate\n");
357
        session_shutdown(session);
358
        shutdown(sock, SHUT_RDWR);
359
        LIBSSH2_SOCKET_CLOSE(sock);
360
        return -1;
361
    }
362

363
    /* Open a channel */
364
    channel = libssh2_channel_open_session(session);
365
    if(!channel) {
366
        fprintf(stderr, "Failed to open a new channel\n");
367
        session_shutdown(session);
368
        shutdown(sock, SHUT_RDWR);
369
        LIBSSH2_SOCKET_CLOSE(sock);
370
        return -1;
371
    }
372

373
    /* Request a PTY */
374
    rc = libssh2_channel_request_pty(channel, "xterm");
375
    if(rc) {
376
        fprintf(stderr, "Failed to request a pty\n");
377
        session_shutdown(session);
378
        shutdown(sock, SHUT_RDWR);
379
        LIBSSH2_SOCKET_CLOSE(sock);
380
        return -1;
381
    }
382

383
    /* Request X11 */
384
    rc = libssh2_channel_x11_req(channel, 0);
385
    if(rc) {
386
        fprintf(stderr, "Failed to request X11 forwarding\n");
387
        session_shutdown(session);
388
        shutdown(sock, SHUT_RDWR);
389
        LIBSSH2_SOCKET_CLOSE(sock);
390
        return -1;
391
    }
392

393
    /* Request a shell */
394
    rc = libssh2_channel_shell(channel);
395
    if(rc) {
396
        fprintf(stderr, "Failed to open a shell\n");
397
        session_shutdown(session);
398
        shutdown(sock, SHUT_RDWR);
399
        LIBSSH2_SOCKET_CLOSE(sock);
400
        return -1;
401
    }
402

403
    rc = _raw_mode();
404
    if(rc) {
405
        fprintf(stderr, "Failed to entered in raw mode\n");
406
        session_shutdown(session);
407
        shutdown(sock, SHUT_RDWR);
408
        LIBSSH2_SOCKET_CLOSE(sock);
409
        return -1;
410
    }
411

412
    memset(&w_size, 0, sizeof(struct winsize));
413
    memset(&w_size_bck, 0, sizeof(struct winsize));
414

415
    for(;;) {
416

417
        FD_ZERO(&set);
418
#if defined(__GNUC__)
419
#pragma GCC diagnostic push
420
#pragma GCC diagnostic ignored "-Wsign-conversion"
421
#endif
422
        FD_SET(fileno(stdin), &set);
423
#if defined(__GNUC__)
424
#pragma GCC diagnostic pop
425
#endif
426

427
        /* Search if a resize pty has to be send */
428
        ioctl(fileno(stdin), TIOCGWINSZ, &w_size);
429
        if((w_size.ws_row != w_size_bck.ws_row) ||
430
           (w_size.ws_col != w_size_bck.ws_col)) {
431
            w_size_bck = w_size;
432

433
            libssh2_channel_request_pty_size(channel,
434
                                             w_size.ws_col,
435
                                             w_size.ws_row);
436
        }
437

438
        buf = calloc(bufsiz, sizeof(char));
439
        if(!buf)
440
            break;
441

442
        fds = malloc(sizeof(LIBSSH2_POLLFD));
443
        if(!fds) {
444
            free(buf);
445
            break;
446
        }
447

448
        fds[0].type = LIBSSH2_POLLFD_CHANNEL;
449
        fds[0].fd.channel = channel;
450
        fds[0].events = LIBSSH2_POLLFD_POLLIN;
451
        fds[0].revents = LIBSSH2_POLLFD_POLLIN;
452

453
        rc = libssh2_poll(fds, nfds, 0);
454
        if(rc > 0) {
455
            libssh2_channel_read(channel, buf, sizeof(buf));
456
            fprintf(stdout, "%s", buf);
457
            fflush(stdout);
458
        }
459

460
        /* Looping on X clients */
461
        if(gp_x11_chan) {
462
            current_node = gp_x11_chan;
463
        }
464
        else
465
            current_node = NULL;
466

467
        while(current_node) {
468
            struct chan_X11_list *next_node;
469
            rc = x11_send_receive(current_node->chan, current_node->sock);
470
            next_node = current_node->next;
471
            if(rc == -1) {
472
                shutdown(current_node->sock, SHUT_RDWR);
473
                LIBSSH2_SOCKET_CLOSE(current_node->sock);
474
                remove_node(current_node);
475
            }
476

477
            current_node = next_node;
478
        }
479

480
        rc = select((int)(fileno(stdin) + 1), &set, NULL, NULL, &timeval_out);
481
        if(rc > 0) {
482
            ssize_t nread;
483

484
            /* Data in stdin */
485
            nread = read(fileno(stdin), buf, 1);
486
            if(nread > 0)
487
                libssh2_channel_write(channel, buf, sizeof(buf));
488
        }
489

490
        free(fds);
491
        free(buf);
492

493
        if(libssh2_channel_eof(channel) == 1) {
494
            break;
495
        }
496
    }
497

498
    if(channel) {
499
        libssh2_channel_free(channel);
500
        channel = NULL;
501
    }
502
    _normal_mode();
503

504
    libssh2_exit();
505

506
    return 0;
507
}
508

509
#else
510

511
int main(void)
512
{
513
    fprintf(stderr, "Sorry, this platform is not supported.");
514
    return 1;
515
}
516

517
#endif /* HAVE_SYS_UN_H */
518

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

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

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

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