go-sshlib: github.com/blacknon/go-sshlib Index | Examples | Files | Directories

package sshlib

import "github.com/blacknon/go-sshlib"

Package sshlib is a library to easily connect with ssh by go. You can perform multiple proxy, x11 forwarding, PKCS11 authentication, etc...

Example simple ssh shell

It is example code. simple connect ssh shell. You can also do tab completion, send sigint signal(Ctrl+C).

package main

import (
	"fmt"
	"os"

	sshlib "github.com/blacknon/go-sshlib"
	"golang.org/x/crypto/ssh"
)

var (
	host     = "target.com"
	port     = "22"
	user     = "user"
	password = "password"

	termlog = "./test_termlog"
)

func main() {
	// Create sshlib.Connect
	con := &sshlib.Connect{
		// If you use x11 forwarding, please set to true.
		ForwardX11: false,

		// If you use ssh-agent forwarding, please set to true.
		// And after, run `con.ConnectSshAgent()`.
		ForwardAgent: false,
	}

	// Create ssh.AuthMethod
	authMethod := sshlib.CreateAuthMethodPassword(password)

	// If you use ssh-agent forwarding, uncomment it.
	// con.ConnectSshAgent()

	// Connect ssh server
	err := con.CreateClient(host, user, port, []ssh.AuthMethod{authMethod})
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// Set terminal log
	con.SetLog(termlog, false)

	// Start ssh shell
	con.Shell()
}

Example simple ssh proxy shell

Multple proxy by ssh connection is also available. Please refer to the sample code for usage with http and socks5 proxy.

package main

import (
	"fmt"
	"os"

	sshlib "github.com/blacknon/go-sshlib"
	"golang.org/x/crypto/ssh"
)

var (
	// Proxy ssh server
	host1     = "proxy.com"
	port1     = "22"
	user1     = "user"
	password1 = "password"

	// Target ssh server
	host2     = "target.com"
	port2     = "22"
	user2     = "user"
	password2 = "password"

	termlog = "./test_termlog"
)

func main() {
	// ==========
	// proxy connect
	// ==========

	// Create proxy sshlib.Connect
	proxyCon := &sshlib.Connect{}

	// Create proxy ssh.AuthMethod
	proxyAuthMethod := sshlib.CreateAuthMethodPassword(password1)

	// Connect proxy server
	err := proxyCon.CreateClient(host1, user1, port1, []ssh.AuthMethod{proxyAuthMethod})
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// ==========
	// target connect
	// ==========

	// Create target sshlib.Connect
	targetCon := &sshlib.Connect{
		ProxyDialer: proxyCon.Client,
	}

	// Create target ssh.AuthMethod
	targetAuthMethod := sshlib.CreateAuthMethodPassword(password2)

	// Connect target server
	err = targetCon.CreateClient(host2, user2, port2, []ssh.AuthMethod{targetAuthMethod})
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// Set terminal log
	targetCon.SetLog(termlog, false)

	// Start ssh shell
	targetCon.Shell()
}

