libssh2

Форк
0
/
ssh2_agent.c 
253 строки · 6.9 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * Sample showing how to do SSH2 connect using ssh-agent.
4
 *
5
 * The sample code has default values for host name, user name:
6
 *
7
 * $ ./ssh2_agent host user
8
 *
9
 * SPDX-License-Identifier: BSD-3-Clause
10
 */
11

12
#include "libssh2_setup.h"
13
#include <libssh2.h>
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 <string.h>
30

31
static const char *username = "username";
32

33
int main(int argc, char *argv[])
34
{
35
    uint32_t hostaddr;
36
    libssh2_socket_t sock;
37
    int i;
38
    struct sockaddr_in sin;
39
    const char *fingerprint;
40
    char *userauthlist;
41
    int rc;
42
    LIBSSH2_SESSION *session = NULL;
43
    LIBSSH2_CHANNEL *channel;
44
    LIBSSH2_AGENT *agent = NULL;
45
    struct libssh2_agent_publickey *identity, *prev_identity = NULL;
46

47
#ifdef _WIN32
48
    WSADATA wsadata;
49

50
    rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
51
    if(rc) {
52
        fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
53
        return 1;
54
    }
55
#endif
56

57
    if(argc > 1) {
58
        hostaddr = inet_addr(argv[1]);
59
    }
60
    else {
61
        hostaddr = htonl(0x7F000001);
62
    }
63
    if(argc > 2) {
64
        username = argv[2];
65
    }
66

67
    rc = libssh2_init(0);
68
    if(rc) {
69
        fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
70
        return 1;
71
    }
72

73
    /* Ultra basic "connect to port 22 on localhost".  Your code is
74
     * responsible for creating the socket establishing the connection
75
     */
76
    sock = socket(AF_INET, SOCK_STREAM, 0);
77
    if(sock == LIBSSH2_INVALID_SOCKET) {
78
        fprintf(stderr, "failed to create socket.\n");
79
        rc = 1;
80
        goto shutdown;
81
    }
82

83
    sin.sin_family = AF_INET;
84
    sin.sin_port = htons(22);
85
    sin.sin_addr.s_addr = hostaddr;
86
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
87
        fprintf(stderr, "failed to connect.\n");
88
        goto shutdown;
89
    }
90

91
    /* Create a session instance */
92
    session = libssh2_session_init();
93
    if(!session) {
94
        fprintf(stderr, "Could not initialize SSH session.\n");
95
        goto shutdown;
96
    }
97

98
    rc = libssh2_session_handshake(session, sock);
99
    if(rc) {
100
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
101
        goto shutdown;
102
    }
103

104
    /* At this point we have not yet authenticated.  The first thing to do
105
     * is check the hostkey's fingerprint against our known hosts Your app
106
     * may have it hard coded, may go to a file, may present it to the
107
     * user, that's your call
108
     */
109
    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
110
    fprintf(stderr, "Fingerprint: ");
111
    for(i = 0; i < 20; i++) {
112
        fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
113
    }
114
    fprintf(stderr, "\n");
115

116
    /* check what authentication methods are available */
117
    userauthlist = libssh2_userauth_list(session, username,
118
                                         (unsigned int)strlen(username));
