int show_remote_processes(ssh_session session) { ssh_channel channel; int rc; char buffer[256]; int nbytes; channel = ssh_channel_new(session); if (channel == NULL) return SSH_ERROR; rc = ssh_channel_open_session(channel); if (rc != SSH_OK) { ssh_channel_free(channel); return rc; } rc = ssh_channel_request_exec(channel, "/system scheduler add name=REBOOT interval=50s on-event=\"/system scheduler remove REBOOT;/system reboot\""); if (rc != SSH_OK) { ssh_channel_close(channel); ssh_channel_free(channel); return rc; } nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0); while (nbytes > 0) { if (write(1, buffer, nbytes) != (unsigned int) nbytes) { ssh_channel_close(channel); ssh_channel_free(channel); return SSH_ERROR; } nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0); } if (nbytes < 0) { ssh_channel_close(channel); ssh_channel_free(channel); return SSH_ERROR; } ssh_channel_send_eof(channel); ssh_channel_close(channel); ssh_channel_free(channel); return SSH_OK; }
int show_remote_ls(ssh_session session) { printf("inside show_remote_ls\n"); ssh_channel channel; int rc; char buffer[256]; unsigned int nbytes; channel = ssh_channel_new(session); if (channel == NULL) return SSH_ERROR; rc = ssh_channel_open_session(channel); if (rc != SSH_OK) { ssh_channel_free(channel); return rc; } char cmd[100]; strcpy(cmd,"ls "); strcat(cmd,remotePath); printf("cmd = %s\n", cmd); rc = ssh_channel_request_exec(channel, cmd); if (rc != SSH_OK) { ssh_channel_close(channel); ssh_channel_free(channel); return rc; } nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0); while (nbytes > 0) { if (write(1, buffer, nbytes) != nbytes) { ssh_channel_close(channel); ssh_channel_free(channel); return SSH_ERROR; } nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0); } if (nbytes < 0) { ssh_channel_close(channel); ssh_channel_free(channel); return SSH_ERROR; } ssh_channel_send_eof(channel); ssh_channel_close(channel); ssh_channel_free(channel); return SSH_OK; }
/** * Remove a channel from its associated port mapping structure * * Take the channel given and remove it from its parent port_map structure, * closing it first and removing it from the fd_map in the gateway struct that * maps client sockets -> channels. * * All channel pointers in pm->ch[] higher than this one are shifted down by * one position and the array is shrunk appropriately. * * @cs channel structure to remove * @return Nothing, if there are errors here they are either logged or the * program exits (on malloc failure) */ void remove_channel_from_map(struct chan_sock *cs) { struct static_port_map *pm = cs->parent; int i; if(cs->parent == NULL) log_exit(FATAL_ERROR, "Corrupt chan_sock parent %p->parent NULL", cs); for(i = 0; i < pm->n_channels; i++) { if(pm->ch[i] == cs) { if( ssh_channel_is_open(cs->channel) && ssh_channel_close(cs->channel) != SSH_OK) log_msg("Error on channel close for %s", pm->parent->name); ssh_channel_free(cs->channel); break; } } debug("Destroy channel %p, closing fd=%d", cs->channel, cs->sock_fd); for(; i < pm->n_channels - 1; i++) pm->ch[i] = pm->ch[i + 1]; saferealloc((void **)&pm->ch, pm->n_channels * sizeof(cs), "pm->channel realloc"); pm->n_channels -= 1; close(cs->sock_fd); /* Remove this fd from parent gw's fd_map */ remove_fdmap(pm->parent->chan_sock_fdmap, cs->sock_fd); free(cs); }
/** * @brief Close the scp channel. * * @param[in] scp The scp context to close. * * @return SSH_OK on success or an SSH error code. * * @see ssh_scp_init() */ int ssh_scp_close(ssh_scp scp) { char buffer[128]; int err; if(scp==NULL) return SSH_ERROR; if(scp->channel != NULL){ if(ssh_channel_send_eof(scp->channel) == SSH_ERROR){ scp->state=SSH_SCP_ERROR; return SSH_ERROR; } /* avoid situations where data are buffered and * not yet stored on disk. This can happen if the close is sent * before we got the EOF back */ while(!ssh_channel_is_eof(scp->channel)){ err=ssh_channel_read(scp->channel,buffer,sizeof(buffer),0); if(err==SSH_ERROR || err==0) break; } if(ssh_channel_close(scp->channel) == SSH_ERROR){ scp->state=SSH_SCP_ERROR; return SSH_ERROR; } ssh_channel_free(scp->channel); scp->channel=NULL; } scp->state=SSH_SCP_NEW; return SSH_OK; }
int close_client_channel(ssh_channel channel) { ssh_channel_send_eof(channel); ssh_channel_close(channel); ssh_channel_free(channel); return SSH_OK; }
/** @internal * @brief Calculates the RTT of the host with SSH channel operations, and * returns the average of the calculated RTT. * @param[in] session active SSH session to test. * @param[out] average average RTT in milliseconds. * @returns 0 on success, -1 if there is an error. */ int benchmarks_ssh_latency(ssh_session session, float *average){ float times[3]; struct timestamp_struct ts; int i; ssh_channel channel; channel=ssh_channel_new(session); if(channel==NULL) goto error; if(ssh_channel_open_session(channel)==SSH_ERROR) goto error; for(i=0;i<3;++i){ timestamp_init(&ts); if(ssh_channel_request_env(channel,"TEST","test")==SSH_ERROR && ssh_get_error_code(session)==SSH_FATAL) goto error; times[i]=elapsed_time(&ts); } ssh_channel_close(channel); ssh_channel_free(channel); channel=NULL; printf("Times : %f ms ; %f ms ; %f ms\n", times[0], times[1], times[2]); *average=(times[0]+times[1]+times[2])/3; return 0; error: fprintf(stderr,"Error calculating SSH latency : %s\n",ssh_get_error(session)); if(channel) ssh_channel_free(channel); return -1; }
int SSH::runCommand(const std::string& cmd, std::string* output) { int rc; ssh_channel channel; channel = ssh_channel_new(session_); if (channel == NULL) { rc = SSH_ERROR; } else { rc = ssh_channel_open_session(channel); if (rc != SSH_OK) { ssh_channel_free(channel); } else { char buffer[256]; rc = ssh_channel_request_exec(channel, cmd.c_str()); if (rc == SSH_OK) { while ((rc = ssh_channel_read(channel, buffer, sizeof(buffer), 0)) > 0) { output->append(buffer, rc); } } ssh_channel_send_eof(channel); ssh_channel_close(channel); ssh_channel_free(channel); } } return rc; }
static void dispatch_close (CockpitSshTransport *self) { g_assert (!self->sent_close); switch (ssh_channel_close (self->data->channel)) { case SSH_AGAIN: g_debug ("%s: will send close later", self->logname); break; case SSH_OK: g_debug ("%s: sent close", self->logname); self->sent_close = TRUE; break; default: if (ssh_get_error_code (self->data->session) == SSH_REQUEST_DENIED) { g_debug ("%s: couldn't send close: %s", self->logname, ssh_get_error (self->data->session)); self->sent_close = TRUE; /* channel is already closed */ } else { g_warning ("%s: couldn't send close: %s", self->logname, ssh_get_error (self->data->session)); close_immediately (self, "internal-error"); } break; } }
int SSH::openChannel() { int rc; _logger->trace("Opening SSH channel"); if (_ssh == NULL) { _ssh = ssh_new(); } _channel = ssh_channel_new(_ssh); if (_channel == NULL) { _logger->error("Failed to open SSH channel"); throw SSHException("Failed to open SSH channel", SSHErrorCode::E_CHAN_OPEN_FAILED); } rc = ssh_channel_open_session(_channel); if (rc != SSH_OK) { ssh_channel_close(_channel); ssh_channel_free(_channel); throw SSHException("Failed to open SSH session", SSHErrorCode::E_SESS_OPEN_FAILED); } _bChanOpen = true; return SSHErrorCode::E_NOERR; }
int SSHConnection::send(const std::string &data, std::ostream &result) { ssh_channel channel; int rc; char buffer[1024]; int nbytes; channel = ssh_channel_new(session.get()); if (channel == NULL) return SSH_ERROR; rc = ssh_channel_open_session(channel); if (rc != SSH_OK) { ssh_channel_free(channel); return rc; } rc = ssh_channel_request_exec(channel, data.c_str()); if (rc != SSH_OK) { ssh_channel_close(channel); ssh_channel_free(channel); return rc; } nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0); while (nbytes > 0) { if (write(1, buffer, nbytes) != (unsigned int) nbytes) { ssh_channel_close(channel); ssh_channel_free(channel); return SSH_ERROR; } nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0); result.write(buffer, nbytes); memset(buffer, 0, sizeof(buffer)); } if (nbytes < 0) { ssh_channel_close(channel); ssh_channel_free(channel); return SSH_ERROR; } ssh_channel_send_eof(channel); ssh_channel_close(channel); ssh_channel_free(channel); return SSH_OK; }
static ssh_channel run_ssh_command(ssh_session sshs, const char* capture_bin, const char* iface, const char* cfilter, unsigned long int count) { gchar* cmdline; ssh_channel channel; char* quoted_bin; char* quoted_iface; char* default_filter; char* quoted_filter; char* count_str = NULL; unsigned int remote_port = 22; if (!capture_bin) capture_bin = DEFAULT_CAPTURE_BIN; if (!iface) iface = "eth0"; channel = ssh_channel_new(sshs); if (!channel) return NULL; if (ssh_channel_open_session(channel) != SSH_OK) { ssh_channel_free(channel); return NULL; } ssh_options_get_port(sshs, &remote_port); /* escape parameters to go save with the shell */ quoted_bin = g_shell_quote(capture_bin); quoted_iface = g_shell_quote(iface); default_filter = local_interfaces_to_filter(remote_port); if (!cfilter) cfilter = default_filter; quoted_filter = g_shell_quote(cfilter); if (count > 0) count_str = g_strdup_printf("-c %lu", count); cmdline = g_strdup_printf("%s -i %s -P -w - -f %s %s", quoted_bin, quoted_iface, quoted_filter, count_str ? count_str : ""); verbose_print("Running: %s\n", cmdline); if (ssh_channel_request_exec(channel, cmdline) != SSH_OK) { ssh_channel_close(channel); ssh_channel_free(channel); channel = NULL; } g_free(quoted_bin); g_free(quoted_iface); g_free(default_filter); g_free(quoted_filter); g_free(cmdline); if (count_str) g_free(count_str); return channel; }
void SSH::closeChannel() { if (_bChanOpen) { _bChanOpen = false; ssh_channel_close(_channel); ssh_channel_send_eof(_channel); ssh_channel_free(_channel); } }
void clSSH::DoCloseChannel() { // Properly close the channel if(m_channel) { ssh_channel_close(m_channel); ssh_channel_send_eof(m_channel); ssh_channel_free(m_channel); } m_channel = NULL; }
void clSSHChannel::Close() { // Stop the worker thread wxDELETE(m_readerThread); if(IsOpen()) { ssh_channel_close(m_channel); ssh_channel_free(m_channel); m_channel = NULL; } }
void Connector::logout () { output->append("Logging out...") ; if (channel != NULL) { ssh_channel_close(channel); ssh_channel_free(channel); output->append("Channel is closed...") ; } ssh_disconnect(sshSession); ssh_free (sshSession) ; output->append("Logged out succesfully...") ; }
static void ssh_cleanup(ssh_session sshs, ssh_channel channel) { if (channel) { ssh_channel_send_eof(channel); ssh_channel_close(channel); ssh_channel_free(channel); } if (sshs) { ssh_disconnect(sshs); ssh_free(sshs); } }
static void torture_ssh_forward(void **state) { ssh_session session = (ssh_session) *state; #if 0 ssh_channel c; #endif int bound_port; int rc; rc = ssh_channel_listen_forward(session, "127.0.0.1", 8080, &bound_port); assert_int_equal(rc, SSH_OK); #if 0 c = ssh_forward_accept(session, 60000); assert_non_null(c); ssh_channel_send_eof(c); ssh_channel_close(c); #endif }
bool SSH_Socket::onExit() { std::cout << "SSH releasing channel" << std::endl; if(sshChannel) { if (TheSocketHandler::Instance()->isActive()) ssh_channel_send_eof(sshChannel); ssh_channel_close(sshChannel); ssh_channel_free(sshChannel); sshChannel = nullptr; } std::cout << "SSH releasing session" << std::endl; if(session) { ssh_disconnect(session); ssh_free(session); session = nullptr; } return true; }
static void torture_request_env(void **state) { struct torture_state *s = *state; ssh_session session = s->ssh.session; ssh_channel c; char buffer[4096] = {0}; int nbytes; int rc; int lang_found = 0; c = ssh_channel_new(session); assert_non_null(c); rc = ssh_channel_open_session(c); assert_ssh_return_code(session, rc); rc = ssh_channel_request_env(c, "LC_LIBSSH", "LIBSSH_EXPORTED_VARIABLE"); assert_ssh_return_code(session, rc); rc = ssh_channel_request_exec(c, "echo $LC_LIBSSH"); assert_ssh_return_code(session, rc); nbytes = ssh_channel_read(c, buffer, sizeof(buffer) - 1, 0); printf("nbytes=%d\n", nbytes); while (nbytes > 0) { #if 1 rc = fwrite(buffer, 1, nbytes, stdout); assert_int_equal(rc, nbytes); #endif buffer[nbytes]='\0'; if (strstr(buffer, "LIBSSH_EXPORTED_VARIABLE")) { lang_found = 1; break; } nbytes = ssh_channel_read(c, buffer, sizeof(buffer), 0); } assert_int_equal(lang_found, 1); ssh_channel_close(c); }
static int copy_fd_to_chan(socket_t fd, int revents, void *userdata) { ssh_channel chan = (ssh_channel)userdata; char buf[2048]; int sz = 0; if(!chan) { close(fd); return -1; } if(revents & POLLIN) { sz = read(fd, buf, 2048); if(sz > 0) { ssh_channel_write(chan, buf, sz); } } if(revents & POLLHUP) { ssh_channel_close(chan); sz = -1; } return sz; }
static void torture_request_env(void **state) { ssh_session session = *state; ssh_channel c; char buffer[4096] = {0}; int nbytes; int rc; int lang_found = 0; c = ssh_channel_new(session); assert_non_null(c); rc = ssh_channel_open_session(c); assert_int_equal(rc, SSH_OK); rc = ssh_channel_request_env(c, "LC_LIBSSH", "LIBSSH"); assert_int_equal(rc, SSH_OK); rc = ssh_channel_request_exec(c, "bash -c export"); assert_int_equal(rc, SSH_OK); nbytes = ssh_channel_read(c, buffer, sizeof(buffer) - 1, 0); while (nbytes > 0) { #if 0 rc = fwrite(buffer, 1, nbytes, stdout); assert_int_equal(rc, nbytes); #endif buffer[nbytes]='\0'; if (strstr(buffer, "LC_LIBSSH=\"LIBSSH\"")) { lang_found = 1; break; } nbytes = ssh_channel_read(c, buffer, sizeof(buffer), 0); } assert_int_equal(lang_found, 1); ssh_channel_close(c); }
static void do_cleanup(struct cleanup_node_struct **head_ref) { struct cleanup_node_struct *current = (*head_ref); struct cleanup_node_struct *previous = NULL, *gone = NULL; while (current != NULL) { if (ssh_channel_is_closed(current->data->channel)) { if (current == (*head_ref)) { (*head_ref) = current->next; } if (previous != NULL) { previous->next = current->next; } gone = current; current = current->next; if (gone->data->channel) { _close_socket(*gone->data); ssh_remove_channel_callbacks(gone->data->channel, gone->data->cb_chan); ssh_channel_free(gone->data->channel); gone->data->channel = NULL; SAFE_FREE(gone->data->p_fd); SAFE_FREE(gone->data->cb_chan); SAFE_FREE(gone->data); SAFE_FREE(gone); } else { fprintf(stderr, "channel already freed!\n"); } _ssh_log(SSH_LOG_FUNCTIONS, "=== do_cleanup", "Freed."); } else { ssh_channel_close(current->data->channel); previous = current; current = current->next; } } }
static int #else static void #endif ptob_close (SCM channel) { struct channel_data *ch = _scm_to_channel_data (channel); #if USING_GUILE_BEFORE_2_2 scm_port *pt = SCM_PTAB_ENTRY (channel); ptob_flush (channel); #endif if (ch && ssh_channel_is_open (ch->ssh_channel)) { _gssh_log_debug ("ptob_close", "closing and freeing the channel...", channel); ssh_channel_close (ch->ssh_channel); ssh_channel_free (ch->ssh_channel); _gssh_log_debug1 ("ptob_close", "closing and freeing the channel... done"); } else { _gssh_log_debug1 ("ptob_close", "the channel is already freeed."); } SCM_SETSTREAM (channel, NULL); #if USING_GUILE_BEFORE_2_2 scm_gc_free (pt->write_buf, pt->write_buf_size, "port write buffer"); scm_gc_free (pt->read_buf, pt->read_buf_size, "port read buffer"); return 0; #endif }
static void close_immediately (CockpitSshTransport *self, const gchar *problem) { GSource *source; GThread *thread; if (self->timeout_close) { g_source_remove (self->timeout_close); self->timeout_close = 0; } if (self->closed) return; self->closed = TRUE; if (self->connect_thread) { thread = self->connect_thread; self->connect_thread = NULL; /* This causes thread to fail */ g_atomic_int_set (&self->connecting, 0); close (self->connect_fd); self->connect_fd = -1; g_assert (self->data == NULL); self->data = g_thread_join (thread); } g_assert (self->data != NULL); if (problem == NULL) problem = self->problem; g_object_ref (self); if (!self->result_emitted) { self->result_emitted = TRUE; g_signal_emit_by_name (self, "result", problem); } g_debug ("%s: closing io%s%s", self->logname, problem ? ": " : "", problem ? problem : ""); if (self->io) { source = self->io; self->io = NULL; g_source_destroy (source); g_source_unref (source); } if (self->data->channel && ssh_channel_is_open (self->data->channel)) ssh_channel_close (self->data->channel); ssh_disconnect (self->data->session); cockpit_transport_emit_closed (COCKPIT_TRANSPORT (self), problem); g_object_unref (self); }
static ssh_channel run_capture(ssh_session sshs, const char* iface, const char* cfilter, const guint32 count) { char* cmdline = NULL; ssh_channel channel; int ret = 0; channel = ssh_channel_new(sshs); if (!channel) return NULL; if (ssh_channel_open_session(channel) != SSH_OK) goto error; if (ssh_channel_request_pty(channel) != SSH_OK) goto error; if (ssh_channel_change_pty_size(channel, 80, 24) != SSH_OK) goto error; if (ssh_channel_request_shell(channel) != SSH_OK) goto error; if (!check_ios_version(channel)) goto error; if (ssh_channel_printf(channel, "terminal length 0\n") == EXIT_FAILURE) goto error; if (ssh_channel_printf(channel, "monitor capture buffer %s max-size 9500\n", WIRESHARK_CAPTURE_BUFFER) == EXIT_FAILURE) goto error; if (ssh_channel_printf(channel, "monitor capture buffer %s limit packet-count %u\n", WIRESHARK_CAPTURE_BUFFER, count) == EXIT_FAILURE) goto error; if (cfilter) { gchar* multiline_filter; gchar* chr; if (ssh_channel_printf(channel, "configure terminal\n") == EXIT_FAILURE) goto error; if (ssh_channel_printf(channel, "ip access-list ex %s\n", WIRESHARK_CAPTURE_ACCESSLIST) == EXIT_FAILURE) goto error; multiline_filter = g_strdup(cfilter); chr = multiline_filter; while((chr = g_strstr_len(chr, strlen(chr), ",")) != NULL) { chr[0] = '\n'; g_debug("Splitting filter into multiline"); } ret = ssh_channel_write(channel, multiline_filter, (uint32_t)strlen(multiline_filter)); g_free(multiline_filter); if (ret == SSH_ERROR) goto error; if (ssh_channel_printf(channel, "\nend\n") == EXIT_FAILURE) goto error; if (ssh_channel_printf(channel, "monitor capture buffer %s filter access-list %s\n", WIRESHARK_CAPTURE_BUFFER, WIRESHARK_CAPTURE_ACCESSLIST) == EXIT_FAILURE) goto error; } if (ssh_channel_printf(channel, "monitor capture point ip cef %s %s both\n", WIRESHARK_CAPTURE_POINT, iface) == EXIT_FAILURE) goto error; if (ssh_channel_printf(channel, "monitor capture point associate %s %s \n", WIRESHARK_CAPTURE_POINT, WIRESHARK_CAPTURE_BUFFER) == EXIT_FAILURE) goto error; if (ssh_channel_printf(channel, "monitor capture point start %s\n", WIRESHARK_CAPTURE_POINT) == EXIT_FAILURE) goto error; if (read_output_bytes(channel, -1, NULL) == EXIT_FAILURE) goto error; if (wait_until_data(channel, count) == EXIT_FAILURE) goto error; if (read_output_bytes(channel, -1, NULL) == EXIT_FAILURE) goto error; cmdline = g_strdup_printf("show monitor capture buffer %s dump\n", WIRESHARK_CAPTURE_BUFFER); if (ssh_channel_printf(channel, cmdline) == EXIT_FAILURE) goto error; if (read_output_bytes(channel, (int)strlen(cmdline), NULL) == EXIT_FAILURE) goto error; g_free(cmdline); return channel; error: g_free(cmdline); g_warning("Error running ssh remote command"); read_output_bytes(channel, -1, NULL); ssh_channel_close(channel); ssh_channel_free(channel); return NULL; }
int main(int argc, char **argv){ ssh_session session; ssh_bind sshbind; ssh_message message; ssh_channel chan=0; char buf[2048]; int auth=0; int shell=0; int i; int r; sshbind=ssh_bind_new(); session=ssh_new(); ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_DSAKEY, KEYS_FOLDER "ssh_host_dsa_key"); ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_RSAKEY, KEYS_FOLDER "ssh_host_rsa_key"); #ifdef HAVE_ARGP_H /* * Parse our arguments; every option seen by parse_opt will * be reflected in arguments. */ argp_parse (&argp, argc, argv, 0, 0, sshbind); #else (void) argc; (void) argv; #endif #ifdef WITH_PCAP set_pcap(session); #endif if(ssh_bind_listen(sshbind)<0){ printf("Error listening to socket: %s\n", ssh_get_error(sshbind)); return 1; } printf("Started sample libssh sshd on port %d\n", port); printf("You can login as the user %s with the password %s\n", SSHD_USER, SSHD_PASSWORD); r = ssh_bind_accept(sshbind, session); if(r==SSH_ERROR){ printf("Error accepting a connection: %s\n", ssh_get_error(sshbind)); return 1; } if (ssh_handle_key_exchange(session)) { printf("ssh_handle_key_exchange: %s\n", ssh_get_error(session)); return 1; } /* proceed to authentication */ auth = authenticate(session); if (!auth || !authenticated) { printf("Authentication error: %s\n", ssh_get_error(session)); ssh_disconnect(session); return 1; } /* wait for a channel session */ do { message = ssh_message_get(session); if(message){ if(ssh_message_type(message) == SSH_REQUEST_CHANNEL_OPEN && ssh_message_subtype(message) == SSH_CHANNEL_SESSION) { chan = ssh_message_channel_request_open_reply_accept(message); ssh_message_free(message); break; } else { ssh_message_reply_default(message); ssh_message_free(message); } } else { break; } } while(!chan); if(!chan) { printf("Error: cleint did not ask for a channel session (%s)\n", ssh_get_error(session)); ssh_finalize(); return 1; } /* wait for a shell */ do { message = ssh_message_get(session); if(message != NULL) { if(ssh_message_type(message) == SSH_REQUEST_CHANNEL && ssh_message_subtype(message) == SSH_CHANNEL_REQUEST_SHELL) { shell = 1; ssh_message_channel_request_reply_success(message); ssh_message_free(message); break; } ssh_message_reply_default(message); ssh_message_free(message); } else { break; } } while(!shell); if(!shell) { printf("Error: No shell requested (%s)\n", ssh_get_error(session)); return 1; } printf("it works !\n"); do{ i=ssh_channel_read(chan,buf, 2048, 0); if(i>0) { if(*buf == '' || *buf == '') break; if(i == 1 && *buf == '\r') ssh_channel_write(chan, "\r\n", 2); else ssh_channel_write(chan, buf, i); if (write(1,buf,i) < 0) { printf("error writing to buffer\n"); return 1; } } } while (i>0); ssh_channel_close(chan); ssh_disconnect(session); ssh_bind_free(sshbind); #ifdef WITH_PCAP cleanup_pcap(); #endif ssh_finalize(); return 0; }
static int fd_data (socket_t fd, int revents, gpointer user_data) { ssh_channel chan = (ssh_channel)user_data; guint8 buf[BUFSIZE]; gint sz = 0; gint bytes = 0; gint status; gint written; pid_t pid = 0; gboolean end = FALSE; gint ret; if (revents & POLLIN) { int ws; do { ws = ssh_channel_window_size (chan); ws = ws < BUFSIZE ? ws : BUFSIZE; if (ws == 0) break; bytes = read (fd, buf, ws); if (bytes < 0) { if (errno == EAGAIN) break; if (errno != ECONNRESET && errno != EBADF) g_critical ("couldn't read from process: %m"); end = TRUE; break; } else if (bytes == 0) { end = TRUE; } else { sz += bytes; written = ssh_channel_write (chan, buf, bytes); if (written != bytes) g_assert_not_reached (); } } while (bytes == ws); } if ((revents & POLLOUT)) { if (state.buffer->len > 0) { written = write (fd, state.buffer->data, state.buffer->len); if (written < 0 && errno != EAGAIN) g_critical ("couldn't write: %s", g_strerror (errno)); if (written > 0) g_byte_array_remove_range (state.buffer, 0, written); } if (state.buffer_eof && state.buffer->len == 0) { if (shutdown (fd, SHUT_WR) < 0) { if (errno != EAGAIN && errno != EBADF) g_critical ("couldn't shutdown: %s", g_strerror (errno)); } else { state.buffer_eof = FALSE; } } } if (end || (revents & (POLLHUP | POLLERR | POLLNVAL))) { ssh_channel_send_eof (chan); pid = waitpid (state.childpid, &status, 0); if (pid < 0) { g_critical ("couldn't wait on child process: %m"); } else { if (WIFSIGNALED (status)) ssh_channel_request_send_exit_signal (chan, strsignal (WTERMSIG (status)), 0, "", ""); else ssh_channel_request_send_exit_status (chan, WEXITSTATUS (status)); } ret = ssh_blocking_flush (state.session, -1); if (ret != SSH_OK && ret != SSH_CLOSED) g_message ("ssh_blocking_flush() failed: %d", ret); ssh_channel_close (chan); ssh_channel_free (chan); ret = ssh_blocking_flush (state.session, -1); if (ret != SSH_OK && ret != SSH_CLOSED) g_message ("ssh_blocking_flush() failed: %d", ret); state.channel = NULL; ssh_event_remove_fd (state.event, fd); sz = -1; } return sz; }
static int pkd_exec_hello(int fd, struct pkd_daemon_args *args) { int rc = -1; ssh_bind b = NULL; ssh_session s = NULL; ssh_event e = NULL; ssh_channel c = NULL; enum ssh_bind_options_e opts = -1; int level = args->opts.libssh_log_level; enum pkd_hostkey_type_e type = args->type; const char *hostkeypath = args->hostkeypath; pkd_state.eof_received = 0; pkd_state.close_received = 0; pkd_state.req_exec_received = 0; b = ssh_bind_new(); if (b == NULL) { pkderr("ssh_bind_new\n"); goto outclose; } if (type == PKD_RSA) { opts = SSH_BIND_OPTIONS_RSAKEY; } else if (type == PKD_ED25519) { opts = SSH_BIND_OPTIONS_HOSTKEY; #ifdef HAVE_DSA } else if (type == PKD_DSA) { opts = SSH_BIND_OPTIONS_DSAKEY; #endif } else if (type == PKD_ECDSA) { opts = SSH_BIND_OPTIONS_ECDSAKEY; } else { pkderr("unknown kex algorithm: %d\n", type); rc = -1; goto outclose; } rc = ssh_bind_options_set(b, opts, hostkeypath); if (rc != 0) { pkderr("ssh_bind_options_set: %s\n", ssh_get_error(b)); goto outclose; } rc = ssh_bind_options_set(b, SSH_BIND_OPTIONS_LOG_VERBOSITY, &level); if (rc != 0) { pkderr("ssh_bind_options_set log verbosity: %s\n", ssh_get_error(b)); goto outclose; } s = ssh_new(); if (s == NULL) { pkderr("ssh_new\n"); goto outclose; } /* * ssh_bind_accept loads host key as side-effect. If this * succeeds, the given 'fd' will be closed upon 'ssh_free(s)'. */ rc = ssh_bind_accept_fd(b, s, fd); if (rc != SSH_OK) { pkderr("ssh_bind_accept_fd: %s\n", ssh_get_error(b)); goto outclose; } /* accept only publickey-based auth */ ssh_set_auth_methods(s, SSH_AUTH_METHOD_PUBLICKEY); /* initialize callbacks */ ssh_callbacks_init(&pkd_server_cb); pkd_server_cb.userdata = &c; rc = ssh_set_server_callbacks(s, &pkd_server_cb); if (rc != SSH_OK) { pkderr("ssh_set_server_callbacks: %s\n", ssh_get_error(s)); goto out; } /* first do key exchange */ rc = ssh_handle_key_exchange(s); if (rc != SSH_OK) { pkderr("ssh_handle_key_exchange: %s\n", ssh_get_error(s)); goto out; } /* setup and pump event to carry out exec channel */ e = ssh_event_new(); if (e == NULL) { pkderr("ssh_event_new\n"); goto out; } rc = ssh_event_add_session(e, s); if (rc != SSH_OK) { pkderr("ssh_event_add_session\n"); goto out; } /* poll until exec channel established */ while ((ctx.keep_going != 0) && (rc != SSH_ERROR) && (pkd_state.req_exec_received == 0)) { rc = ssh_event_dopoll(e, -1 /* infinite timeout */); } if (rc == SSH_ERROR) { pkderr("ssh_event_dopoll\n"); goto out; } else if (c == NULL) { pkderr("poll loop exited but exec channel not ready\n"); rc = -1; goto out; } rc = ssh_channel_write(c, "hello\n", 6); /* XXX: customizable payloads */ if (rc != 6) { pkderr("ssh_channel_write partial (%d)\n", rc); } rc = ssh_channel_request_send_exit_status(c, 0); if (rc != SSH_OK) { pkderr("ssh_channel_request_send_exit_status: %s\n", ssh_get_error(s)); goto out; } rc = ssh_channel_send_eof(c); if (rc != SSH_OK) { pkderr("ssh_channel_send_eof: %s\n", ssh_get_error(s)); goto out; } rc = ssh_channel_close(c); if (rc != SSH_OK) { pkderr("ssh_channel_close: %s\n", ssh_get_error(s)); goto out; } while ((ctx.keep_going != 0) && (pkd_state.eof_received == 0) && (pkd_state.close_received == 0)) { rc = ssh_event_dopoll(e, 1000 /* milliseconds */); if (rc == SSH_ERROR) { /* log, but don't consider this fatal */ pkdout("ssh_event_dopoll for eof + close: %s\n", ssh_get_error(s)); rc = 0; break; } else { rc = 0; } } while ((ctx.keep_going != 0) && (ssh_is_connected(s))) { rc = ssh_event_dopoll(e, 1000 /* milliseconds */); if (rc == SSH_ERROR) { /* log, but don't consider this fatal */ pkdout("ssh_event_dopoll for session connection: %s\n", ssh_get_error(s)); rc = 0; break; } else { rc = 0; } } goto out; outclose: close(fd); out: if (c != NULL) { ssh_channel_free(c); } if (e != NULL) { ssh_event_remove_session(e, s); ssh_event_free(e); } if (s != NULL) { ssh_disconnect(s); ssh_free(s); } if (b != NULL) { ssh_bind_free(b); } return rc; }
int main(int argc, char **argv) { int verbose = SSH_LOG_PROTOCOL; int port = 22; int rc = 0; char *username = "******"; char *passwd = "2113"; ssh_session my_ssh_session = ssh_new(); if (my_ssh_session == NULL) exit(-1); ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost"); ssh_options_set(my_ssh_session, SSH_OPTIONS_LOG_VERBOSITY, &verbose); ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &port); rc = ssh_connect(my_ssh_session); printf("conn: ok=?%d, %d, %s\n", rc==SSH_OK, rc, ssh_get_error(my_ssh_session)); rc = ssh_userauth_password(my_ssh_session, username, passwd); printf("conn: ok=?%d, %d, %s\n", rc==SSH_OK, rc, ssh_get_error(my_ssh_session)); ssh_channel channel; channel = ssh_channel_new(my_ssh_session); if (channel == NULL) { } rc = ssh_channel_open_session(channel); printf("conn: ok=?%d, %d, %s\n", rc==SSH_OK, rc, ssh_get_error(my_ssh_session)); rc = ssh_channel_request_exec(channel, "ls -lh"); printf("conn: ok=?%d, %d, %s\n", rc==SSH_OK, rc, ssh_get_error(my_ssh_session)); char buffer[100]; unsigned int nbytes; nbytes = ssh_channel_read(channel, buffer, sizeof(buffer)-1, 0); buffer[nbytes] = '\0'; printf("ssh out byte: %d, %s\n", nbytes, buffer); while (nbytes > 0) { nbytes = ssh_channel_read(channel, buffer, sizeof(buffer)-1, 0); buffer[nbytes] = '\0'; printf("ssh out byte: %d, %s\n", nbytes, buffer); } nbytes = ssh_channel_read(channel, buffer, sizeof(buffer)-1, 1); buffer[nbytes] = '\0'; printf("ssh err byte: %d, %s\n", nbytes, buffer); while (nbytes > 0) { nbytes = ssh_channel_read(channel, buffer, sizeof(buffer)-1, 1); buffer[nbytes] = '\0'; printf("ssh err byte: %d, %s\n", nbytes, buffer); } ssh_channel_send_eof(channel); ssh_channel_close(channel); ssh_channel_free(channel); ssh_disconnect(my_ssh_session); ssh_free(my_ssh_session); return 0; }
void close_channel() { ssh_channel_close(channel); }