This library was created for my ssh client (https://github.com/blacknon/lssh)

Index

Examples

Package Files

agent.go auth.go cmd.go common.go connect.go doc.go forward.go pkcs11.go proxy.go shell.go

func CreateAuthMethodCertificate Uses

func CreateAuthMethodCertificate(cert string, keySigner ssh.Signer) (auth ssh.AuthMethod, err error)

CreateAuthMethodCertificate returns ssh.AuthMethod generated from Certificate. To generate an AuthMethod from a certificate, you will need the certificate's private key Signer. Signer should be generated from CreateSignerPublicKey() or CreateSignerPKCS11().

func CreateAuthMethodPKCS11 Uses

func CreateAuthMethodPKCS11(provider, pin string) (auth []ssh.AuthMethod, err error)

CreateAuthMethodPKCS11 return []ssh.AuthMethod generated from pkcs11 token. PIN is required to generate a AuthMethod from a PKCS 11 token.

WORNING: Does not work if multiple tokens are stuck at the same time.

func CreateAuthMethodPassword Uses

func CreateAuthMethodPassword(password string) (auth ssh.AuthMethod)

CreateAuthMethodPassword returns ssh.AuthMethod generated from password.

func CreateAuthMethodPublicKey Uses

func CreateAuthMethodPublicKey(key, password string) (auth ssh.AuthMethod, err error)

CreateAuthMethodPublicKey returns ssh.AuthMethod generated from PublicKey. If you have not specified a passphrase, please specify a empty character("").

func CreateSignerAgent Uses

func CreateSignerAgent(sshAgent interface{}) (signers []ssh.Signer, err error)

CreateSignerAgent return []ssh.Signer from ssh-agent. In sshAgent, put agent.Agent or agent.ExtendedAgent.

func CreateSignerCertificate Uses

func CreateSignerCertificate(cert string, keySigner ssh.Signer) (certSigner ssh.Signer, err error)

CreateSignerCertificate returns ssh.Signer generated from Certificate. To generate an AuthMethod from a certificate, you will need the certificate's private key Signer. Signer should be generated from CreateSignerPublicKey() or CreateSignerPKCS11().

func CreateSignerPKCS11 Uses

func CreateSignerPKCS11(provider, pin string) (signers []ssh.Signer, err error)

CreateSignerCertificate returns []ssh.Signer generated from PKCS11 token. PIN is required to generate a Signer from a PKCS 11 token.

WORNING: Does not work if multiple tokens are stuck at the same time.

func CreateSignerPKCS11Prompt Uses

func CreateSignerPKCS11Prompt(provider, pin string) (signers []ssh.Signer, err error)

CreateSignerPKCS11Prompt rapper CreateSignerPKCS11. Output a PIN input prompt if the PIN is not entered or incorrect.

Only Support UNIX-like OS.

func CreateSignerPublicKey Uses

func CreateSignerPublicKey(key, password string) (signer ssh.Signer, err error)

CreateSignerPublicKey returns []ssh.Signer generated from public key. If you have not specified a passphrase, please specify a empty character("").

func CreateSignerPublicKeyData Uses

func CreateSignerPublicKeyData(keyData []byte, password string) (signer ssh.Signer, err error)

func CreateSignerPublicKeyPrompt Uses

func CreateSignerPublicKeyPrompt(key, password string) (signer ssh.Signer, err error)

CreateSignerPublicKeyPrompt rapper CreateSignerPKCS11. Output a passphrase input prompt if the passphrase is not entered or incorrect.

Only Support UNIX-like OS.

func RequestTty Uses

func RequestTty(session *ssh.Session) (err error)

RequestTty requests the association of a pty with the session on the remote host. Terminal size is obtained from the currently connected terminal

type AgentInterface Uses

type AgentInterface interface{}

AgentInterface Interface for storing agent.Agent or agent.ExtendedAgent.

func ConnectSshAgent Uses

func ConnectSshAgent() (ag AgentInterface)

ConnectSshAgent

type Connect Uses

type Connect struct {
    // Client *ssh.Client
    Client *ssh.Client

    // Session
    Session *ssh.Session

    // Session Stdin, Stdout, Stderr...
    Stdin  io.Reader
    Stdout io.Writer
    Stderr io.Writer

    // ProxyDialer
    ProxyDialer proxy.Dialer

    // Connect timeout second.
    ConnectTimeout int

    // SendKeepAliveMax and SendKeepAliveInterval
    SendKeepAliveMax      int
    SendKeepAliveInterval int

    // Session use tty flag.
    TTY bool

    // Forward ssh agent flag.
    ForwardAgent bool

    // ssh-agent interface.
    // agent.Agent or agent.ExtendedAgent
    Agent AgentInterface

    // Forward x11 flag.
    ForwardX11 bool
    // contains filtered or unexported fields
}

Connect structure to store contents about ssh connection.

func (*Connect) AddKeySshAgent Uses

func (c *Connect) AddKeySshAgent(sshAgent interface{}, key interface{})

AddKeySshAgent is rapper agent.Add(). key must be a *rsa.PrivateKey, *dsa.PrivateKey or *ecdsa.PrivateKey, which will be inserted into the agent.

Should use `ssh.ParseRawPrivateKey()` or `ssh.ParseRawPrivateKeyWithPassphrase()`.

func (*Connect) CheckClientAlive Uses

func (c *Connect) CheckClientAlive() error

CheckClientAlive check alive ssh.Client.

func (*Connect) CmdShell Uses

func (c *Connect) CmdShell(session *ssh.Session, command string) (err error)

Shell connect command shell over ssh. Used to start a shell with a specified command.

func (*Connect) Command Uses

func (c *Connect) Command(command string) (err error)

Cmd connect and run command over ssh. Output data is processed by channel because it is executed in parallel. If specification is troublesome, it is good to generate and process session from ssh package.

func (*Connect) CreateClient Uses

func (c *Connect) CreateClient(host, port, user string, authMethods []ssh.AuthMethod) (err error)

CreateClient

func (*Connect) CreateSession Uses

func (c *Connect) CreateSession() (session *ssh.Session, err error)

CreateSession

func (*Connect) ForwardSshAgent Uses

func (c *Connect) ForwardSshAgent(session *ssh.Session)

ForwardAgent forward ssh-agent in session.

func (*Connect) SendKeepAlive Uses

func (c *Connect) SendKeepAlive(session *ssh.Session)

SendKeepAlive send packet to session. TODO(blacknon): Interval及びMaxを設定できるようにする(v0.1.1)

func (*Connect) SetLog Uses

func (c *Connect) SetLog(path string, timestamp bool)

SetLog set up terminal log logging. This only happens in Connect.Shell().

func (*Connect) Shell Uses

func (c *Connect) Shell(session *ssh.Session) (err error)

Shell connect login shell over ssh.

func (*Connect) TCPDynamicForward Uses

func (c *Connect) TCPDynamicForward(address, port string) (err error)

TCPDynamicForward forwarding tcp data. Like Dynamic port forward (ssh -D). listen port Socks5 proxy server.

func (*Connect) TCPLocalForward Uses

func (c *Connect) TCPLocalForward(localAddr, remoteAddr string) (err error)

TCPLocalForward forwarding tcp data. Like Local port forward (ssh -L). localAddr, remoteAddr is write as "address:port".

example) "127.0.0.1:22", "abc.com:9977"