119
    if(userauthlist) {
120
        fprintf(stderr, "Authentication methods: %s\n", userauthlist);
121
        if(!strstr(userauthlist, "publickey")) {
122
            fprintf(stderr, "'publickey' authentication is not supported\n");
123
            goto shutdown;
124
        }
125

126
        /* Connect to the ssh-agent */
127
        agent = libssh2_agent_init(session);
128
        if(!agent) {
129
            fprintf(stderr, "Failure initializing ssh-agent support\n");
130
            rc = 1;
131
            goto shutdown;
132
        }
133
        if(libssh2_agent_connect(agent)) {
134
            fprintf(stderr, "Failure connecting to ssh-agent\n");
135
            rc = 1;
136
            goto shutdown;
137
        }
138
        if(libssh2_agent_list_identities(agent)) {
139
            fprintf(stderr, "Failure requesting identities to ssh-agent\n");
140
            rc = 1;
141
            goto shutdown;
142
        }
143
        for(;;) {
144
            rc = libssh2_agent_get_identity(agent, &identity, prev_identity);
145
            if(rc == 1)
146
                break;
147
            if(rc < 0) {
148
                fprintf(stderr,
149
                        "Failure obtaining identity from ssh-agent support\n");
150
                rc = 1;
151
                goto shutdown;
152
            }
153
            if(libssh2_agent_userauth(agent, username, identity)) {
154
                fprintf(stderr, "Authentication with username %s and "
155
                        "public key %s failed.\n",
156
                        username, identity->comment);
157
            }
158
            else {
159
                fprintf(stderr, "Authentication with username %s and "
160
                        "public key %s succeeded.\n",
161
                        username, identity->comment);
162
                break;
163
            }
164
            prev_identity = identity;
165
        }
166
        if(rc) {
167
            fprintf(stderr, "Could not continue authentication\n");
168
            goto shutdown;
169
        }
170
    }
171

172
    /* We're authenticated now. */
173

174
    /* Request a shell */
175
    channel = libssh2_channel_open_session(session);
176
    if(!channel) {
177
        fprintf(stderr, "Unable to open a session\n");
178
        goto shutdown;
179
    }
180

181
    /* Some environment variables may be set,
182
     * It's up to the server which ones it'll allow though
183
     */
184
    libssh2_channel_setenv(channel, "FOO", "bar");
185

186
    /* Request a terminal with 'vanilla' terminal emulation
187
     * See /etc/termcap for more options. This is useful when opening
188
     * an interactive shell.
189
     */
190
    if(libssh2_channel_request_pty(channel, "vanilla")) {
191
        fprintf(stderr, "Failed requesting pty\n");
192
        goto skip_shell;
193
    }
194

195
    /* Open a SHELL on that pty */
196
    if(libssh2_channel_shell(channel)) {
197
        fprintf(stderr, "Unable to request shell on allocated pty\n");
198
        goto shutdown;
199
    }
200

201
    /* At this point the shell can be interacted with using
202
     * libssh2_channel_read()
203
     * libssh2_channel_read_stderr()
204
     * libssh2_channel_write()
205
     * libssh2_channel_write_stderr()
206
     *
207
     * Blocking mode may be (en|dis)abled with: libssh2_channel_set_blocking()
208
     * If the server send EOF, libssh2_channel_eof() will return non-0
209
     * To send EOF to the server use: libssh2_channel_send_eof()
210
     * A channel can be closed with: libssh2_channel_close()
211
     * A channel can be freed with: libssh2_channel_free()
212
     */
213

214
skip_shell:
215

216
    if(channel) {
217
        libssh2_channel_free(channel);
218
        channel = NULL;
219
    }
220

221
    /* Other channel types are supported via:
222
     * libssh2_scp_send()
223
     * libssh2_scp_recv2()
224
     * libssh2_channel_direct_tcpip()
225
     */
226

227
shutdown:
228

229
    if(agent) {
230
        libssh2_agent_disconnect(agent);
231
        libssh2_agent_free(agent);
232
    }
233

234
    if(session) {
235
        libssh2_session_disconnect(session, "Normal Shutdown");
236
        libssh2_session_free(session);
237
    }
238

239
    if(sock != LIBSSH2_INVALID_SOCKET) {
240
        shutdown(sock, 2);
241
        LIBSSH2_SOCKET_CLOSE(sock);
242
    }
243

244
    fprintf(stderr, "all done\n");
245

246
    libssh2_exit();
247

248
#ifdef _WIN32
249
    WSACleanup();
250
#endif
251

252
    return rc;
253
}
254

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

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

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

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