Is it possible to SSH to another host while in an SSH session in golang? I tried chaining some stuff together like this, but the printout says the remote addr of client 2 is 0.0.0.0 and an error is given when I try to execute anything on an ssh.Session from client2.
host1 := "host1.com"
host2 := "host2.com"
client1, err := ssh.Dial("tcp", host, config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
conn, err := client1.Dial("tcp", host2)
if err != nil {
panic(err)
}
sshConn, newChan, requestChan, err := ssh.NewClientConn(conn, host2, config)
if err != nil {
panic(err)
}
client2 := ssh.NewClient(sshConn, newChan, requestChan)
fmt.Println("Client 2 RemoteAddr():", client2.RemoteAddr())
The problem is that you are running all of this code on the same host. Let's call the host you run your app on host0 for convenience.
You start out making a connection from host0 to host1. That works fine. What you seem to want to do next is make a connection from host1 to host2. To do that you need to run the SSH code on host1. But your app, which is and always has been running on host0, is not in the place to do that.
You will need to put a program on host1 that does the connection to host2 and then send a command down the SSH connection to host1 that will start that program.
Related
I tried to fetch data from a SQL Server database. When I run, it keeps giving me this error:
unable to open tcp connection with host 'localhost:1433': dial tcp [::1]:1433: connectex: No connection could be made because the target machine actively refused it.
exit status 1
My code:
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/denisenkom/go-mssqldb"
)
var kiosk string
var server = ".\\MSSQLSERVER01"
var port = 1433
var user = "DESKTOP-37624KK"
var password = "**********"
var database = "Kiosk"
func main() {
connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s", server, user, password, port, database)
db, err := sql.Open("mssql", connString)
if err != nil {
fmt.Println("Error in connect DB")
log.Fatal(err)
}
rows, err := db.Query("SELECT * FROM Kiosk")
if err != nil {
log.Fatal(err)
}
for rows.Next() {
if err := rows.Scan(&kiosk); err != nil {
log.Fatal(err)
}
fmt.Println(kiosk)
}
defer rows.Close()
}
Checked if firewall is blocking needed port
Tried to change and connect to new ports
Tried to search on the internet for other solutions. Nothing has helped yet
The server variable value is wrong. The dot (.) means "localhost". If the SQL server is installed locally just use "." (or ".\InstanceName" - if there are multiple instances installed). If the server is installed in the network just use SERVERNAME (without the leading backslashes), or SERVERNAME\InstanceName.
What I'm trying to do:
Build a package (later usage) that provides a method to execute a get-request to any page through a given socks5 proxy.
My problem:
When ever I try to request a page with SSL (https) I get the following error:
Error executing request Get https://www.xxxxxxx.com: socks connect tcp 83.234.8.214:4145->www.xxxxxxx.com:443: EOF
However requesting http://www.google.com is working fine. So there must be a problem with the SSL connection. Can't imagine why this isn't working as I'm not very experienced with SSL-connections. End of file makes no sense to me.
My current code:
func main() {
// public socks5 - worked when I created this question
proxy_addr := "83.234.8.214:4145"
// With this address I get the error
web_addr := "https://www.whatismyip.com"
// Requesting google works fine
//web_addr := "http://www.google.com"
dialer, err := proxy.SOCKS5("tcp", proxy_addr, nil, proxy.Direct)
handleError(err, "error creating dialer")
httpTransport := &http.Transport{}
httpClient := &http.Client{Transport: httpTransport}
httpTransport.DialTLS = dialer.Dial
req, err := http.NewRequest("GET", web_addr, nil)
handleError(err, "error creating request")
httpClient.Timeout = 5 * time.Second
resp, err := httpClient.Do(req)
handleError(err, "error executing request")
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
handleError(err, "error reading body")
fmt.Println(string(b))
}
func handleError(err error, msg string) {
if err != nil {
log.Fatal(err)
}
}
So what am I missing in here to deal with ssl-connections?
Thank you very much.
Edit 1:
In case someone would think this is an issue with whatismyip.com I've done some more tests:
https://www.google.com
EOF error
https://stackoverflow.com
EOF error
https://www.youtube.com/
EOF error
Connection between your program and your socks5 proxy goes not through SSL/TLS
So you should change line
httpTransport.DialTLS = dialer.Dial
to
httpTransport.Dial = dialer.Dial
I checked https://www.whatismyip.com and https://www.google.com.
URLs are downloaded fine.
For test I set up 3proxy service on my server, test your code with fixed line and check 3proxy logs.
All made requests was in proxy server logs.
If you need more help - please let me know, I'll help
Things to notice:
Socks5 proxies need to support SSL connections.
The code from the question won't work with this answer as the proxy (used in the code) isn't supporting SSL connections.
I'm creating a Go TCP server (NOT http/s) and I'm trying to configure it to use SSL. I have a StartCom free SSL certificate which I am trying to use to accomplish this. My server code looks like this:
cert, err := tls.LoadX509KeyPair("example.com.pem", "example.com.key")
if err != nil {
fmt.Println("Error loading certificate. ",err)
}
trustCert, err := ioutil.ReadFile("sub.class1.server.ca.pem")
if err != nil {
fmt.Println("Error loading trust certificate. ",err)
}
validationCert, err := ioutil.ReadFile("ca.pem")
if err != nil {
fmt.Println("Error loading validation certificate. ",err)
}
certs := x509.NewCertPool()
if !certs.AppendCertsFromPEM(validationCert) {
fmt.Println("Error installing validation certificate.")
}
if !certs.AppendCertsFromPEM(trustCert) {
fmt.Println("Error installing trust certificate.")
}
sslConfig := tls.Config{RootCAs: certs,Certificates: []tls.Certificate{cert}}
service := ":5555"
tcpAddr, error := net.ResolveTCPAddr("tcp", service)
if error != nil {
fmt.Println("Error: Could not resolve address")
} else {
netListen, error := tls.Listen(tcpAddr.Network(), tcpAddr.String(), &sslConfig)
if error != nil {
fmt.Println(error)
} else {
defer netListen.Close()
for {
fmt.Println("Waiting for clients")
connection, error := netListen.Accept()
I've tried switching around the order of the certs, not including some certs, etc. but the output from openssl s_client -CApath /etc/ssl/certs/ -connect localhost:5555 remains essentially the same, verify error:num=20:unable to get local issuer certificate. See here for full output. I seem to be doing something wrong with the intermediate certificates, but I have no idea what. I have been working on this for a few days, lots of googling and SO'ing, but nothing seemed to quite fit my situation. I have set up many certificates in Apache and HAProxy, but this really has me stumped.
The RootCAs field is for clients verifying server certificates. I assume you only want to present a cert for verification, so anything you need should be loaded into the Certificates slice.
Here is a minimal example:
cert, err := tls.LoadX509KeyPair("example.com.pem", "example.com.key")
if err != nil {
log.Fatal("Error loading certificate. ", err)
}
tlsCfg := &tls.Config{Certificates: []tls.Certificate{cert}}
listener, err := tls.Listen("tcp4", "127.0.0.1:5555", tlsCfg)
if err != nil {
log.Fatal(err)
}
defer listener.Close()
for {
log.Println("Waiting for clients")
conn, err := listener.Accept()
if err != nil {
log.Fatal(err)
}
go handle(conn)
}
Even though you're not using HTTPS, it may still be useful to walk through the server setup starting at http.ListenAndServeTLS.
I'm trying to work out the mechanism to fork/start a ssh terminal session
i.e I want to be logged into remote server (my keys are on server) if I execute this program.
Right now it just executes but nothing happens.
package main
import (
"os/exec"
"os"
)
func main() {
cmd := exec.Command("ssh","root#SERVER-IP")
cmd.Stdout = os.Stdout
//cmd.Stderr = os.Stderr
cmd.Run()
}
cmd.Run waits for the command to complete. Your ssh session should (normally) not exit without user interaction. Therefore your program blocks, since it waits for the ssh process to finish.
You may want to either
also redirect Stdin, so you can interact with the ssh session
execute ssh me#server somecommand. In the last form a specific command gets executed and the output of this command gets redirected.
take a look at the ssh package
I've done library that can cover your requiremenets: https://github.com/shagabutdinov/shell; checkout if it helps or not.
You can use this library to start ssh session and execute the commands:
key, err := ssh.ParsePrivateKey([]byte(YOUR_PRIVATE_KEY))
if(err != nil) {
panic(err)
}
shell, err = shell.NewRemote(shell.RemoteConfig{
Host: "root#example.com:22",
Auth: []ssh.AuthMethod{ssh.PublicKeys(key)},
})
if(err != nil) {
panic(err)
}
shell.Run("cat /etc/hostname", func(_ int, message string) {
log.Println(message) // example.com
})
This is simple wrapper over golang ssh library that helps to execute consequent commands over /bin/sh.
I was struggling with and ssh client for golang but was told that the ciphers for the freesshd server was incompatible with the ssh client for Go, so I just installed another one (PowerShell Server) and I can successfully connect to the server.
My problem is not over because I now need to transfer files from local to remote, and this can only be done through scp. I was directed to this scp client for go and have two issues.
I run it and get this:
Where or how can I access the contents of id_rsa needed for privateKey? I just went in my .ssh folder and saw a github_rsa and used that private key, I'm sure that this is not the correct one to use but wouldn't I see some kind of error or invalid private key and not the result above?
The code you were directed to is broken. The example also uses the public key authentication, which is not necessarily your only option. If you can allow password authentication instead, you can make it a bit easier for yourself.
I just made an upload myself by modifying the example you used:
package main
import (
"code.google.com/p/go.crypto/ssh"
"fmt"
)
type password string
func (p password) Password(_ string) (string, error) {
return string(p), nil
}
func main() {
// Dial code is taken from the ssh package example
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.ClientAuth{
ssh.ClientAuthPassword(password("password")),
},
}
client, err := ssh.Dial("tcp", "127.0.0.1:22", config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
session, err := client.NewSession()
if err != nil {
panic("Failed to create session: " + err.Error())
}
defer session.Close()
go func() {
w, _ := session.StdinPipe()
defer w.Close()
content := "123456789\n"
fmt.Fprintln(w, "C0644", len(content), "testfile")
fmt.Fprint(w, content)
fmt.Fprint(w, "\x00")
}()
if err := session.Run("/usr/bin/scp -qrt ./"); err != nil {
panic("Failed to run: " + err.Error())
}
}