int SSH2Utils::connect(const char *hostname, const char *username, const char *password) { unsigned long hostaddr; int rc, sock, auth_pw = 0; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; _password = password; hostaddr = inet_addr(hostname); /* Ultra basic "connect to port 22 on localhost". Your code is * responsible for creating the socket establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (::connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); m_errCode = 2; return -1; } /* Create a session instance */ session = libssh2_session_init(); if (!session) { m_errCode = 3; return -1; } /* tell libssh2 we want it all done non-blocking */ //libssh2_session_set_blocking(session, 0); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_startup(session, sock)) == LIBSSH2_ERROR_EAGAIN) ; if (rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); m_errCode = 4; return -1; } /* At this point we havn't authenticated. The first thing to do is check * the hostkey's fingerprint against our known hosts Your app may have it * hard coded, may go to a file, may present it to the user, that's your * call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); printf("Fingerprint: "); for(int i = 0; i < 20; i++) { printf("%02X ", (unsigned char)fingerprint[i]); } printf("\n"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); printf("Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "password") != NULL) { auth_pw |= 1; } if (strstr(userauthlist, "keyboard-interactive") != NULL) { auth_pw |= 2; } if (strstr(userauthlist, "publickey") != NULL) { auth_pw |= 4; } if (auth_pw & 1) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { printf("\tAuthentication by password failed!\n"); m_errCode = 5; goto shutdown; } else { printf("\tAuthentication by password succeeded.\n"); } } else if (auth_pw & 2) { /* Or via keyboard-interactive */ if (libssh2_userauth_keyboard_interactive(session, username, &SSH2Utils::kbd_callback) ) { printf("\tAuthentication by keyboard-interactive failed!\n"); m_errCode = 6; goto shutdown; } else { printf("\tAuthentication by keyboard-interactive succeeded.\n"); } } else if (auth_pw & 4) { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { printf("\tAuthentication by public key failed!\n"); m_errCode = 7; goto shutdown; } else { printf("\tAuthentication by public key succeeded.\n"); } } else { printf("No supported authentication methods found!\n"); m_errCode = 8; goto shutdown; } m_sock = sock; m_session = session; return 0; shutdown: return -1; deconnect(); }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 0, port=22; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; int rc; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; if (!strcmp(argv[1],"--help")) usage(); if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { port=atoi(argv[2]); } if(argc > 3) { username = argv[3]; } if(argc > 4) { password = argv[4]; } if(argc > 5) { sftppath = argv[5]; } if(argc > 6) { localpath = argv[6]; } sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } session = libssh2_session_init(); if(!session) return -1; libssh2_session_set_blocking(session, 1); rc = libssh2_session_startup(session, sock); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); userauthlist = libssh2_userauth_list(session, username, strlen(username)); if (strstr(userauthlist, "password") != NULL) { auth_pw |= 1; } if (strstr(userauthlist, "keyboard-interactive") != NULL) { auth_pw |= 2; } if (strstr(userauthlist, "publickey") != NULL) { auth_pw |= 4; } /* if we got an 4. argument we set this option if supported */ if(argc > 5) { if ((auth_pw & 1) && !strcasecmp(argv[5], "-p")) { auth_pw = 1; } if ((auth_pw & 2) && !strcasecmp(argv[5], "-i")) { auth_pw = 2; } if ((auth_pw & 4) && !strcasecmp(argv[5], "-k")) { auth_pw = 4; } } if (auth_pw & 1) { if (libssh2_userauth_password(session, username, password)) { return 1; goto shutdown; } } else if (auth_pw & 2) { if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) ) { return 1; goto shutdown; } } else if (auth_pw & 4) { if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { printf("\tAuthentication by public key failed!\n"); return 1; goto shutdown; } } else { printf("No supported authentication methods found!\n"); return 1; goto shutdown; } sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); return 1; goto shutdown; } sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); if (!sftp_handle) { return 2; goto shutdown; } FILE *fp=fopen(localpath,"w"); if (fp) { char mem[1024]; do { rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem)); if (rc > 0) { fwrite(mem,rc,1,fp); } else { break; } } while (1); fclose(fp); } libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel; const char *username="******"; const char *password="******"; const char *loclfile="scp_write.c"; const char *scppath="/tmp/TEST"; FILE *local; int rc; #if defined(HAVE_IOCTLSOCKET) long flag = 1; #endif char mem[1024]; size_t nread; char *ptr; struct stat fileinfo; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if(argc > 4) { loclfile = argv[4]; } if (argc > 5) { scppath = argv[5]; } local = fopen(loclfile, "rb"); if (!local) { fprintf(stderr, "Can't local file %s\n", loclfile); goto shutdown; } stat(loclfile, &fileinfo); /* Ultra basic "connect to port 22 on localhost" * Your code is responsible for creating the socket establishing the * connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* We set the socket non-blocking. We do it after the connect just to simplify the example code. */ #ifdef F_SETFL /* FIXME: this can/should be done in a more portable manner */ rc = fcntl(sock, F_GETFL, 0); fcntl(sock, F_SETFL, rc | O_NONBLOCK); #elif defined(HAVE_IOCTLSOCKET) ioctlsocket(sock, FIONBIO, &flag); #else #ifdef WIN32 u_long mode = 1; ioctlsocket (sock, FIONBIO, &mode); #else #error "add support for setting the socket non-blocking here" #endif #endif /* Create a session instance */ session = libssh2_session_init(); if(!session) return -1; /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_startup(session, sock)) == LIBSSH2_ERROR_EAGAIN); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 16; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); if (auth_pw) { /* We could authenticate via password */ while ((rc = libssh2_userauth_password(session, username, password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ while ((rc = libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } /* Request a file via SCP */ do { channel = libssh2_scp_send(session, scppath, 0x1FF & fileinfo.st_mode, (unsigned long)fileinfo.st_size); if ((!channel) && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { char *err_msg; libssh2_session_last_error(session, &err_msg, NULL, 0); fprintf(stderr, "%s\n", err_msg); goto shutdown; } } while (!channel); fprintf(stderr, "SCP session waiting to send file\n"); do { nread = fread(mem, 1, sizeof(mem), local); if (nread <= 0) { /* end of file */ break; } ptr = mem; do { /* write data in a loop until we block */ while ((rc = libssh2_channel_write(channel, ptr, nread)) == LIBSSH2_ERROR_EAGAIN); if (rc < 0) { fprintf(stderr, "ERROR %d\n", rc); } ptr += rc; nread -= rc; } while (nread > 0); } while (1); fprintf(stderr, "Sending EOF\n"); while (libssh2_channel_send_eof(channel) == LIBSSH2_ERROR_EAGAIN); fprintf(stderr, "Waiting for EOF\n"); while (libssh2_channel_wait_eof(channel) == LIBSSH2_ERROR_EAGAIN); fprintf(stderr, "Waiting for channel to close\n"); while (libssh2_channel_wait_closed(channel) == LIBSSH2_ERROR_EAGAIN); libssh2_channel_free(channel); channel = NULL; shutdown: while ((rc = libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing")) == LIBSSH2_ERROR_EAGAIN); libssh2_session_free(session); #ifdef WIN32 Sleep(1000); closesocket(sock); #else sleep(1); close(sock); #endif fprintf(stderr, "all done\n"); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *sftppath="/tmp/TEST"; struct timeval start; struct timeval end; int rc; int total = 0; long time_ms; int spin = 0; #if defined(HAVE_IOCTLSOCKET) long flag = 1; #endif LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { sftppath = argv[4]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if (!session) return -1; /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); gettimeofday(&start, NULL); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_startup(session, sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); if (auth_pw) { /* We could authenticate via password */ while ((rc = libssh2_userauth_password(session, username, password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ while ((rc = libssh2_userauth_publickey_fromfile(session, username, "/home/username/" ".ssh/id_rsa.pub", "/home/username/" ".ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } #if 0 libssh2_trace(session, LIBSSH2_TRACE_CONN); #endif fprintf(stderr, "libssh2_sftp_init()!\n"); do { sftp_session = libssh2_sftp_init(session); if(!sftp_session) { if(libssh2_session_last_errno(session) == LIBSSH2_ERROR_EAGAIN) { fprintf(stderr, "non-blocking init\n"); waitsocket(sock, session); /* now we wait */ } else { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } } } while (!sftp_session); fprintf(stderr, "libssh2_sftp_open()!\n"); /* Request a file via SFTP */ do { sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); if (!sftp_handle) { if (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } else { fprintf(stderr, "non-blocking open\n"); waitsocket(sock, session); /* now we wait */ } } } while (!sftp_handle); fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n"); do { char mem[1024*24]; /* loop until we fail */ while ((rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem))) == LIBSSH2_ERROR_EAGAIN) { spin++; waitsocket(sock, session); /* now we wait */ } if (rc > 0) { total += rc; write(1, mem, rc); } else { break; } } while (1); gettimeofday(&end, NULL); time_ms = tvdiff(end, start); printf("Got %d bytes in %ld ms = %.1f bytes/sec spin: %d\n", total, time_ms, total/(time_ms/1000.0), spin ); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: printf("libssh2_session_disconnect\n"); while (libssh2_session_disconnect(session, "Normal Shutdown, Thank you") == LIBSSH2_ERROR_EAGAIN); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 0; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif const char *pubkeyfile="etc/user.pub"; const char *privkeyfile="etc/user"; const char *username="******"; const char *password="******"; int ec = 1; (void)argc; (void)argv; if (getenv ("USER")) username = getenv ("USER"); if (getenv ("PRIVKEY")) privkeyfile = getenv ("PRIVKEY"); if (getenv ("PRIVKEY")) pubkeyfile = getenv ("PUBKEY"); hostaddr = htonl(0x7F000001); sock = socket(AF_INET, SOCK_STREAM, 0); #ifndef WIN32 fcntl(sock, F_SETFL, 0); #endif sin.sin_family = AF_INET; sin.sin_port = htons(4711); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance and start it up * This will trade welcome banners, exchange keys, and setup crypto, compression, and MAC layers */ session = libssh2_session_init(); if (libssh2_session_startup(session, sock)) { fprintf(stderr, "Failure establishing SSH session\n"); return -1; } /* At this point we havn't authenticated, * The first thing to do is check the hostkey's fingerprint against our known hosts * Your app may have it hard coded, may go to a file, may present it to the user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); printf("Fingerprint: "); for(i = 0; i < 16; i++) { printf("%02X ", (unsigned char)fingerprint[i]); } printf("\n"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); printf("Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "password") != NULL) { auth_pw |= 1; } if (strstr(userauthlist, "keyboard-interactive") != NULL) { auth_pw |= 2; } if (strstr(userauthlist, "publickey") != NULL) { auth_pw |= 4; } if (auth_pw & 4) { /* Authenticate by public key */ if (libssh2_userauth_publickey_fromfile(session, username, pubkeyfile, privkeyfile, password)) { printf("\tAuthentication by public key failed!\n"); goto shutdown; } else { printf("\tAuthentication by public key succeeded.\n"); } } else { printf("No supported authentication methods found!\n"); goto shutdown; } /* Request a shell */ if (!(channel = libssh2_channel_open_session(session))) { fprintf(stderr, "Unable to open a session\n"); goto shutdown; } /* Some environment variables may be set, * It's up to the server which ones it'll allow though */ libssh2_channel_setenv(channel, "FOO", "bar"); /* Request a terminal with 'vanilla' terminal emulation * See /etc/termcap for more options */ if (libssh2_channel_request_pty(channel, "vanilla")) { fprintf(stderr, "Failed requesting pty\n"); goto skip_shell; } /* Open a SHELL on that pty */ if (libssh2_channel_shell(channel)) { fprintf(stderr, "Unable to request shell on allocated pty\n"); goto shutdown; } ec = 0; skip_shell: if (channel) { libssh2_channel_free(channel); channel = NULL; } shutdown: libssh2_session_disconnect(session, "Normal Shutdown"); libssh2_session_free(session); #ifdef WIN32 Sleep(1000); closesocket(sock); #else sleep(1); close(sock); #endif return ec; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *sftppath="/tmp/sftp_mkdir_nonblock"; int rc; #if defined(HAVE_IOCTLSOCKET) long flag = 1; #endif LIBSSH2_SFTP *sftp_session; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if(argc > 2) { username = argv[2]; } if(argc > 3) { password = argv[3]; } if(argc > 4) { sftppath = argv[4]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) return -1; /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_startup(session, sock); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); printf("Fingerprint: "); for(i = 0; i < 20; i++) { printf("%02X ", (unsigned char)fingerprint[i]); } printf("\n"); if (auth_pw) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { printf("Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) { printf("\tAuthentication by public key failed\n"); goto shutdown; } } fprintf(stderr, "libssh2_sftp_init()!\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); fprintf(stderr, "libssh2_sftp_mkdirnb()!\n"); /* Make a directory via SFTP */ while (libssh2_sftp_mkdir(sftp_session, sftppath, LIBSSH2_SFTP_S_IRWXU| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IXGRP| LIBSSH2_SFTP_S_IROTH|LIBSSH2_SFTP_S_IXOTH) == LIBSSH2_ERROR_EAGAIN); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif printf("all done\n"); libssh2_exit(); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int rc, sock, i, auth_pw = 0; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if(argc > 2) { username = argv[2]; } if(argc > 3) { password = argv[3]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* Ultra basic "connect to port 22 on localhost". Your code is * responsible for creating the socket establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance and start it up. This will trade welcome * banners, exchange keys, and setup crypto, compression, and MAC layers */ session = libssh2_session_init(); if (libssh2_session_startup(session, sock)) { fprintf(stderr, "Failure establishing SSH session\n"); return -1; } /* At this point we havn't authenticated. The first thing to do is check * the hostkey's fingerprint against our known hosts Your app may have it * hard coded, may go to a file, may present it to the user, that's your * call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); printf("Fingerprint: "); for(i = 0; i < 20; i++) { printf("%02X ", (unsigned char)fingerprint[i]); } printf("\n"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); printf("Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "password") != NULL) { auth_pw |= 1; } if (strstr(userauthlist, "keyboard-interactive") != NULL) { auth_pw |= 2; } if (strstr(userauthlist, "publickey") != NULL) { auth_pw |= 4; } /* if we got an 4. argument we set this option if supported */ if(argc > 4) { if ((auth_pw & 1) && !strcasecmp(argv[4], "-p")) { auth_pw = 1; } if ((auth_pw & 2) && !strcasecmp(argv[4], "-i")) { auth_pw = 2; } if ((auth_pw & 4) && !strcasecmp(argv[4], "-k")) { auth_pw = 4; } } if (auth_pw & 1) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { printf("\tAuthentication by password failed!\n"); goto shutdown; } else { printf("\tAuthentication by password succeeded.\n"); } } else if (auth_pw & 2) { /* Or via keyboard-interactive */ if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) ) { printf("\tAuthentication by keyboard-interactive failed!\n"); goto shutdown; } else { printf("\tAuthentication by keyboard-interactive succeeded.\n"); } } else if (auth_pw & 4) { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { printf("\tAuthentication by public key failed!\n"); goto shutdown; } else { printf("\tAuthentication by public key succeeded.\n"); } } else { printf("No supported authentication methods found!\n"); goto shutdown; } /* Request a shell */ if (!(channel = libssh2_channel_open_session(session))) { fprintf(stderr, "Unable to open a session\n"); goto shutdown; } /* Some environment variables may be set, * It's up to the server which ones it'll allow though */ libssh2_channel_setenv(channel, "FOO", "bar"); /* Request a terminal with 'vanilla' terminal emulation * See /etc/termcap for more options */ if (libssh2_channel_request_pty(channel, "vanilla")) { fprintf(stderr, "Failed requesting pty\n"); goto skip_shell; } /* Open a SHELL on that pty */ if (libssh2_channel_shell(channel)) { fprintf(stderr, "Unable to request shell on allocated pty\n"); goto shutdown; } /* At this point the shell can be interacted with using * libssh2_channel_read() * libssh2_channel_read_stderr() * libssh2_channel_write() * libssh2_channel_write_stderr() * * Blocking mode may be (en|dis)abled with: libssh2_channel_set_blocking() * If the server send EOF, libssh2_channel_eof() will return non-0 * To send EOF to the server use: libssh2_channel_send_eof() * A channel can be closed with: libssh2_channel_close() * A channel can be freed with: libssh2_channel_free() */ skip_shell: if (channel) { libssh2_channel_free(channel); channel = NULL; } /* Other channel types are supported via: * libssh2_scp_send() * libssh2_scp_recv() * libssh2_channel_direct_tcpip() */ shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif printf("all done!\n"); libssh2_exit(); return 0; }
/* * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to * do protocol-specific actions at connect-time. */ CURLcode Curl_ssh_connect(struct connectdata *conn, bool *done) { int i; struct SSHPROTO *ssh; const char *fingerprint; const char *authlist; char *home; char rsa_pub[PATH_MAX]; char rsa[PATH_MAX]; char tempHome[PATH_MAX]; curl_socket_t sock; char *real_path; char *working_path; int working_path_len; bool authed = FALSE; CURLcode result; struct SessionHandle *data = conn->data; rsa_pub[0] = rsa[0] = '\0'; result = ssh_init(conn); if (result) return result; ssh = data->reqdata.proto.ssh; working_path = curl_easy_unescape(data, data->reqdata.path, 0, &working_path_len); if (!working_path) return CURLE_OUT_OF_MEMORY; #ifdef CURL_LIBSSH2_DEBUG if (ssh->user) { infof(data, "User: %s\n", ssh->user); } if (ssh->passwd) { infof(data, "Password: %s\n", ssh->passwd); } #endif /* CURL_LIBSSH2_DEBUG */ sock = conn->sock[FIRSTSOCKET]; ssh->ssh_session = libssh2_session_init_ex(libssh2_malloc, libssh2_free, libssh2_realloc, ssh); if (ssh->ssh_session == NULL) { failf(data, "Failure initialising ssh session\n"); Curl_safefree(ssh->path); return CURLE_FAILED_INIT; } #ifdef CURL_LIBSSH2_DEBUG infof(data, "SSH socket: %d\n", sock); #endif /* CURL_LIBSSH2_DEBUG */ if (libssh2_session_startup(ssh->ssh_session, sock)) { failf(data, "Failure establishing ssh session\n"); libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; Curl_safefree(ssh->path); return CURLE_FAILED_INIT; } /* * Before we authenticate we should check the hostkey's fingerprint against * our known hosts. How that is handled (reading from file, whatever) is * up to us. As for know not much is implemented, besides showing how to * get the fingerprint. */ fingerprint = libssh2_hostkey_hash(ssh->ssh_session, LIBSSH2_HOSTKEY_HASH_MD5); #ifdef CURL_LIBSSH2_DEBUG /* The fingerprint points to static storage (!), don't free() it. */ infof(data, "Fingerprint: "); for (i = 0; i < 16; i++) { infof(data, "%02X ", (unsigned char) fingerprint[i]); } infof(data, "\n"); #endif /* CURL_LIBSSH2_DEBUG */ /* TBD - methods to check the host keys need to be done */ /* * Figure out authentication methods * NB: As soon as we have provided a username to an openssh server we must * never change it later. Thus, always specify the correct username here, * even though the libssh2 docs kind of indicate that it should be possible * to get a 'generic' list (not user-specific) of authentication methods, * presumably with a blank username. That won't work in my experience. * So always specify it here. */ authlist = libssh2_userauth_list(ssh->ssh_session, ssh->user, strlen(ssh->user)); /* * Check the supported auth types in the order I feel is most secure with the * requested type of authentication */ if ((data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY) && (strstr(authlist, "publickey") != NULL)) { /* To ponder about: should really the lib be messing about with the HOME environment variable etc? */ home = curl_getenv("HOME"); if (data->set.ssh_public_key) snprintf(rsa_pub, sizeof(rsa_pub), "%s", data->set.ssh_public_key); else if (home) snprintf(rsa_pub, sizeof(rsa_pub), "%s/.ssh/id_dsa.pub", home); if (data->set.ssh_private_key) snprintf(rsa, sizeof(rsa), "%s", data->set.ssh_private_key); else if (home) snprintf(rsa, sizeof(rsa), "%s/.ssh/id_dsa", home); curl_free(home); if (rsa_pub[0]) { /* The function below checks if the files exists, no need to stat() here. */ if (libssh2_userauth_publickey_fromfile(ssh->ssh_session, ssh->user, rsa_pub, rsa, "") == 0) { authed = TRUE; } } } if (!authed && (data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD) && (strstr(authlist, "password") != NULL)) { if (!libssh2_userauth_password(ssh->ssh_session, ssh->user, ssh->passwd)) authed = TRUE; } if (!authed && (data->set.ssh_auth_types & CURLSSH_AUTH_HOST) && (strstr(authlist, "hostbased") != NULL)) { } if (!authed && (data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD) && (strstr(authlist, "keyboard-interactive") != NULL)) { /* Authentication failed. Continue with keyboard-interactive now. */ if (libssh2_userauth_keyboard_interactive_ex(ssh->ssh_session, ssh->user, strlen(ssh->user), &kbd_callback) == 0) { authed = TRUE; } } if (!authed) { failf(data, "Authentication failure\n"); libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; Curl_safefree(ssh->path); return CURLE_FAILED_INIT; } /* * At this point we have an authenticated ssh session. */ conn->sockfd = sock; conn->writesockfd = CURL_SOCKET_BAD; if (conn->protocol == PROT_SFTP) { /* * Start the libssh2 sftp session */ ssh->sftp_session = libssh2_sftp_init(ssh->ssh_session); if (ssh->sftp_session == NULL) { failf(data, "Failure initialising sftp session\n"); libssh2_sftp_shutdown(ssh->sftp_session); ssh->sftp_session = NULL; libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; return CURLE_FAILED_INIT; } /* * Get the "home" directory */ i = libssh2_sftp_realpath(ssh->sftp_session, ".", tempHome, PATH_MAX-1); if (i > 0) { /* It seems that this string is not always NULL terminated */ tempHome[i] = '\0'; ssh->homedir = (char *)strdup(tempHome); if (!ssh->homedir) { libssh2_sftp_shutdown(ssh->sftp_session); ssh->sftp_session = NULL; libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; return CURLE_OUT_OF_MEMORY; } } else { /* Return the error type */ i = libssh2_sftp_last_error(ssh->sftp_session); DEBUGF(infof(data, "error = %d\n", i)); } } /* Check for /~/ , indicating realative to the users home directory */ if (conn->protocol == PROT_SCP) { real_path = (char *)malloc(working_path_len+1); if (real_path == NULL) { Curl_safefree(working_path); libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; return CURLE_OUT_OF_MEMORY; } if (working_path[1] == '~') /* It is referenced to the home directory, so strip the leading '/' */ memcpy(real_path, working_path+1, 1 + working_path_len-1); else memcpy(real_path, working_path, 1 + working_path_len); } else if (conn->protocol == PROT_SFTP) { if (working_path[1] == '~') { real_path = (char *)malloc(strlen(ssh->homedir) + working_path_len + 1); if (real_path == NULL) { libssh2_sftp_shutdown(ssh->sftp_session); ssh->sftp_session = NULL; libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; Curl_safefree(working_path); return CURLE_OUT_OF_MEMORY; } /* It is referenced to the home directory, so strip the leading '/' */ memcpy(real_path, ssh->homedir, strlen(ssh->homedir)); real_path[strlen(ssh->homedir)] = '/'; real_path[strlen(ssh->homedir)+1] = '\0'; if (working_path_len > 3) { memcpy(real_path+strlen(ssh->homedir)+1, working_path + 3, 1 + working_path_len -3); } } else { real_path = (char *)malloc(working_path_len+1); if (real_path == NULL) { libssh2_session_free(ssh->ssh_session); ssh->ssh_session = NULL; Curl_safefree(working_path); return CURLE_OUT_OF_MEMORY; } memcpy(real_path, working_path, 1+working_path_len); } } else return CURLE_FAILED_INIT; Curl_safefree(working_path); ssh->path = real_path; *done = TRUE; return CURLE_OK; }
void *Mount( struct FHandler *s, struct TagItem *ti ) { File *dev = NULL; char *path = NULL; char *name = NULL; char *host = NULL; char *ulogin = NULL; char *upass = NULL; int port = 22; User *usr = NULL; if( s == NULL ) { return NULL; } DEBUG("Mounting ssh2 filesystem!\n"); if( ( dev = calloc( sizeof( File ), 1 ) ) != NULL ) { struct TagItem *lptr = ti; // // checking passed arguments while( lptr->ti_Tag != TAG_DONE ) { switch( lptr->ti_Tag ) { case FSys_Mount_Path: path = (char *)lptr->ti_Data; DEBUG("Mount FS path set '%s'\n", path ); break; case FSys_Mount_Host: host = (char *)lptr->ti_Data; break; case FSys_Mount_Port: port = atol( (char *)lptr->ti_Data ); break; case FSys_Mount_Name: name = (char *)lptr->ti_Data; break; case FSys_Mount_User: usr = (User *)lptr->ti_Data; break; case FSys_Mount_LoginUser: ulogin = (char *)lptr->ti_Data; break; case FSys_Mount_LoginPass: upass = (char *)lptr->ti_Data; break; } lptr++; } // if( path == NULL ) { DEBUG("[ERROR]: Path option not found!\n"); free( dev ); return NULL; } init( s ); // we are trying to open folder/connection struct stat st; if( stat( path, &st ) == 0 && S_ISDIR( st.st_mode ) ) { DEBUG("Mounting localfsys, Its directory FSYS: %s!\n", s->GetPrefix() ); dev->f_Path = StringDup( path ); DEBUG("localfs path is ok '%s'\n", dev->f_Path ); dev->f_FSys = s; dev->f_Type = FType_Directory; dev->f_Size = 0; dev->f_Position = 0; dev->f_User = usr; dev->f_Name = StringDup( name ); DEBUG("data filled\n"); } } // // we will hold here special data SSH2 // dev->f_SpecialData = calloc( sizeof(SpecialData), 1 ); SpecialData *sdat = (SpecialData *) dev->f_SpecialData; if( sdat != NULL ) { sdat->sd_Host = StringDup( host ); sdat->sd_Port = port; sdat->sd_LoginUser = StringDup( ulogin ); sdat->sd_LoginPass = StringDup( upass ); sdat->rc = libssh2_init (0); if( sdat->rc != 0 ) { ERROR ( "libssh2 initialization failed (%d)\n", sdat->rc ); return NULL; } // Ultra basic "connect to port 22 on localhost". Your code is //responsible for creating the socket establishing the connection /// sdat->hostaddr = inet_addr( sdat->sd_Host ); sdat->sock = socket( AF_INET, SOCK_STREAM, 0 ); sdat->sin.sin_family = AF_INET; sdat->sin.sin_port = htons( sdat->sd_Port ); sdat->sin.sin_addr.s_addr = sdat->hostaddr; if ( connect( sdat->sock, (struct sockaddr*)( &(sdat->sin) ), sizeof(struct sockaddr_in)) != 0) { ERROR( "failed to connect!\n"); goto shutdown; } // Create a session instance and start it up. This will trade welcome // banners, exchange keys, and setup crypto, compression, and MAC layers // sdat->session = libssh2_session_init( ); if (libssh2_session_handshake( sdat->session, sdat->sock) ) { ERROR("Failure establishing SSH session\n"); goto shutdown; } // At this point we havn't authenticated. The first thing to do is check // the hostkey's fingerprint against our known hosts Your app may have it // hard coded, may go to a file, may present it to the user, that's your // call // sdat->fingerprint = libssh2_hostkey_hash( sdat->session, LIBSSH2_HOSTKEY_HASH_SHA1 ); DEBUG("Fingerprint: "); int i; for(i = 0; i < 20; i++) { DEBUG( "%02X ", (unsigned char)sdat->fingerprint[i]); } DEBUG("\n"); sdat->rc = libssh2_userauth_password( sdat->session, sdat->sd_LoginUser, sdat->sd_LoginPass ); /* if (!(sdat->channel = libssh2_channel_open_session(session))) { ERROR( "Unable to open a session\n"); goto shutdown; }*/ sdat->sftp_session = libssh2_sftp_init( sdat->session ); if (!sdat->sftp_session) { DEBUG("Unable to init SFTP session\n"); goto shutdown; } /* Since we have not set non-blocking, tell libssh2 we are blocking */ libssh2_session_set_blocking( sdat->session, 1); return dev; } DEBUG("localfs mount ok\n"); shutdown: if( sdat != NULL ) { UnMount( s, dev ); } return NULL; }
void sshsocket::socket_connected_slot() { rc = libssh2_init (0); sock = socket->socketDescriptor() ; session = libssh2_session_init(); libssh2_session_set_blocking(session, 0); while ((rc = libssh2_session_startup(session, sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { emit error("Failure establishing SSH session!") ; libssh2_session_free(session); } nh = libssh2_knownhost_init(session); if(!nh) { /* eeek, do cleanup here */ } QString known_host_dir = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "known_hosts" ; libssh2_knownhost_readfile(nh, known_host_dir.toAscii(), LIBSSH2_KNOWNHOST_FILE_OPENSSH); fingerprint = libssh2_session_hostkey(session, &len, &type); if(fingerprint) { #if LIBSSH2_VERSION_NUM >= 0x010206 /* introduced in 1.2.6 */ struct libssh2_knownhost *known_host; int check = libssh2_knownhost_checkp(nh, host->hostname().toAscii(), host->port(), fingerprint, len, LIBSSH2_KNOWNHOST_TYPE_PLAIN| LIBSSH2_KNOWNHOST_KEYENC_RAW, &known_host); #else /* 1.2.5 or older */ int check = libssh2_knownhost_check(nh, host->hostname().toAscii(), fingerprint, len, LIBSSH2_KNOWNHOST_TYPE_PLAIN| LIBSSH2_KNOWNHOST_KEYENC_RAW, &known_host); #endif if (check == LIBSSH2_KNOWNHOST_CHECK_NOTFOUND) { const char *finger = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); QString fingerkey ; fingerkey.append("Server's SHA-1 fingerprint is ") ; int i=0 ; for (i=0; i < 20; i++) { if (i != 19) { QString str ; str.sprintf("%02X:", (unsigned char)finger[i]) ; fingerkey.append(str) ; } else { QString str ; str.sprintf("%02X", (unsigned char)finger[i]) ; fingerkey.append(str) ; } if (i == 10) { fingerkey.append("<br>") ; } } if (mode == 0) { emit accept_fingerprint(fingerkey); } else { emit accept_fingerprint_edit(fingerkey); } setMode(0); } if (check == LIBSSH2_KNOWNHOST_CHECK_MATCH) { if (mode == 0) { emit insertHost(); } else { emit insertHost_edit(); } setMode(0); } } }
netsnmp_transport * netsnmp_ssh_transport(const struct sockaddr_in *addr, int local) { netsnmp_transport *t = NULL; netsnmp_ssh_addr_pair *addr_pair = NULL; int rc = 0; int i, auth_pw = 0; const char *fingerprint; char *userauthlist; struct sockaddr_un *unaddr; const char *sockpath = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SSHTOSNMP_SOCKET); char tmpsockpath[MAXPATHLEN]; #ifdef NETSNMP_NO_LISTEN_SUPPORT if (local) return NULL; #endif /* NETSNMP_NO_LISTEN_SUPPORT */ if (addr == NULL || addr->sin_family != AF_INET) { return NULL; } t = SNMP_MALLOC_TYPEDEF(netsnmp_transport); if (t == NULL) { return NULL; } t->domain = netsnmp_snmpSSHDomain; t->domain_length = netsnmp_snmpSSHDomain_len; t->flags = NETSNMP_TRANSPORT_FLAG_STREAM | NETSNMP_TRANSPORT_FLAG_TUNNELED; addr_pair = SNMP_MALLOC_TYPEDEF(netsnmp_ssh_addr_pair); if (addr_pair == NULL) { netsnmp_transport_free(t); return NULL; } t->data = addr_pair; t->data_length = sizeof(netsnmp_ssh_addr_pair); if (local) { #ifndef NETSNMP_NO_LISTEN_SUPPORT #ifdef SNMPSSHDOMAIN_USE_EXTERNAL_PIPE /* XXX: set t->local and t->local_length */ t->flags |= NETSNMP_TRANSPORT_FLAG_LISTEN; unaddr = &addr_pair->unix_socket_end; /* open a unix domain socket */ /* XXX: get data from the transport def for it's location */ unaddr->sun_family = AF_UNIX; if (NULL == sockpath) { sprintf(tmpsockpath, "%s/%s", get_persistent_directory(), DEFAULT_SOCK_NAME); sockpath = tmpsockpath; } snprintf(unaddr->sun_path, sizeof(unaddr->sun_path), "%s", sockpath); snprintf(addr_pair->socket_path, sizeof(addr_pair->socket_path), "%s", sockpath); t->sock = socket(PF_UNIX, SOCK_STREAM, 0); if (t->sock < 0) { netsnmp_transport_free(t); return NULL; } /* set the SO_PASSCRED option so we can receive the remote uid */ { int one = 1; setsockopt(t->sock, SOL_SOCKET, SO_PASSCRED, (void *) &one, sizeof(one)); } unlink(unaddr->sun_path); rc = bind(t->sock, unaddr, SUN_LEN(unaddr)); if (rc != 0) { DEBUGMSGTL(("netsnmp_ssh_transport", "couldn't bind \"%s\", errno %d (%s)\n", unaddr->sun_path, errno, strerror(errno))); netsnmp_ssh_close(t); netsnmp_transport_free(t); return NULL; } /* set the socket permissions */ { /* * Apply any settings to the ownership/permissions of the * Sshdomain socket */ int sshdomain_sock_perm = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_SSHDOMAIN_SOCK_PERM); int sshdomain_sock_user = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_SSHDOMAIN_SOCK_USER); int sshdomain_sock_group = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_SSHDOMAIN_SOCK_GROUP); DEBUGMSGTL(("ssh", "here: %s, %d, %d, %d\n", unaddr->sun_path, sshdomain_sock_perm, sshdomain_sock_user, sshdomain_sock_group)); if (sshdomain_sock_perm != 0) { DEBUGMSGTL(("ssh", "Setting socket perms to %d\n", sshdomain_sock_perm)); chmod(unaddr->sun_path, sshdomain_sock_perm); } if (sshdomain_sock_user || sshdomain_sock_group) { /* * If either of user or group haven't been set, * then leave them unchanged. */ if (sshdomain_sock_user == 0 ) sshdomain_sock_user = -1; if (sshdomain_sock_group == 0 ) sshdomain_sock_group = -1; DEBUGMSGTL(("ssh", "Setting socket user/group to %d/%d\n", sshdomain_sock_user, sshdomain_sock_group)); chown(unaddr->sun_path, sshdomain_sock_user, sshdomain_sock_group); } } rc = listen(t->sock, NETSNMP_STREAM_QUEUE_LEN); if (rc != 0) { DEBUGMSGTL(("netsnmp_ssh_transport", "couldn't listen to \"%s\", errno %d (%s)\n", unaddr->sun_path, errno, strerror(errno))); netsnmp_ssh_close(t); netsnmp_transport_free(t); return NULL; } #else /* we're called directly by sshd and use stdin/out */ /* for ssh on the server side we've been launched so bind to stdin/out */ /* nothing to do */ /* XXX: verify we're inside ssh */ t->sock = STDIN_FILENO; #endif /* ! SNMPSSHDOMAIN_USE_EXTERNAL_PIPE */ #else /* NETSNMP_NO_LISTEN_SUPPORT */ netsnmp_transport_free(t); return NULL; #endif /* NETSNMP_NO_LISTEN_SUPPORT */ } else { char *username; char *keyfilepub; char *keyfilepriv; /* use the requested user name */ /* XXX: default to the current user name on the system like ssh does */ username = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SSH_USERNAME); if (!username || 0 == *username) { snmp_log(LOG_ERR, "You must specify a ssh username to use. See the snmp.conf manual page\n"); netsnmp_transport_free(t); return NULL; } /* use the requested public key file */ keyfilepub = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SSH_PUBKEY); if (!keyfilepub || 0 == *keyfilepub) { /* XXX: default to ~/.ssh/id_rsa.pub */ snmp_log(LOG_ERR, "You must specify a ssh public key file to use. See the snmp.conf manual page\n"); netsnmp_transport_free(t); return NULL; } /* use the requested private key file */ keyfilepriv = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SSH_PRIVKEY); if (!keyfilepriv || 0 == *keyfilepriv) { /* XXX: default to keyfilepub without the .pub suffix */ snmp_log(LOG_ERR, "You must specify a ssh private key file to use. See the snmp.conf manual page\n"); netsnmp_transport_free(t); return NULL; } /* xxx: need an ipv6 friendly one too (sigh) */ /* XXX: not ideal when structs don't actually match size wise */ memcpy(&(addr_pair->remote_addr), addr, sizeof(struct sockaddr_in)); t->sock = socket(PF_INET, SOCK_STREAM, 0); if (t->sock < 0) { netsnmp_transport_free(t); return NULL; } t->remote_length = sizeof(*addr); t->remote = netsnmp_memdup(addr, sizeof(*addr)); if (!t->remote) { netsnmp_ssh_close(t); netsnmp_transport_free(t); return NULL; } /* * This is a client-type session, so attempt to connect to the far * end. We don't go non-blocking here because it's not obvious what * you'd then do if you tried to do snmp_sends before the connection * had completed. So this can block. */ rc = connect(t->sock, addr, sizeof(struct sockaddr)); if (rc < 0) { netsnmp_ssh_close(t); netsnmp_transport_free(t); return NULL; } /* * Allow user to override the send and receive buffers. Default is * to use os default. Don't worry too much about errors -- * just plough on regardless. */ netsnmp_sock_buffer_set(t->sock, SO_SNDBUF, local, 0); netsnmp_sock_buffer_set(t->sock, SO_RCVBUF, local, 0); /* open the SSH session and channel */ addr_pair->session = libssh2_session_init(); if (libssh2_session_startup(addr_pair->session, t->sock)) { shutdown: snmp_log(LOG_ERR, "Failed to establish an SSH session\n"); netsnmp_ssh_close(t); netsnmp_transport_free(t); return NULL; } /* At this point we havn't authenticated, The first thing to do is check the hostkey's fingerprint against our known hosts Your app may have it hard coded, may go to a file, may present it to the user, that's your call */ fingerprint = libssh2_hostkey_hash(addr_pair->session, LIBSSH2_HOSTKEY_HASH_MD5); DEBUGMSGTL(("ssh", "Fingerprint: ")); for(i = 0; i < 16; i++) { DEBUGMSG(("ssh", "%02x", (unsigned char)fingerprint[i])); } DEBUGMSG(("ssh", "\n")); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(addr_pair->session, username, strlen(username)); DEBUGMSG(("ssh", "Authentication methods: %s\n", userauthlist)); /* XXX: allow other types */ /* XXX: 4 seems magic to me... */ if (strstr(userauthlist, "publickey") != NULL) { auth_pw |= 4; } /* XXX: hard coded paths and users */ if (auth_pw & 4) { /* public key */ if (libssh2_userauth_publickey_fromfile(addr_pair->session, username, keyfilepub, keyfilepriv, NULL)) { snmp_log(LOG_ERR,"Authentication by public key failed!\n"); goto shutdown; } else { DEBUGMSG(("ssh", "\tAuthentication by public key succeeded.\n")); } } else { snmp_log(LOG_ERR,"Authentication by public key failed!\n"); goto shutdown; } /* we've now authenticated both sides; contining onward ... */ /* Request a channel */ if (!(addr_pair->channel = libssh2_channel_open_session(addr_pair->session))) { snmp_log(LOG_ERR, "Unable to open a session\n"); goto shutdown; } /* Request a terminal with 'vanilla' terminal emulation * See /etc/termcap for more options */ /* XXX: needed? doubt it */ /* if (libssh2_channel_request_pty(addr_pair->channel, "vanilla")) { */ /* snmp_log(LOG_ERR, "Failed requesting pty\n"); */ /* goto shutdown; */ /* } */ if (libssh2_channel_subsystem(addr_pair->channel, "snmp")) { snmp_log(LOG_ERR, "Failed to request the ssh 'snmp' subsystem\n"); goto shutdown; } } DEBUGMSG(("ssh","Opened connection.\n")); /* * Message size is not limited by this transport (hence msgMaxSize * is equal to the maximum legal size of an SNMP message). */ t->msgMaxSize = SNMP_MAX_PACKET_LEN; t->f_recv = netsnmp_ssh_recv; t->f_send = netsnmp_ssh_send; t->f_close = netsnmp_ssh_close; t->f_accept = netsnmp_ssh_accept; t->f_fmtaddr = netsnmp_ssh_fmtaddr; return t; }
static int ssh2_drive_session(eventer_t e, int mask, void *closure, struct timeval *now) { int i; const char *fingerprint; ssh2_check_info_t *ci = closure; struct timeval diff; int timeout_ms = 10; /* 10ms, gets set below */ if(ci->state == WANT_CLOSE) { noit_check_t *check = ci->check; ssh2_log_results(ci->self, ci->check); ssh2_cleanup(ci->self, ci->check); eventer_remove_fd(e->fd); e->opset->close(e->fd, &mask, e); check->flags &= ~NP_RUNNING; return 0; } switch(mask) { case EVENTER_ASYNCH_WORK: if(eventer_set_fd_blocking(e->fd)) { ci->timed_out = 0; ci->error = strdup("socket error"); return 0; } ci->session = libssh2_session_init(); #define set_method(a,b) do { \ int rv; \ if(ci->methods.a && \ (rv = libssh2_session_method_pref(ci->session, b, ci->methods.a)) != 0) { \ ci->timed_out = 0; \ ci->error = strdup((rv == LIBSSH2_ERROR_METHOD_NOT_SUPPORTED) ? \ #a " method not supported" : "error setting " #a); \ return 0; \ } \ } while(0) set_method(kex, LIBSSH2_METHOD_KEX); set_method(hostkey, LIBSSH2_METHOD_HOSTKEY); set_method(crypt_cs, LIBSSH2_METHOD_CRYPT_CS); set_method(crypt_sc, LIBSSH2_METHOD_CRYPT_SC); set_method(mac_cs, LIBSSH2_METHOD_MAC_CS); set_method(mac_sc, LIBSSH2_METHOD_MAC_SC); set_method(comp_cs, LIBSSH2_METHOD_COMP_CS); set_method(comp_sc, LIBSSH2_METHOD_COMP_SC); if(compare_timeval(*now, e->whence) < 0) { sub_timeval(e->whence, *now, &diff); timeout_ms = diff.tv_sec * 1000 + diff.tv_usec / 1000; } #if LIBSSH2_VERSION_NUM >= 0x010209 libssh2_session_set_timeout(ci->session, timeout_ms); #endif if (libssh2_session_startup(ci->session, e->fd)) { ci->timed_out = 0; ci->error = strdup("ssh session startup failed"); return 0; } fingerprint = libssh2_hostkey_hash(ci->session, LIBSSH2_HOSTKEY_HASH_MD5); for(i=0;i<16;i++) { snprintf(ci->fingerprint + (i*2), 3, "%02x", (unsigned char)fingerprint[i]); } ci->fingerprint[32] = '\0'; ci->timed_out = 0; return 0; break; case EVENTER_ASYNCH_CLEANUP: if(ci->session) { libssh2_session_disconnect(ci->session, "Bye!"); libssh2_session_free(ci->session); ci->session = NULL; } ci->state = WANT_CLOSE; break; default: abort(); } return 0; }
// if there was an error, throw it. if( ec < 0 ) { char* msg; libssh2_session_last_error( m_session, &msg, 0, 0 ); MACE_SSH_THROW( "Handshake error: %1% - %2%", %ec %msg ); } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call * * TODO: validate fingerprint */ const char* fingerprint = libssh2_hostkey_hash(m_session, LIBSSH2_HOSTKEY_HASH_SHA1); // try to authenticate, throw on error. authenticate(); // libssh2_trace(m_session, LIBSSH2_TRACE_TRANS); } catch ( ... ) { self.close(); throw; } } } // namespace detail
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *loclfile="sftp_write.c"; const char *sftppath="/tmp/TEST"; int rc; FILE *local; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; LIBSSH2_SFTP_ATTRIBUTES attrs; char mem[1024*100]; size_t nread; char *ptr; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if(argc > 2) { username = argv[2]; } if(argc > 3) { password = argv[3]; } if(argc > 4) { loclfile = argv[4]; } if(argc > 5) { sftppath = argv[5]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } local = fopen(loclfile, "rb"); if (!local) { printf("Can't local file %s\n", loclfile); return -1; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) return -1; /* Since we have set non-blocking, tell libssh2 we are blocking */ libssh2_session_set_blocking(session, 1); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_startup(session, sock); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); printf("Fingerprint: "); for(i = 0; i < 20; i++) { printf("%02X ", (unsigned char)fingerprint[i]); } printf("\n"); if (auth_pw) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { printf("Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) { printf("\tAuthentication by public key failed\n"); goto shutdown; } } fprintf(stderr, "libssh2_sftp_init()!\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() for READ and WRITE!\n"); /* Request a file via SFTP */ sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_WRITE|LIBSSH2_FXF_READ, LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } if(libssh2_sftp_fstat_ex(sftp_handle, &attrs, 0) < 0) { printf("libssh2_sftp_fstat_ex failed\n"); goto shutdown; } else libssh2_sftp_seek64(sftp_handle, attrs.filesize); printf("Did a seek to position %ld\n", (long) attrs.filesize); fprintf(stderr, "libssh2_sftp_open() a handle for APPEND\n"); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); do { nread = fread(mem, 1, sizeof(mem), local); if (nread <= 0) { /* end of file */ break; } ptr = mem; do { /* write data in a loop until we block */ rc = libssh2_sftp_write(sftp_handle, ptr, nread); if(rc < 0) break; ptr += rc; nread -= rc; } while (nread); } while (rc > 0); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif if (local) fclose(local); printf("all done\n"); libssh2_exit(); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 0; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; int rc; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if(argc > 2) { username = argv[2]; } if(argc > 3) { password = argv[3]; } if(argc > 4) { sftppath = argv[4]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) return -1; /* Since we have set non-blocking, tell libssh2 we are blocking */ libssh2_session_set_blocking(session, 1); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_startup(session, sock); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); printf("Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "password") != NULL) { auth_pw |= 1; } if (strstr(userauthlist, "keyboard-interactive") != NULL) { auth_pw |= 2; } if (strstr(userauthlist, "publickey") != NULL) { auth_pw |= 4; } /* if we got an 4. argument we set this option if supported */ if(argc > 5) { if ((auth_pw & 1) && !strcasecmp(argv[5], "-p")) { auth_pw = 1; } if ((auth_pw & 2) && !strcasecmp(argv[5], "-i")) { auth_pw = 2; } if ((auth_pw & 4) && !strcasecmp(argv[5], "-k")) { auth_pw = 4; } } if (auth_pw & 1) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else if (auth_pw & 2) { /* Or via keyboard-interactive */ if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) ) { printf("\tAuthentication by keyboard-interactive failed!\n"); goto shutdown; } else { printf("\tAuthentication by keyboard-interactive succeeded.\n"); } } else if (auth_pw & 4) { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { printf("\tAuthentication by public key failed!\n"); goto shutdown; } else { printf("\tAuthentication by public key succeeded.\n"); } } else { printf("No supported authentication methods found!\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_init()!\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_open()!\n"); /* Request a file via SFTP */ sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP: %ld\n", libssh2_sftp_last_error(sftp_session)); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n"); do { char mem[1024]; /* loop until we fail */ fprintf(stderr, "libssh2_sftp_read()!\n"); rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem)); if (rc > 0) { write(1, mem, rc); } else { break; } } while (1); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
int main(int argc, char *argv[]) { int rc, i, auth = AUTH_NONE; struct sockaddr_in sin; socklen_t sinlen = sizeof(sin); const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; LIBSSH2_LISTENER *listener = NULL; LIBSSH2_CHANNEL *channel = NULL; fd_set fds; struct timeval tv; ssize_t len, wr; char buf[16384]; #ifdef WIN32 SOCKET sock = INVALID_SOCKET, forwardsock = INVALID_SOCKET; WSADATA wsadata; int err; err = WSAStartup(MAKEWORD(2,0), &wsadata); if (err != 0) { fprintf(stderr, "WSAStartup failed with error: %d\n", err); return 1; } #else int sock = -1, forwardsock = -1; #endif if (argc > 1) server_ip = argv[1]; if (argc > 2) username = argv[2]; if (argc > 3) password = argv[3]; if (argc > 4) remote_listenhost = argv[4]; if (argc > 5) remote_wantport = atoi(argv[5]); if (argc > 6) local_destip = argv[6]; if (argc > 7) local_destport = atoi(argv[7]); rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* Connect to SSH server */ sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); #ifdef WIN32 if (sock == INVALID_SOCKET) { fprintf(stderr, "failed to open socket!\n"); return -1; } #else if (sock == -1) { perror("socket"); return -1; } #endif sin.sin_family = AF_INET; if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(server_ip))) { perror("inet_addr"); return -1; } sin.sin_port = htons(22); if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) { fprintf(stderr, "Could not initialize SSH session!\n"); return -1; } /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(session, sock); if(rc) { fprintf(stderr, "Error when starting up SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); fprintf(stderr, "\n"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); fprintf(stderr, "Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "password")) auth |= AUTH_PASSWORD; if (strstr(userauthlist, "publickey")) auth |= AUTH_PUBLICKEY; /* check for options */ if(argc > 8) { if ((auth & AUTH_PASSWORD) && !strcasecmp(argv[8], "-p")) auth = AUTH_PASSWORD; if ((auth & AUTH_PUBLICKEY) && !strcasecmp(argv[8], "-k")) auth = AUTH_PUBLICKEY; } if (auth & AUTH_PASSWORD) { if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else if (auth & AUTH_PUBLICKEY) { if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { fprintf(stderr, "\tAuthentication by public key failed!\n"); goto shutdown; } fprintf(stderr, "\tAuthentication by public key succeeded.\n"); } else { fprintf(stderr, "No supported authentication methods found!\n"); goto shutdown; } fprintf(stderr, "Asking server to listen on remote %s:%d\n", remote_listenhost, remote_wantport); listener = libssh2_channel_forward_listen_ex(session, remote_listenhost, remote_wantport, &remote_listenport, 1); if (!listener) { fprintf(stderr, "Could not start the tcpip-forward listener!\n" "(Note that this can be a problem at the server!" " Please review the server logs.)\n"); goto shutdown; } fprintf(stderr, "Server is listening on %s:%d\n", remote_listenhost, remote_listenport); fprintf(stderr, "Waiting for remote connection\n"); channel = libssh2_channel_forward_accept(listener); if (!channel) { fprintf(stderr, "Could not accept connection!\n" "(Note that this can be a problem at the server!" " Please review the server logs.)\n"); goto shutdown; } fprintf(stderr, "Accepted remote connection. Connecting to local server %s:%d\n", local_destip, local_destport); forwardsock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); #ifdef WIN32 if (forwardsock == INVALID_SOCKET) { fprintf(stderr, "failed to open forward socket!\n"); goto shutdown; } #else if (forwardsock == -1) { perror("socket"); goto shutdown; } #endif sin.sin_family = AF_INET; sin.sin_port = htons(local_destport); if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(local_destip))) { perror("inet_addr"); goto shutdown; } if (-1 == connect(forwardsock, (struct sockaddr *)&sin, sinlen)) { perror("connect"); goto shutdown; } fprintf(stderr, "Forwarding connection from remote %s:%d to local %s:%d\n", remote_listenhost, remote_listenport, local_destip, local_destport); /* Must use non-blocking IO hereafter due to the current libssh2 API */ libssh2_session_set_blocking(session, 0); while (1) { FD_ZERO(&fds); FD_SET(forwardsock, &fds); tv.tv_sec = 0; tv.tv_usec = 100000; rc = select(forwardsock + 1, &fds, NULL, NULL, &tv); if (-1 == rc) { perror("select"); goto shutdown; } if (rc && FD_ISSET(forwardsock, &fds)) { len = recv(forwardsock, buf, sizeof(buf), 0); if (len < 0) { perror("read"); goto shutdown; } else if (0 == len) { fprintf(stderr, "The local server at %s:%d disconnected!\n", local_destip, local_destport); goto shutdown; } wr = 0; do { i = libssh2_channel_write(channel, buf, len); if (i < 0) { fprintf(stderr, "libssh2_channel_write: %d\n", i); goto shutdown; } wr += i; } while(i > 0 && wr < len); } while (1) { len = libssh2_channel_read(channel, buf, sizeof(buf)); if (LIBSSH2_ERROR_EAGAIN == len) break; else if (len < 0) { fprintf(stderr, "libssh2_channel_read: %d", (int)len); goto shutdown; } wr = 0; while (wr < len) { i = send(forwardsock, buf + wr, len - wr, 0); if (i <= 0) { perror("write"); goto shutdown; } wr += i; } if (libssh2_channel_eof(channel)) { fprintf(stderr, "The remote client at %s:%d disconnected!\n", remote_listenhost, remote_listenport); goto shutdown; } } } shutdown: #ifdef WIN32 closesocket(forwardsock); #else close(forwardsock); #endif if (channel) libssh2_channel_free(channel); if (listener) libssh2_channel_forward_cancel(listener); libssh2_session_disconnect(session, "Client disconnecting normally"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif libssh2_exit(); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *loclfile="sftp_write_nonblock.c"; const char *sftppath="/tmp/sftp_write_nonblock.c"; int rc; FILE *local; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; char mem[1024 * 1000]; size_t nread; size_t memuse; time_t start; long total = 0; int duration; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { loclfile = argv[4]; } if (argc > 5) { sftppath = argv[5]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } local = fopen(loclfile, "rb"); if (!local) { fprintf(stderr, "Can't open local file %s\n", loclfile); return -1; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if (!session) return -1; /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_handshake(session, sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do is * check the hostkey's fingerprint against our known hosts Your app may * have it hard coded, may go to a file, may present it to the user, * that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); if (auth_pw) { /* We could authenticate via password */ while ((rc = libssh2_userauth_password(session, username, password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ while ((rc = libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } fprintf(stderr, "libssh2_sftp_init()!\n"); do { sftp_session = libssh2_sftp_init(session); if (!sftp_session && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } } while (!sftp_session); fprintf(stderr, "libssh2_sftp_open()!\n"); /* Request a file via SFTP */ do { sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC, LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); if (!sftp_handle && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } } while (!sftp_handle); fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); start = time(NULL); memuse = 0; /* it starts blank */ do { nread = fread(&mem[memuse], 1, sizeof(mem)-memuse, local); if (nread <= 0) { /* end of file */ if (memuse > 0) /* the previous sending is not finished */ nread = 0; else break; } memuse += nread; total += nread; /* write data in a loop until we block */ while ((rc = libssh2_sftp_write(sftp_handle, mem, memuse)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, session); } if(rc < 0) break; if(memuse - rc) { /* make room for more data at the end of the buffer */ memmove(&mem[0], &mem[rc], memuse - rc); memuse -= rc; } else /* 'mem' was consumed fully */ memuse = 0; } while (rc > 0); duration = (int)(time(NULL)-start); fprintf(stderr, "%ld bytes in %d seconds makes %.1f bytes/sec\n", total, duration, total/(double)duration); fclose(local); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: while (libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing") == LIBSSH2_ERROR_EAGAIN); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel; const char *username="******"; const char *password="******"; const char *scppath="/tmp/TEST"; libssh2_struct_stat fileinfo; #ifdef HAVE_GETTIMEOFDAY struct timeval start; struct timeval end; long time_ms; #endif int rc; int spin = 0; libssh2_struct_stat_size got = 0; libssh2_struct_stat_size total = 0; #ifdef WIN32 WSADATA wsadata; int err; err = WSAStartup(MAKEWORD(2,0), &wsadata); if (err != 0) { fprintf(stderr, "WSAStartup failed with error: %d\n", err); return 1; } #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { scppath = argv[4]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* Ultra basic "connect to port 22 on localhost" * Your code is responsible for creating the socket establishing the * connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if (!session) return -1; /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); #ifdef HAVE_GETTIMEOFDAY gettimeofday(&start, NULL); #endif /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_handshake(session, sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); if (auth_pw) { /* We could authenticate via password */ while ((rc = libssh2_userauth_password(session, username, password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ while ((rc = libssh2_userauth_publickey_fromfile(session, username, "/home/username/" ".ssh/id_rsa.pub", "/home/username/" ".ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } #if 0 libssh2_trace(session, LIBSSH2_TRACE_CONN); #endif /* Request a file via SCP */ fprintf(stderr, "libssh2_scp_recv2()!\n"); do { channel = libssh2_scp_recv2(session, scppath, &fileinfo); if (!channel) { if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) { char *err_msg; libssh2_session_last_error(session, &err_msg, NULL, 0); fprintf(stderr, "%s\n", err_msg); goto shutdown; } else { fprintf(stderr, "libssh2_scp_recv() spin\n"); waitsocket(sock, session); } } } while (!channel); fprintf(stderr, "libssh2_scp_recv() is done, now receive data!\n"); while(got < fileinfo.st_size) { char mem[1024*24]; int rc; do { int amount=sizeof(mem); if ((fileinfo.st_size -got) < amount) { amount = (int)(fileinfo.st_size - got); } /* loop until we block */ rc = libssh2_channel_read(channel, mem, amount); if (rc > 0) { write(1, mem, rc); got += rc; total += rc; } } while (rc > 0); if ((rc == LIBSSH2_ERROR_EAGAIN) && (got < fileinfo.st_size)) { /* this is due to blocking that would occur otherwise so we loop on this condition */ spin++; waitsocket(sock, session); /* now we wait */ continue; } break; } #ifdef HAVE_GETTIMEOFDAY gettimeofday(&end, NULL); time_ms = tvdiff(end, start); fprintf(stderr, "Got " LIBSSH2_STRUCT_STAT_SIZE_FORMAT " bytes in %ld ms = %.1f bytes/sec spin: %d\n", total, time_ms, total/(time_ms/1000.0), spin); #else fprintf(stderr, "Got " LIBSSH2_STRUCT_STAT_SIZE_FORMAT " bytes spin: %d\n", total, spin); #endif libssh2_channel_free(channel); channel = NULL; shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel; const char *username="******"; const char *password="******"; const char *scppath="/tmp/TEST"; struct stat fileinfo; int rc; off_t got=0; #ifdef WIN32 WSADATA wsadata; WSAStartup(WINSOCK_VERSION, &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { scppath = argv[4]; } /* Ultra basic "connect to port 22 on localhost" * Your code is responsible for creating the socket establishing the * connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* We set the socket non-blocking. We do it after the connect just to simplify the example code. */ #ifdef F_SETFL /* FIXME: this can/should be done in a more portable manner */ rc = fcntl(sock, F_GETFL, 0); fcntl(sock, F_SETFL, rc | O_NONBLOCK); #else #error "add support for setting the socket non-blocking here" #endif /* Create a session instance */ session = libssh2_session_init(); if (!session) return -1; /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_startup(session, sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 16; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); if (auth_pw) { /* We could authenticate via password */ while ((rc = libssh2_userauth_password(session, username, password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ while ((rc = libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } /* Request a file via SCP */ fprintf(stderr, "libssh2_scp_recv()!\n"); do { channel = libssh2_scp_recv(session, scppath, &fileinfo); if ((!channel) && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { char *err_msg; libssh2_session_last_error(session, &err_msg, NULL, 0); fprintf(stderr, "%s\n", err_msg); goto shutdown; } } while (!channel); fprintf(stderr, "libssh2_scp_recv() is done, now receive data!\n"); while(got < fileinfo.st_size) { char mem[1000]; struct timeval timeout; int rc; fd_set fd; do { int amount=sizeof(mem); if ((fileinfo.st_size -got) < amount) { amount = fileinfo.st_size - got; } /* loop until we block */ rc = libssh2_channel_read(channel, mem, amount); if (rc > 0) { write(1, mem, rc); got += rc; } } while (rc > 0); if (rc == LIBSSH2_ERROR_EAGAIN) { /* this is due to blocking that would occur otherwise so we loop on this condition */ timeout.tv_sec = 10; timeout.tv_usec = 0; FD_ZERO(&fd); FD_SET(sock, &fd); rc = select(sock+1, &fd, &fd, NULL, &timeout); if (rc <= 0) { /* negative is error 0 is timeout */ fprintf(stderr, "SCP timed out: %d\n", rc); } continue; } break; } libssh2_channel_free(channel); channel = NULL; shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 Sleep(1000); closesocket(sock); #else sleep(1); close(sock); #endif fprintf(stderr, "all done\n"); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *loclfile="sftp_write_nonblock.c"; const char *sftppath="/tmp/sftp_write_nonblock.c"; int rc; FILE *local; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; char mem[1024]; size_t nread; char *ptr; #ifdef WIN32 WSADATA wsadata; WSAStartup(WINSOCK_VERSION, &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { loclfile = argv[4]; } if (argc > 5) { sftppath = argv[5]; } local = fopen(loclfile, "rb"); if (!local) { printf("Can't local file %s\n", loclfile); goto shutdown; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* We set the socket non-blocking. We do it after the connect just to simplify the example code. */ #ifdef F_SETFL /* FIXME: this can/should be done in a more portable manner */ rc = fcntl(sock, F_GETFL, 0); fcntl(sock, F_SETFL, rc | O_NONBLOCK); #else #error "add support for setting the socket non-blocking here" #endif /* Create a session instance */ session = libssh2_session_init(); if (!session) return -1; /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_startup(session, sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); printf("Fingerprint: "); for(i = 0; i < 16; i++) { printf("%02X ", (unsigned char)fingerprint[i]); } printf("\n"); if (auth_pw) { /* We could authenticate via password */ while ((rc = libssh2_userauth_password(session, username, password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { printf("Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ while ((rc = libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { printf("\tAuthentication by public key failed\n"); goto shutdown; } } fprintf(stderr, "libssh2_sftp_init()!\n"); do { sftp_session = libssh2_sftp_init(session); if ((!sftp_session) && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } } while (!sftp_session); /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); fprintf(stderr, "libssh2_sftp_open()!\n"); /* Request a file via SFTP */ do { sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC, LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); if ((!sftp_handle) && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } } while (!sftp_handle); fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); do { nread = fread(mem, 1, sizeof(mem), local); if (nread <= 0) { /* end of file */ break; } ptr = mem; do { /* write data in a loop until we block */ while ((rc = libssh2_sftp_write(sftp_handle, ptr, nread)) == LIBSSH2_ERROR_EAGAIN) { ; } ptr += rc; nread -= nread; } while (rc > 0); } while (1); fclose(local); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: while ((rc = libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing")) == LIBSSH2_ERROR_EAGAIN); libssh2_session_free(session); #ifdef WIN32 Sleep(1000); closesocket(sock); #else sleep(1); close(sock); #endif printf("all done\n"); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session = NULL; LIBSSH2_CHANNEL *channel; const char *username="******"; const char *password="******"; const char *loclfile="scp_write.c"; const char *scppath="/tmp/TEST"; FILE *local; int rc; char mem[1024]; size_t nread; char *ptr; struct stat fileinfo; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if(argc > 4) { loclfile = argv[4]; } if (argc > 5) { scppath = argv[5]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } local = fopen(loclfile, "rb"); if (!local) { fprintf(stderr, "Can't open local file %s\n", loclfile); return -1; } stat(loclfile, &fileinfo); /* Ultra basic "connect to port 22 on localhost" * Your code is responsible for creating the socket establishing the * connection */ sock = socket(AF_INET, SOCK_STREAM, 0); if(-1 == sock) { fprintf(stderr, "failed to create socket!\n"); return -1; } sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) return -1; /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(session, sock); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); if (auth_pw) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } /* Send a file via scp. The mode parameter must only have permissions! */ channel = libssh2_scp_send(session, scppath, fileinfo.st_mode & 0777, (unsigned long)fileinfo.st_size); if (!channel) { char *errmsg; int errlen; int err = libssh2_session_last_error(session, &errmsg, &errlen, 0); fprintf(stderr, "Unable to open a session: (%d) %s\n", err, errmsg); goto shutdown; } fprintf(stderr, "SCP session waiting to send file\n"); do { nread = fread(mem, 1, sizeof(mem), local); if (nread <= 0) { /* end of file */ break; } ptr = mem; do { /* write the same data over and over, until error or completion */ rc = libssh2_channel_write(channel, ptr, nread); if (rc < 0) { fprintf(stderr, "ERROR %d\n", rc); break; } else { /* rc indicates how many bytes were written this time */ ptr += rc; nread -= rc; } } while (nread); } while (1); fprintf(stderr, "Sending EOF\n"); libssh2_channel_send_eof(channel); fprintf(stderr, "Waiting for EOF\n"); libssh2_channel_wait_eof(channel); fprintf(stderr, "Waiting for channel to close\n"); libssh2_channel_wait_closed(channel); libssh2_channel_free(channel); channel = NULL; shutdown: if(session) { libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); } #ifdef WIN32 closesocket(sock); #else close(sock); #endif if (local) fclose(local); fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *sftppath="/tmp/secretdir"; int rc; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if(argc > 2) { username = argv[2]; } if(argc > 3) { password = argv[3]; } if(argc > 4) { sftppath = argv[4]; } /* * The application code is responsible for creating the socket * and establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) return -1; /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_startup(session, sock); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); printf("Fingerprint: "); for(i = 0; i < 16; i++) { printf("%02X ", (unsigned char)fingerprint[i]); } printf("\n"); if (auth_pw) { /* We could authenticate via password */ if ((i = libssh2_userauth_password(session, username, password))) { printf("Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) { printf("\tAuthentication by public key failed\n"); goto shutdown; } } fprintf(stderr, "libssh2_sftp_init()!\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } /* Since we have not set non-blocking, tell libssh2 we are blocking */ libssh2_session_set_blocking(session, 1); fprintf(stderr, "libssh2_sftp_opendir()!\n"); /* Request a dir listing via SFTP */ sftp_handle = libssh2_sftp_opendir(sftp_session, sftppath); if (!sftp_handle) { fprintf(stderr, "Unable to open dir with SFTP\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_opendir() is done, now receive listing!\n"); do { char mem[512]; char longentry[512]; LIBSSH2_SFTP_ATTRIBUTES attrs; /* loop until we fail */ rc = libssh2_sftp_readdir_ex(sftp_handle, mem, sizeof(mem), longentry, sizeof(longentry), &attrs); if(rc > 0) { /* rc is the length of the file name in the mem buffer */ if (longentry[0] != '\0') { printf("%s\n", longentry); } else { if(attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) { /* this should check what permissions it is and print the output accordingly */ printf("--fix----- "); } else { printf("---------- "); } if(attrs.flags & LIBSSH2_SFTP_ATTR_UIDGID) { printf("%4ld %4ld ", attrs.uid, attrs.gid); } else { printf(" - - "); } if(attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) { /* attrs.filesize is an uint64_t according to the docs but there is no really good and portable 64bit type for C before C99, and correspondingly there was no good printf() option for it... */ printf("%8lld ", attrs.filesize); } printf("%s\n", mem); } } else break; } while (1); libssh2_sftp_closedir(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 Sleep(1000); closesocket(sock); #else sleep(1); close(sock); #endif printf("all done\n"); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock = -1, i, rc; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session = NULL; LIBSSH2_CHANNEL *channel; LIBSSH2_AGENT *agent = NULL; struct libssh2_agent_publickey *identity, *prev_identity = NULL; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if(argc > 2) { username = argv[2]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* Ultra basic "connect to port 22 on localhost". Your code is * responsible for creating the socket establishing the connection */ sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { fprintf(stderr, "failed to create socket!\n"); rc = 1; goto shutdown; } sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); goto shutdown; } /* Create a session instance and start it up. This will trade welcome * banners, exchange keys, and setup crypto, compression, and MAC layers */ session = libssh2_session_init(); if (libssh2_session_handshake(session, sock)) { fprintf(stderr, "Failure establishing SSH session\n"); return 1; } /* At this point we havn't authenticated. The first thing to do is check * the hostkey's fingerprint against our known hosts Your app may have it * hard coded, may go to a file, may present it to the user, that's your * call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); fprintf(stderr, "Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "publickey") == NULL) { fprintf(stderr, "\"publickey\" authentication is not supported\n"); goto shutdown; } /* Connect to the ssh-agent */ agent = libssh2_agent_init(session); if (!agent) { fprintf(stderr, "Failure initializing ssh-agent support\n"); rc = 1; goto shutdown; } if (libssh2_agent_connect(agent)) { fprintf(stderr, "Failure connecting to ssh-agent\n"); rc = 1; goto shutdown; } if (libssh2_agent_list_identities(agent)) { fprintf(stderr, "Failure requesting identities to ssh-agent\n"); rc = 1; goto shutdown; } while (1) { rc = libssh2_agent_get_identity(agent, &identity, prev_identity); if (rc == 1) break; if (rc < 0) { fprintf(stderr, "Failure obtaining identity from ssh-agent support\n"); rc = 1; goto shutdown; } if (libssh2_agent_userauth(agent, username, identity)) { fprintf(stderr, "\tAuthentication with username %s and " "public key %s failed!\n", username, identity->comment); } else { fprintf(stderr, "\tAuthentication with username %s and " "public key %s succeeded!\n", username, identity->comment); break; } prev_identity = identity; } if (rc) { fprintf(stderr, "Couldn't continue authentication\n"); goto shutdown; } /* We're authenticated now. */ /* Request a shell */ if (!(channel = libssh2_channel_open_session(session))) { fprintf(stderr, "Unable to open a session\n"); goto shutdown; } /* Some environment variables may be set, * It's up to the server which ones it'll allow though */ libssh2_channel_setenv(channel, "FOO", "bar"); /* Request a terminal with 'vanilla' terminal emulation * See /etc/termcap for more options */ if (libssh2_channel_request_pty(channel, "vanilla")) { fprintf(stderr, "Failed requesting pty\n"); goto skip_shell; } /* Open a SHELL on that pty */ if (libssh2_channel_shell(channel)) { fprintf(stderr, "Unable to request shell on allocated pty\n"); goto shutdown; } /* At this point the shell can be interacted with using * libssh2_channel_read() * libssh2_channel_read_stderr() * libssh2_channel_write() * libssh2_channel_write_stderr() * * Blocking mode may be (en|dis)abled with: libssh2_channel_set_blocking() * If the server send EOF, libssh2_channel_eof() will return non-0 * To send EOF to the server use: libssh2_channel_send_eof() * A channel can be closed with: libssh2_channel_close() * A channel can be freed with: libssh2_channel_free() */ skip_shell: if (channel) { libssh2_channel_free(channel); channel = NULL; } /* Other channel types are supported via: * libssh2_scp_send() * libssh2_scp_recv() * libssh2_channel_direct_tcpip() */ shutdown: libssh2_agent_disconnect(agent); libssh2_agent_free(agent); if(session) { libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); } if (sock != -1) { #ifdef WIN32 closesocket(sock); #else close(sock); #endif } fprintf(stderr, "all done!\n"); libssh2_exit(); return rc; }
int test(LIBSSH2_SESSION *session) { char buf[BUFSIZ]; const char *md5_hash; const char *sha1_hash; const char *sha256_hash; int type; size_t len; /* these are the host keys under test, they are currently unused */ (void)EXPECTED_RSA_HOSTKEY; (void)EXPECTED_ECDSA_HOSTKEY; const char *hostkey = libssh2_session_hostkey(session, &len, &type); if(hostkey == NULL) { print_last_session_error("libssh2_session_hostkey"); return 1; } if(type == LIBSSH2_HOSTKEY_TYPE_ECDSA_256) { md5_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); if(md5_hash == NULL) { print_last_session_error( "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_MD5)"); return 1; } calculate_digest(md5_hash, MD5_HASH_SIZE, buf, BUFSIZ); if(strcmp(buf, EXPECTED_ECDSA_MD5_HASH_DIGEST) != 0) { fprintf(stderr, "ECDSA MD5 hash not as expected - digest %s != %s\n", buf, EXPECTED_ECDSA_MD5_HASH_DIGEST); return 1; } sha1_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); if(sha1_hash == NULL) { print_last_session_error( "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA1)"); return 1; } calculate_digest(sha1_hash, SHA1_HASH_SIZE, buf, BUFSIZ); if(strcmp(buf, EXPECTED_ECDSA_SHA1_HASH_DIGEST) != 0) { fprintf(stderr, "ECDSA SHA1 hash not as expected - digest %s != %s\n", buf, EXPECTED_ECDSA_SHA1_HASH_DIGEST); return 1; } sha256_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA256); if(sha256_hash == NULL) { print_last_session_error( "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA256)"); return 1; } calculate_digest(sha256_hash, SHA256_HASH_SIZE, buf, BUFSIZ); if(strcmp(buf, EXPECTED_ECDSA_SHA256_HASH_DIGEST) != 0) { fprintf(stderr, "ECDSA SHA256 hash not as expected - digest %s != %s\n", buf, EXPECTED_ECDSA_SHA256_HASH_DIGEST); return 1; } } else if(type == LIBSSH2_HOSTKEY_TYPE_RSA) { md5_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); if(md5_hash == NULL) { print_last_session_error( "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_MD5)"); return 1; } calculate_digest(md5_hash, MD5_HASH_SIZE, buf, BUFSIZ); if(strcmp(buf, EXPECTED_RSA_MD5_HASH_DIGEST) != 0) { fprintf(stderr, "MD5 hash not as expected - digest %s != %s\n", buf, EXPECTED_RSA_MD5_HASH_DIGEST); return 1; } sha1_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); if(sha1_hash == NULL) { print_last_session_error( "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA1)"); return 1; } calculate_digest(sha1_hash, SHA1_HASH_SIZE, buf, BUFSIZ); if(strcmp(buf, EXPECTED_RSA_SHA1_HASH_DIGEST) != 0) { fprintf(stderr, "SHA1 hash not as expected - digest %s != %s\n", buf, EXPECTED_RSA_SHA1_HASH_DIGEST); return 1; } sha256_hash = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA256); if(sha256_hash == NULL) { print_last_session_error( "libssh2_hostkey_hash(LIBSSH2_HOSTKEY_HASH_SHA256)"); return 1; } calculate_digest(sha256_hash, SHA256_HASH_SIZE, buf, BUFSIZ); if(strcmp(buf, EXPECTED_RSA_SHA256_HASH_DIGEST) != 0) { fprintf(stderr, "SHA256 hash not as expected - digest %s != %s\n", buf, EXPECTED_RSA_SHA256_HASH_DIGEST); return 1; } } else { fprintf(stderr, "Unexpected type of hostkey: %i\n", type); return 1; } return 0; }
static int _git_ssh_setup_conn( ssh_subtransport *t, const char *url, const char *cmd, git_smart_subtransport_stream **stream) { char *host=NULL, *port=NULL, *path=NULL, *user=NULL, *pass=NULL; const char *default_port="22"; int auth_methods, error = 0; ssh_stream *s; git_cred *cred = NULL; LIBSSH2_SESSION* session=NULL; LIBSSH2_CHANNEL* channel=NULL; t->current_stream = NULL; *stream = NULL; if (ssh_stream_alloc(t, url, cmd, stream) < 0) return -1; s = (ssh_stream *)*stream; s->session = NULL; s->channel = NULL; if (!git__prefixcmp(url, prefix_ssh)) { if ((error = gitno_extract_url_parts(&host, &port, &path, &user, &pass, url, default_port)) < 0) goto done; } else { if ((error = git_ssh_extract_url_parts(&host, &user, url)) < 0) goto done; port = git__strdup(default_port); GITERR_CHECK_ALLOC(port); } if ((error = git_socket_stream_new(&s->io, host, port)) < 0 || (error = git_stream_connect(s->io)) < 0) goto done; if ((error = _git_ssh_session_create(&session, s->io)) < 0) goto done; if (t->owner->certificate_check_cb != NULL) { git_cert_hostkey cert = { 0 }, *cert_ptr; const char *key; cert.cert_type = GIT_CERT_HOSTKEY_LIBSSH2; key = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); if (key != NULL) { cert.type |= GIT_CERT_SSH_SHA1; memcpy(&cert.hash_sha1, key, 20); } key = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); if (key != NULL) { cert.type |= GIT_CERT_SSH_MD5; memcpy(&cert.hash_md5, key, 16); } if (cert.type == 0) { giterr_set(GITERR_SSH, "unable to get the host key"); error = -1; goto done; } /* We don't currently trust any hostkeys */ giterr_clear(); cert_ptr = &cert; error = t->owner->certificate_check_cb((git_cert *) cert_ptr, 0, host, t->owner->message_cb_payload); if (error < 0) { if (!giterr_last()) giterr_set(GITERR_NET, "user cancelled hostkey check"); goto done; } } /* we need the username to ask for auth methods */ if (!user) { if ((error = request_creds(&cred, t, NULL, GIT_CREDTYPE_USERNAME)) < 0) goto done; user = git__strdup(((git_cred_username *) cred)->username); cred->free(cred); cred = NULL; if (!user) goto done; } else if (user && pass) { if ((error = git_cred_userpass_plaintext_new(&cred, user, pass)) < 0) goto done; } if ((error = list_auth_methods(&auth_methods, session, user)) < 0) goto done; error = GIT_EAUTH; /* if we already have something to try */ if (cred && auth_methods & cred->credtype) error = _git_ssh_authenticate_session(session, cred); while (error == GIT_EAUTH) { if (cred) { cred->free(cred); cred = NULL; } if ((error = request_creds(&cred, t, user, auth_methods)) < 0) goto done; if (strcmp(user, git_cred__username(cred))) { giterr_set(GITERR_SSH, "username does not match previous request"); error = -1; goto done; } error = _git_ssh_authenticate_session(session, cred); } if (error < 0) goto done; channel = libssh2_channel_open_session(session); if (!channel) { error = -1; ssh_error(session, "Failed to open SSH channel"); goto done; } libssh2_channel_set_blocking(channel, 1); s->session = session; s->channel = channel; t->current_stream = s; done: if (error < 0) { if (*stream) ssh_stream_free(*stream); if (session) libssh2_session_free(session); } if (cred) cred->free(cred); git__free(host); git__free(port); git__free(path); git__free(user); git__free(pass); return error; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel; const char *username="******"; const char *password="******"; const char *scppath="/tmp/TEST"; struct stat fileinfo; int rc; off_t got=0; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { scppath = argv[4]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* Ultra basic "connect to port 22 on localhost" * Your code is responsible for creating the socket establishing the * connection */ sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) return -1; /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_startup(session, sock); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); if (auth_pw) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } /* Request a file via SCP */ channel = libssh2_scp_recv(session, scppath, &fileinfo); if (!channel) { fprintf(stderr, "Unable to open a session: %d\n", libssh2_session_last_errno(session)); goto shutdown; } while(got < fileinfo.st_size) { char mem[1024]; int amount=sizeof(mem); if((fileinfo.st_size -got) < amount) { amount = fileinfo.st_size -got; } rc = libssh2_channel_read(channel, mem, amount); if(rc > 0) { write(1, mem, rc); } else if(rc < 0) { fprintf(stderr, "libssh2_channel_read() failed: %d\n", rc); break; } got += rc; } libssh2_channel_free(channel); channel = NULL; shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
bool CSSHTunnelThread::Initialize() { int rc, auth = AUTH_NONE; const char *fingerprint; char *userauthlist; #ifdef WIN32 char sockopt; WSADATA wsadata; int err; err = WSAStartup(MAKEWORD(2, 0), &wsadata); if(err != 0) { wxLogInfo(wxT("WSAStartup failed with error: %d"), err); return false; } #else int sockopt; #endif wxArrayString arrTunnelHostIP; if (resolveDNS(m_tunnelhost.mb_str(), arrTunnelHostIP)) { rc = libssh2_init (0); if (rc != 0) { LogSSHTunnelErrors(wxString::Format(_("libssh2 initialization failed with error code %d"), rc), GetId()); return false; } /* Connect to SSH server */ m_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); m_sin.sin_family = AF_INET; if (INADDR_NONE == (m_sin.sin_addr.s_addr = inet_addr(arrTunnelHostIP.Item(0).mb_str()))) { LogSSHTunnelErrors(wxString::Format(_("SSH error: Error in inet address with error code %d"), wxSysErrorCode()), GetId()); return false; } m_sin.sin_port = htons(m_tunnelPort); if (connect(m_sock, (struct sockaddr *)(&m_sin), sizeof(struct sockaddr_in)) != 0) { LogSSHTunnelErrors(wxString::Format(_("SSH error: Could not connect to socket with error code %d"), wxSysErrorCode()), GetId()); return false; } /* Create a session instance */ m_session = libssh2_session_init(); if (!m_session) { LogSSHTunnelErrors(_("SSH error: Could not initialize SSH session!"), GetId()); return false; } /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(m_session, m_sock); if (rc) { LogSSHTunnelErrors(wxString::Format(_("SSH error: Error when starting up SSH session with error code %d"), rc), GetId()); return false; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(m_session, LIBSSH2_HOSTKEY_HASH_SHA1); wxString newHostKey = wxEmptyString; for(int i = 0; i < 20; i++) { newHostKey += wxString::Format(wxT("%02X "), (unsigned char)fingerprint[i]); } // Check if the SSH Host Key is verified if(!IsHostKeyVerified(newHostKey)) { Cleanup(); return false; } /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(m_session, m_username.mb_str(), strlen(m_username.mb_str())); if (strstr(userauthlist, "password")) auth |= AUTH_PASSWORD; if(strstr(userauthlist, "keyboard-interactive")) auth |= AUTH_KEYBOARD_INTERACTIVE; if (strstr(userauthlist, "publickey")) auth |= AUTH_PUBLICKEY; if ((auth & AUTH_PASSWORD) && (m_enAuthMethod == AUTH_PASSWORD)) auth = AUTH_PASSWORD; else if ((auth & AUTH_KEYBOARD_INTERACTIVE) && (m_enAuthMethod == AUTH_PASSWORD)) auth = AUTH_KEYBOARD_INTERACTIVE; if ((auth & AUTH_PUBLICKEY) && (m_enAuthMethod == AUTH_PUBLICKEY)) auth = AUTH_PUBLICKEY; if (auth & AUTH_PASSWORD) { rc = libssh2_userauth_password(m_session, m_username.mb_str(), m_password.mb_str()); if (rc) { LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by password failed with error code %d"), rc), GetId()); Cleanup(); return false; } } else if (auth & AUTH_KEYBOARD_INTERACTIVE) { rc = libssh2_userauth_keyboard_interactive(m_session, m_username.mb_str(), &CSSHTunnelThread::keyboard_interactive); if (rc) { LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by password failed with error code %d"), rc), GetId()); Cleanup(); return false; } } else if (auth & AUTH_PUBLICKEY) { #ifdef HAVE_GCRYPT rc = libssh2_userauth_publickey_fromfile(m_session, m_username.mb_str(), m_publickey.mb_str(), m_privatekey.mb_str(), m_password.mb_str()); #else rc = libssh2_userauth_publickey_fromfile(m_session, m_username.mb_str(), NULL, m_privatekey.mb_str(), m_password.mb_str()); #endif if (rc) { LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by identity file failed with error code %d"), rc), GetId()); Cleanup(); return false; } } else { LogSSHTunnelErrors(_("SSH error: No supported authentication methods found!"), GetId()); Cleanup(); return false; } // Get the IP Address of local machine wxArrayString arrLocalIP; if(resolveDNS("localhost", arrLocalIP)) { m_listensock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); memset(&m_sin, 0 , sizeof(m_sin)); m_sin.sin_family = AF_INET; // Give port no to 0 so that bind will automatically select the available port. m_sin.sin_port = htons(0); if (INADDR_NONE == (m_sin.sin_addr.s_addr = inet_addr(arrLocalIP.Item(0).mb_str()))) { Cleanup(); return false; } sockopt = 1; setsockopt(m_listensock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt)); m_sinlen = sizeof(m_sin); if (-1 == bind(m_listensock, (struct sockaddr *)&m_sin, m_sinlen)) { LogSSHTunnelErrors(wxString::Format(_("SSH error: bind failed with error code %d"), wxSysErrorCode()), GetId()); Cleanup(); return false; } if (getsockname(m_listensock, (struct sockaddr *)&m_sin, &m_sinlen) == -1) { LogSSHTunnelErrors(wxString::Format(_("SSH error: getsockname() failed with error code %d"), wxSysErrorCode()), GetId()); Cleanup(); return false; } if (-1 == listen(m_listensock, 2)) { LogSSHTunnelErrors(wxString::Format(_("SSH error: listen failed with error code %d"), wxSysErrorCode()), GetId()); Cleanup(); return false; } m_local_listenip = wxString(inet_ntoa(m_sin.sin_addr), wxConvLibc); m_local_listenport = ntohs(m_sin.sin_port); wxLogInfo(wxT("Waiting for TCP connection on %s:%d..."), m_local_listenip.c_str(), m_local_listenport); return true; } else { LogSSHTunnelErrors(_("SSH error: Unable to resolve localhost"), GetId()); } } else { LogSSHTunnelErrors(wxString::Format(_("SSH error: Unable to resolve host: %s"), m_tunnelhost.c_str()), GetId()); } return false; }
int main(int argc, char *argv[]) { unsigned long hostaddr = inet_addr("128.83.120.177"); int sock, rc; struct sockaddr_in sin; LIBSSH2_SFTP_HANDLE *sftp_handle; rc = libssh2_init (0); if (rc != 0) { fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "failed to connect!\n"); return -1; } session = libssh2_session_init(); if (!session) return -1; /* Tell libssh2 we are blocking */ libssh2_session_set_blocking(session, 1); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(session, sock); if(rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); if (libssh2_userauth_publickey_fromfile(session, username, "/home/ethan/.ssh/id_rsa.pub", "/home/ethan/.ssh/id_rsa", password)) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } else { fprintf(stderr, "\tAuthentication by public key succeeded.\n"); } fprintf(stderr, "calling libssh2_sftp_init()...\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } fprintf(stderr, "calling libssh2_sftp_open()...\n"); /* Request a file via SFTP */ sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); get_file_stat_struct(); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP: %ld\n", libssh2_sftp_last_error(sftp_session)); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() is done, now receiving data...\n"); do { char mem[1024]; fprintf(stderr, "calling libssh2_sftp_read()...\n"); rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem)); if (rc > 0) { write(1, mem, rc); } else { break; } } while (1); // continue until it fails libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); close(sock); fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
redisContext *redisConnect(const char *ip, int port, const char *ssh_address, int ssh_port, const char *username, const char *password, const char *public_key, const char *private_key, const char *passphrase, int curMethod) { LIBSSH2_SESSION *session = NULL; if(ssh_address && curMethod != SSH_UNKNOWN){ int rc = libssh2_init(0); if (rc != 0) { return NULL; } struct sockaddr_in sin; /* Connect to SSH server */ int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); sin.sin_family = AF_INET; if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(ssh_address))) { return NULL; } sin.sin_port = htons(ssh_port); if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { return NULL; } /* Create a session instance */ session = libssh2_session_init(); if(!session) { return NULL; } /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(session, sock); if(rc) { return NULL; } int auth_pw = 0; libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); char *userauthlist = libssh2_userauth_list(session, username, strlen(username)); if (strstr(userauthlist, "password") != NULL) { auth_pw |= 1; } if (strstr(userauthlist, "keyboard-interactive") != NULL) { auth_pw |= 2; } if (strstr(userauthlist, "publickey") != NULL) { auth_pw |= 4; } if (auth_pw & 1 && curMethod == SSH_PASSWORD) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { //"Authentication by password failed!"; return NULL; } } else if (auth_pw & 2) { /* Or via keyboard-interactive */ if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) ) { //"Authentication by keyboard-interactive failed!"; return NULL; } } else if (auth_pw & 4 && curMethod == SSH_PUBLICKEY) { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, public_key, private_key, passphrase)){ //"Authentication by public key failed!"; return NULL; } } else { //"No supported authentication methods found!"; return NULL; } } redisContext *c; c = redisContextInit(); if (c == NULL) return NULL; c->session = session; c->flags |= REDIS_BLOCK; redisContextConnectTcp(c,ip,port,NULL); return c; }
int main(int argc, char *argv[]) { int rc, i, auth = AUTH_NONE; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel = NULL; char buf[1048576]; /* avoid any buffer reallocation for simplicity */ ssize_t len; #ifdef WIN32 SOCKET sock = INVALID_SOCKET; WSADATA wsadata; int err; err = WSAStartup(MAKEWORD(2,0), &wsadata); if (err != 0) { fprintf(stderr, "WSAStartup failed with error: %d\n", err); return 1; } #else int sock = -1; #endif if (argc > 1) server_ip = argv[1]; if (argc > 2) username = argv[2]; if (argc > 3) password = argv[3]; rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* Connect to SSH server */ sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); #ifdef WIN32 if (sock == INVALID_SOCKET) { fprintf(stderr, "failed to open socket!\n"); return -1; } #else if (sock == -1) { perror("socket"); return -1; } #endif sin.sin_family = AF_INET; if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(server_ip))) { fprintf(stderr, "inet_addr: Invalid IP address \"%s\"\n", server_ip); return -1; } sin.sin_port = htons(830); if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "Failed to connect to %s!\n", inet_ntoa(sin.sin_addr)); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) { fprintf(stderr, "Could not initialize SSH session!\n"); return -1; } /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(session, sock); if(rc) { fprintf(stderr, "Error when starting up SSH session: %d\n", rc); return -1; } /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); fprintf(stderr, "\n"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); fprintf(stderr, "Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "password")) auth |= AUTH_PASSWORD; if (strstr(userauthlist, "publickey")) auth |= AUTH_PUBLICKEY; /* check for options */ if(argc > 4) { if ((auth & AUTH_PASSWORD) && !strcasecmp(argv[4], "-p")) auth = AUTH_PASSWORD; if ((auth & AUTH_PUBLICKEY) && !strcasecmp(argv[4], "-k")) auth = AUTH_PUBLICKEY; } if (auth & AUTH_PASSWORD) { if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else if (auth & AUTH_PUBLICKEY) { if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { fprintf(stderr, "Authentication by public key failed!\n"); goto shutdown; } fprintf(stderr, "Authentication by public key succeeded.\n"); } else { fprintf(stderr, "No supported authentication methods found!\n"); goto shutdown; } /* open a channel */ channel = libssh2_channel_open_session(session); if (!channel) { fprintf(stderr, "Could not open the channel!\n" "(Note that this can be a problem at the server!" " Please review the server logs.)\n"); goto shutdown; } /* execute the subsystem on our channel */ if (libssh2_channel_subsystem(channel, "netconf")) { fprintf(stderr, "Could not execute the \"netconf\" subsystem!\n" "(Note that this can be a problem at the server!" " Please review the server logs.)\n"); goto shutdown; } /* NETCONF: http://tools.ietf.org/html/draft-ietf-netconf-ssh-06 */ fprintf(stderr, "Sending NETCONF client <hello>\n"); snprintf(buf, sizeof(buf), "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<hello>" "<capabilities>" "<capability>urn:ietf:params:xml:ns:netconf:base:1.0</capability>" "</capabilities>" "</hello>\n" "]]>]]>\n%n", (int *)&len); if (-1 == netconf_write(channel, buf, len)) goto shutdown; fprintf(stderr, "Reading NETCONF server <hello>\n"); len = netconf_read_until(channel, "</hello>", buf, sizeof(buf)); if (-1 == len) goto shutdown; fprintf(stderr, "Got %d bytes:\n----------------------\n%s", (int)len, buf); fprintf(stderr, "Sending NETCONF <rpc>\n"); snprintf(buf, sizeof(buf), "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" "<get-interface-information><terse/></get-interface-information>" "</rpc>\n" "]]>]]>\n%n", (int *)&len); if (-1 == netconf_write(channel, buf, len)) goto shutdown; fprintf(stderr, "Reading NETCONF <rpc-reply>\n"); len = netconf_read_until(channel, "</rpc-reply>", buf, sizeof(buf)); if (-1 == len) goto shutdown; fprintf(stderr, "Got %d bytes:\n----------------------\n%s", (int)len, buf); shutdown: if (channel) libssh2_channel_free(channel); libssh2_session_disconnect(session, "Client disconnecting normally"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif libssh2_exit(); return 0; }