libssh2

Форк
0
/
ssh2.c 
364 строки · 11.0 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * Sample showing how to do SSH2 connect.
4
 *
5
 * The sample code has default values for host name, user name, password
6
 * and path to copy, but you can specify them on the command line like:
7
 *
8
 * $ ./ssh2 hostip user password [[-p|-i|-k] [command]]
9
 *
10
 *  -p authenticate using password
11
 *  -i authenticate using keyboard-interactive
12
 *  -k authenticate using public key (password argument decrypts keyfile)
13
 *  command executes on the remote machine
14
 *
15
 * SPDX-License-Identifier: BSD-3-Clause
16
 */
17

18
#include "libssh2_setup.h"
19
#include <libssh2.h>
20

21
#ifdef HAVE_SYS_SOCKET_H
22
#include <sys/socket.h>
23
#endif
24
#ifdef HAVE_UNISTD_H
25
#include <unistd.h>
26
#endif
27
#ifdef HAVE_NETINET_IN_H
28
#include <netinet/in.h>
29
#endif
30
#ifdef HAVE_ARPA_INET_H
31
#include <arpa/inet.h>
32
#endif
33

34
#include <stdio.h>
35
#include <stdlib.h>
36
#include <string.h>
37

38
static const char *pubkey = ".ssh/id_rsa.pub";
39
static const char *privkey = ".ssh/id_rsa";
40
static const char *username = "username";
41
static const char *password = "password";
42

43
static void kbd_callback(const char *name, int name_len,
44
                         const char *instruction, int instruction_len,
45
                         int num_prompts,
46
                         const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts,
47
                         LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses,
48
                         void **abstract)
49
{
50
    (void)name;
51
    (void)name_len;
52
    (void)instruction;
53
    (void)instruction_len;
54
    if(num_prompts == 1) {
55
        responses[0].text = strdup(password);
56
        responses[0].length = (unsigned int)strlen(password);
57
    }
58
    (void)prompts;
59
    (void)abstract;
60
}
61

62
int main(int argc, char *argv[])
63
{
64
    uint32_t hostaddr;
65
    libssh2_socket_t sock;
66
    int i, auth_pw = 0;
67
    struct sockaddr_in sin;
68
    const char *fingerprint;
69
    char *userauthlist;
70
    int rc;
71
    LIBSSH2_SESSION *session = NULL;
72
    LIBSSH2_CHANNEL *channel;
73

74
#ifdef _WIN32
75
    WSADATA wsadata;
76

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

84
    if(argc > 1) {
85
        hostaddr = inet_addr(argv[1]);
86
    }
87
    else {
88
        hostaddr = htonl(0x7F000001);
89
    }
90
    if(argc > 2) {
91
        username = argv[2];
92
    }
93
    if(argc > 3) {
94
        password = argv[3];
95
    }
96

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

103
    /* Ultra basic "connect to port 22 on localhost".  Your code is
104
     * responsible for creating the socket establishing the connection
105
     */
106
    sock = socket(AF_INET, SOCK_STREAM, 0);
107
    if(sock == LIBSSH2_INVALID_SOCKET) {
108
        fprintf(stderr, "failed to create socket.\n");
109
        rc = 1;
110
        goto shutdown;
111
    }
112

113
    sin.sin_family = AF_INET;
114
    sin.sin_port = htons(22);
115
    sin.sin_addr.s_addr = hostaddr;
116

117
    fprintf(stderr, "Connecting to %s:%d as user %s\n",
118
            inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), username);
119

120
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
121
        fprintf(stderr, "failed to connect.\n");
122
        goto shutdown;
123
    }
124

125
    /* Create a session instance and start it up. This will trade welcome
126
     * banners, exchange keys, and setup crypto, compression, and MAC layers
127
     */
128
    session = libssh2_session_init();
129
    if(!session) {
130
        fprintf(stderr, "Could not initialize SSH session.\n");
131
        goto shutdown;
132
    }
133