func (*Connect) TCPRemoteForward Uses

func (c *Connect) TCPRemoteForward(localAddr, remoteAddr string) (err error)

TCPRemoteForward forwarding tcp data. Like Remote port forward (ssh -R). localAddr, remoteAddr is write as "address:port".

example) "127.0.0.1:22", "abc.com:9977"

func (*Connect) X11Forward Uses

func (c *Connect) X11Forward(session *ssh.Session) (err error)

X11Forward send x11-req to ssh server and do x11 forwarding. Since the display number of the transfer destination and the PATH of the socket communication file are checked from the local environment variable DISPLAY, this does not work if it is not set.

Also, the value of COOKIE transfers the local value as it is. This will be addressed in the future.

Code:

// Create session
session, err := c.CreateSession()
if err != nil {
    return
}

// X11 forwarding
err = c.X11Forward(session)
if err != nil {
    log.Fatal(err)
}

type NetPipe Uses

type NetPipe struct {
    Command string
}

func (*NetPipe) Dial Uses

func (n *NetPipe) Dial(network, addr string) (con net.Conn, err error)

type PKCS11 Uses

type PKCS11 struct {
    // pkcs11 provider path
    Pkcs11Provider string
    Ctx            *pkcs11.Ctx
    Label          string
    SlotID         uint
    KeyID          map[int][]byte
    PIN            string
    SessionHandle  pkcs11.SessionHandle
}

PKCS11 struct for pkcs11 processing.

func (*PKCS11) CreateCtx Uses

func (p *PKCS11) CreateCtx() (err error)

CreateCtx create and into PKCS11.Ctx. This is the first process to be performed when processing with PKCS11.

func (*PKCS11) GetCryptoSigner Uses

func (p *PKCS11) GetCryptoSigner() (signers []crypto.Signer, err error)

GetCryptoSigner return []crypto.Signer

func (*PKCS11) GetKeyID Uses

func (p *PKCS11) GetKeyID() (err error)

GetKeyID acquire KeyID via PKCS11 and store it in PKCS11 structure.

func (*PKCS11) GetPIN Uses

func (p *PKCS11) GetPIN() (err error)

GetPin prompt for PIN if P11.Pin is blank Only Support UNIX-like OS.

func (*PKCS11) GetTokenLabel Uses

func (p *PKCS11) GetTokenLabel() (err error)

GetTokenLabel get pkcs11 token label. and into PKCS11.Label. Only one token is supported.

func (*PKCS11) RecreateCtx Uses

func (p *PKCS11) RecreateCtx(pkcs11Provider string) (err error)

RecreateCtx exchange PKCS11.Ctx with PIN accessible ctx. Recreate Ctx to access information after PIN entry.

type Proxy Uses

type Proxy struct {
    // Type set proxy type.
    // Can specify `http`, `https`, `socks`, `socks5`, `command`.
    //
    // It is read at the time of specification depending on the type.
    Type string

    // Addr set proxy address.
    //
    Addr string

    // Port set proxy port.
    //
    Port string

    // Port set proxy user.
    //
    User string

    // Port set proxy user.
    //
    Password string

    // Command only use Type `command`.
    //
    Command string

    // Forwarder set Dialer.
    Forwarder proxy.Dialer
}

func (*Proxy) CreateHttpProxyDialer Uses

func (p *Proxy) CreateHttpProxyDialer() (proxyDialer proxy.Dialer, err error)

CreateHttpProxy return proxy.Dialer as http proxy.

func (*Proxy) CreateProxyCommandProxyDialer Uses

func (p *Proxy) CreateProxyCommandProxyDialer() (proxyDialer proxy.Dialer, err error)

CreateProxyCommandProxyDialer as ProxyCommand. When passing ProxyCommand, replace %h, %p and %r etc...

func (*Proxy) CreateProxyDialer Uses

func (p *Proxy) CreateProxyDialer() (proxyDialer proxy.Dialer, err error)

CreateProxyDialer retrun proxy.Dialer.

func (*Proxy) CreateSocks5ProxyDialer Uses

func (p *Proxy) CreateSocks5ProxyDialer() (proxyDialer proxy.Dialer, err error)

CreateSocks5Proxy return proxy.Dialer as Socks5 proxy.

Directories

PathSynopsis
_example

Package sshlib imports 30 packages (graph) and is imported by 2 packages. Updated 2019-10-08. Refresh now. Tools for package owners.