134
    /* Enable all debugging when libssh2 was built with debugging enabled */
135
    libssh2_trace(session, ~0);
136

137
    rc = libssh2_session_handshake(session, sock);
138
    if(rc) {
139
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
140
        goto shutdown;
141
    }
142

143
    rc = 1;
144

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

157
    /* check what authentication methods are available */
158
    userauthlist = libssh2_userauth_list(session, username,
159
                                         (unsigned int)strlen(username));
160
    if(userauthlist) {
161
        fprintf(stderr, "Authentication methods: %s\n", userauthlist);
162
        if(strstr(userauthlist, "password")) {
163
            auth_pw |= 1;
164
        }
165
        if(strstr(userauthlist, "keyboard-interactive")) {
166
            auth_pw |= 2;
167
        }
168
        if(strstr(userauthlist, "publickey")) {
169
            auth_pw |= 4;
170
        }
171

172
        /* check for options */
173
        if(argc > 4) {
174
            if((auth_pw & 1) && !strcmp(argv[4], "-p")) {
175
                auth_pw = 1;
176
            }
177
            if((auth_pw & 2) && !strcmp(argv[4], "-i")) {
178
                auth_pw = 2;
179
            }
180
            if((auth_pw & 4) && !strcmp(argv[4], "-k")) {
181
                auth_pw = 4;
182
            }
183
        }
184

185
        if(auth_pw & 1) {
186
            /* We could authenticate via password */
187
            if(libssh2_userauth_password(session, username, password)) {
188
                fprintf(stderr, "Authentication by password failed.\n");
189
                goto shutdown;
190
            }
191
            else {
192
                fprintf(stderr, "Authentication by password succeeded.\n");
193
            }
194
        }
195
        else if(auth_pw & 2) {
196
            /* Or via keyboard-interactive */
197
            if(libssh2_userauth_keyboard_interactive(session, username,
198
                                                     &kbd_callback) ) {
199
                fprintf(stderr,
200
                        "Authentication by keyboard-interactive failed.\n");
201
                goto shutdown;
202
            }
203
            else {
204
                fprintf(stderr,
205
                        "Authentication by keyboard-interactive succeeded.\n");
206
            }
207
        }
208
        else if(auth_pw & 4) {
209
            /* Or by public key */
210
            size_t fn1sz, fn2sz;
211
            char *fn1, *fn2;
212
            char const *h = getenv("HOME");
213
            if(!h || !*h)
214
                h = ".";
215
            fn1sz = strlen(h) + strlen(pubkey) + 2;
216
            fn2sz = strlen(h) + strlen(privkey) + 2;
217
            fn1 = malloc(fn1sz);
218
            fn2 = malloc(fn2sz);
219
            if(!fn1 || !fn2) {
220
                free(fn2);
221
                free(fn1);
222
                fprintf(stderr, "out of memory\n");
223
                goto shutdown;
224
            }
225
            /* Avoid false positives */
226
#if defined(__GNUC__) && __GNUC__ >= 7
227
#pragma GCC diagnostic push
228
#pragma GCC diagnostic warning "-Wformat-truncation=1"
229
#endif
230
            /* Using asprintf() here would be much cleaner,
231
               but less portable */
232
            snprintf(fn1, fn1sz, "%s/%s", h, pubkey);
233
            snprintf(fn2, fn2sz, "%s/%s", h, privkey);
234
#if defined(__GNUC__) && __GNUC__ >= 7
235
#pragma GCC diagnostic pop
236
#endif
237

238
            if(libssh2_userauth_publickey_fromfile(session, username,
239
                                                   fn1, fn2,
240
                                                   password)) {
241
                fprintf(stderr, "Authentication by public key failed.\n");
242
                free(fn2);
243
                free(fn1);
244
                goto shutdown;
245
            }
246
            else {
247
                fprintf(stderr, "Authentication by public key succeeded.\n");
248
            }
249
            free(fn2);
250
            free(fn1);
251
        }
252
        else {
253
            fprintf(stderr, "No supported authentication methods found.\n");
254
            goto shutdown;
255
        }
256
    }
257

258
    /* Request a session channel on which to run a shell */
259
    channel = libssh2_channel_open_session(session);
260
    if(!channel) {
261
        fprintf(stderr, "Unable to open a session\n");
262
        goto shutdown;
263
    }
264

265
    /* Some environment variables may be set,
266
     * It's up to the server which ones it'll allow though
267
     */
268
    libssh2_channel_setenv(channel, "FOO", "bar");
269

270
    /* Request a terminal with 'vanilla' terminal emulation
271
     * See /etc/termcap for more options. This is useful when opening
272
     * an interactive shell.
273
     */
274
    #if 0
275
    if(libssh2_channel_request_pty(channel, "vanilla")) {
276
        fprintf(stderr, "Failed requesting pty\n");
277
    }
278
    #endif
279

280
    if(argc > 5) {
281
        if(libssh2_channel_exec(channel, argv[5])) {
282
            fprintf(stderr, "Unable to request command on channel\n");
283
            goto shutdown;
284
        }
285
        /* Instead of just running a single command with libssh2_channel_exec,
286
         * a shell can be opened on the channel instead, for interactive use.
287
         * You usually want a pty allocated first in that case (see above). */
288
        #if 0
289
        if(libssh2_channel_shell(channel)) {
290
            fprintf(stderr, "Unable to request shell on allocated pty\n");
291
            goto shutdown;
292
        }
293
        #endif
294

295
        /* At this point the shell can be interacted with using
296
         * libssh2_channel_read()
297
         * libssh2_channel_read_stderr()
298
         * libssh2_channel_write()
299
         * libssh2_channel_write_stderr()
300
         *
301
         * Blocking mode may be (en|dis)abled with:
302
         *    libssh2_channel_set_blocking()
303
         * If the server send EOF, libssh2_channel_eof() will return non-0
304
         * To send EOF to the server use: libssh2_channel_send_eof()
305
         * A channel can be closed with: libssh2_channel_close()
306
         * A channel can be freed with: libssh2_channel_free()
307
         */
308

309
        /* Read and display all the data received on stdout (ignoring stderr)
310
         * until the channel closes. This will eventually block if the command
311
         * produces too much data on stderr; the loop must be rewritten to use
312
         * non-blocking mode and include interspersed calls to
313
         * libssh2_channel_read_stderr() to avoid this. See ssh2_echo.c for
314
         * an idea of how such a loop might look.
315
         */
316
        while(!libssh2_channel_eof(channel)) {
317
            char buf[1024];
318
            ssize_t err = libssh2_channel_read(channel, buf, sizeof(buf));
319
            if(err < 0)
320
                fprintf(stderr, "Unable to read response: %ld\n", (long)err);
321
            else {
322
                fwrite(buf, 1, (size_t)err, stdout);
323
            }
324
        }
325
    }
326

327
    rc = libssh2_channel_get_exit_status(channel);
328

329
    if(libssh2_channel_close(channel))
330
        fprintf(stderr, "Unable to close channel\n");
331

332
    if(channel) {
333
        libssh2_channel_free(channel);
334
        channel = NULL;
335
    }
336

337
    /* Other channel types are supported via:
338
     * libssh2_scp_send()
339
     * libssh2_scp_recv2()
340
     * libssh2_channel_direct_tcpip()
341
     */
342

343
shutdown:
344

345
    if(session) {
346
        libssh2_session_disconnect(session, "Normal Shutdown");
347
        libssh2_session_free(session);
348
    }
349

350
    if(sock != LIBSSH2_INVALID_SOCKET) {
351
        shutdown(sock, 2);
352
        LIBSSH2_SOCKET_CLOSE(sock);
353
    }
354

355
    fprintf(stderr, "all done\n");
356

357
    libssh2_exit();
358

359
#ifdef _WIN32
360
    WSACleanup();
361
#endif
362

363
    return rc;
364
}
365

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

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

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

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