ssh

package
v0.3.0-rc.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 7, 2014 License: Apache-2.0, BSD-3-Clause Imports: 37 Imported by: 0

Documentation

Overview

Package ssh implements an SSH client and server.

SSH is a transport security protocol, an authentication protocol and a family of application protocols. The most typical application level protocol is a remote shell and this is specifically implemented. However, the multiplexed nature of SSH is exposed to users that wish to support others.

References:

[PROTOCOL.certkeys]: http://www.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys
[SSH-PARAMETERS]:    http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1

Index

Examples

Constants

View Source
const (
	CertAlgoRSAv01      = "ssh-rsa-cert-v01@openssh.com"
	CertAlgoDSAv01      = "ssh-dss-cert-v01@openssh.com"
	CertAlgoECDSA256v01 = "ecdsa-sha2-nistp256-cert-v01@openssh.com"
	CertAlgoECDSA384v01 = "ecdsa-sha2-nistp384-cert-v01@openssh.com"
	CertAlgoECDSA521v01 = "ecdsa-sha2-nistp521-cert-v01@openssh.com"
)

These constants from [PROTOCOL.certkeys] represent the algorithm names for certificate types supported by this package.

View Source
const (
	UserCert = 1
	HostCert = 2
)

Certificate types distinguish between host and user certificates. The values can be set in the CertType field of Certificate.

View Source
const (
	KeyAlgoRSA      = "ssh-rsa"
	KeyAlgoDSA      = "ssh-dss"
	KeyAlgoECDSA256 = "ecdsa-sha2-nistp256"
	KeyAlgoECDSA384 = "ecdsa-sha2-nistp384"
	KeyAlgoECDSA521 = "ecdsa-sha2-nistp521"
)

These constants represent the algorithm names for key types supported by this package.

View Source
const (
	VINTR         = 1
	VQUIT         = 2
	VERASE        = 3
	VKILL         = 4
	VEOF          = 5
	VEOL          = 6
	VEOL2         = 7
	VSTART        = 8
	VSTOP         = 9
	VSUSP         = 10
	VDSUSP        = 11
	VREPRINT      = 12
	VWERASE       = 13
	VLNEXT        = 14
	VFLUSH        = 15
	VSWTCH        = 16
	VSTATUS       = 17
	VDISCARD      = 18
	IGNPAR        = 30
	PARMRK        = 31
	INPCK         = 32
	ISTRIP        = 33
	INLCR         = 34
	IGNCR         = 35
	ICRNL         = 36
	IUCLC         = 37
	IXON          = 38
	IXANY         = 39
	IXOFF         = 40
	IMAXBEL       = 41
	ISIG          = 50
	ICANON        = 51
	XCASE         = 52
	ECHO          = 53
	ECHOE         = 54
	ECHOK         = 55
	ECHONL        = 56
	NOFLSH        = 57
	TOSTOP        = 58
	IEXTEN        = 59
	ECHOCTL       = 60
	ECHOKE        = 61
	PENDIN        = 62
	OPOST         = 70
	OLCUC         = 71
	ONLCR         = 72
	OCRNL         = 73
	ONOCR         = 74
	ONLRET        = 75
	CS7           = 90
	CS8           = 91
	PARENB        = 92
	PARODD        = 93
	TTY_OP_ISPEED = 128
	TTY_OP_OSPEED = 129
)

POSIX terminal mode flags as listed in RFC 4254 Section 8.

View Source
const CertTimeInfinity = 1<<64 - 1

CertTimeInfinity can be used for OpenSSHCertV01.ValidBefore for a certificate that does not expire.

Variables

View Source
var DefaultCipherOrder = []string{
	"aes128-ctr", "aes192-ctr", "aes256-ctr",
	"arcfour256", "arcfour128", "aes128-gcm@openssh.com",
}

DefaultCipherOrder specifies a default set of ciphers and a preference order. This is based on OpenSSH's default client preference order, minus algorithms that are not implemented.

View Source
var DefaultMACOrder = []string{"hmac-sha1", "hmac-sha1-96"}

DefaultMACOrder specifies a default set of MAC algorithms and a preference order. This is based on RFC 4253, section 6.4, with the removal of the hmac-md5 variants as they have reached the end of their useful life.

Functions

func DiscardRequests

func DiscardRequests(in <-chan *Request)

DiscardRequests consumes and rejects all requests from the passed-in channel.

func Marshal

func Marshal(msg interface{}) []byte

Marshal serializes the message in msg to SSH wire format. The msg argument should be a struct or pointer to struct. If the first member has the "sshtype" tag set to a number in decimal, that number is prepended to the result. If the last of member has the "ssh" tag set to "rest", its contents are appended to the output.

func MarshalAuthorizedKey

func MarshalAuthorizedKey(key PublicKey) []byte

MarshalAuthorizedKey serializes key for inclusion in an OpenSSH authorized_keys file. The return value ends with newline.

func ParseDSAPrivateKey

func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error)

ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as specified by the OpenSSL DSA man page.

func ParseRawPrivateKey

func ParseRawPrivateKey(pemBytes []byte) (interface{}, error)

ParseRawPrivateKey returns a private key from a PEM encoded private key. It supports RSA (PKCS#1), DSA (OpenSSL), and ECDSA private keys.

func Unmarshal

func Unmarshal(data []byte, out interface{}) error

Unmarshal parses data in SSH wire format into a structure. The out argument should be a pointer to struct. If the first member of the struct has the "sshtype" tag set to a number in decimal, the packet must start that number. In case of error, Unmarshal returns a ParseError or UnexpectedMessageError.

Types

type AuthMethod

type AuthMethod interface {
	// contains filtered or unexported methods
}

An AuthMethod represents an instance of an RFC 4252 authentication method.

func KeyboardInteractive

func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod

KeyboardInteractive returns a AuthMethod using a prompt/response sequence controlled by the server.

func Password

func Password(secret string) AuthMethod

Password returns an AuthMethod using the given password.

func PasswordCallback

func PasswordCallback(prompt func() (secret string, err error)) AuthMethod

PasswordCallback returns an AuthMethod that uses a callback for fetching a password.

func PublicKeys

func PublicKeys(signers ...Signer) AuthMethod

PublicKeys returns an AuthMethod that uses the given key pairs.

func PublicKeysCallback

func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod

PublicKeysCallback returns an AuthMethod that runs the given function to obtain a list of key pairs.

type CertChecker

type CertChecker struct {
	// SupportedCriticalOptions lists the CriticalOptions that the
	// server application layer understands. These are only used
	// for user certificates.
	SupportedCriticalOptions []string

	// IsAuthority should return true if the key is recognized as
	// an authority. This allows for certificates to be signed by other
	// certificates.
	IsAuthority func(auth PublicKey) bool

	// Clock is used for verifying time stamps. If unset, time.Now
	// is used.
	Clock func() time.Time

	// UserKeyFallback is the fallback for non-certificate
	// user keys. If it is nil, non-certificate keys are rejected.
	UserKeyFallback func(conn ConnMetadata, key PublicKey) (*Permissions, error)

	// HostKeyFallback is the fallback for non-certificate host
	// keys.  If it is nil, non-certificate keys are rejected.
	HostKeyFallback func(addr string, remote net.Addr, key PublicKey) error

	// IsRevoked should indicate if the key has been revoked. If
	// unset, no keys are considered revoked.
	IsRevoked func(cert *Certificate) bool
}

CertChecker does the work of verifying a certificate. Its methods can be plugged into ClientConfig.HostKeyCallback and ServerConfig.PublicKeyCallback. For the CertChecker to work, minimally, the IsAuthority callback should be set.

func (*CertChecker) Authenticate

func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permissions, error)

Authenticate checks a user certificate. Authenticate can be used as a value for ServerConfig.PublicKeyCallback.

func (*CertChecker) CheckCert

func (c *CertChecker) CheckCert(principal string, cert *Certificate) error

CheckCert checks CriticalOptions, ValidPrincipals, revocation, timestamp and signature of the certificate.

func (*CertChecker) CheckHostKey

func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey) error

CheckHostKey checks a host key certificate. This method can be plugged into ClientConfig.HostKeyCallback.

type Certificate

type Certificate struct {
	Nonce           []byte
	Key             PublicKey
	Serial          uint64
	CertType        uint32
	KeyId           string
	ValidPrincipals []string
	ValidAfter      uint64
	ValidBefore     uint64
	Permissions
	Reserved     []byte
	SignatureKey PublicKey
	Signature    *Signature
}

An Certificate represents an OpenSSH certificate as defined in [PROTOCOL.certkeys]?rev=1.8.

func (*Certificate) Marshal

func (c *Certificate) Marshal() []byte

Marshal serializes the certificate. It is part of the PublicKey interface.

func (*Certificate) SignCert

func (c *Certificate) SignCert(authority Signer) error

SignCert sets the SignatureKey to the authority's public key, and stores a Signature by the authority in the certificate.

func (*Certificate) Type

func (c *Certificate) Type() string

Type returns the key name. It is part of the PublicKey interface.

func (*Certificate) Verify

func (c *Certificate) Verify(data []byte, sig *Signature) error

Verify verifies a signature against the certificate's public key. It is part of the PublicKey interface.

type Channel

type Channel interface {
	// Read reads up to len(data) bytes from the channel.
	Read(data []byte) (int, error)

	// Write writes len(data) bytes to the channel.
	Write(data []byte) (int, error)

	// Signals end of channel use. No data may be sent after this
	// call.
	Close() error

	// CloseWrite signals the end of sending in-band
	// data. Requests may still be sent, and the other side may
	// still send data
	CloseWrite() error

	// SendRequest sends a channel request.  If wantReply is true,
	// it will wait for a reply and return the result as a
	// boolean, otherwise the return value will be false. Channel
	// requests are out-of-band messages, so they may be sent even
	// if the data stream is closed or blocked by flow control.
	SendRequest(name string, wantReply bool, payload []byte) (bool, error)

	// Stderr returns an io.ReadWriter that writes to this channel with the
	// extended data type set to stderr.
	Stderr() io.ReadWriter
}

A Channel is an ordered, reliable, flow-controlled, duplex stream that is multiplexed over an SSH connection.

type Client

type Client struct {
	Conn
	// contains filtered or unexported fields
}

Client implements a traditional SSH client supporting shells, subprocesses, port forwarding and tunneled dialing.

func Dial

func Dial(network, addr string, config *ClientConfig) (*Client, error)

Dial starts a client connecting to the given SSH server. It is a convenience function that connects to the given network address, initiates the SSH handshake, and then sets up a Client. For access to incoming channels and requests, use net.Dial with NewClientConn instead.

Example
// An SSH client is represented with a ClientConn. Currently only
// the "password" authentication method is supported.
//
// To authenticate with the remote server you must pass at least one
// implementation of AuthMethod via the Auth field in ClientConfig.
config := &ClientConfig{
	User: "username",
	Auth: []AuthMethod{
		Password("yourpassword"),
	},
}
client, err := Dial("tcp", "yourserver.com:22", config)
if err != nil {
	panic("Failed to dial: " + err.Error())
}

// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := client.NewSession()
if err != nil {
	panic("Failed to create session: " + err.Error())
}
defer session.Close()

// Once a Session is created, you can execute a single command on
// the remote side using the Run method.
var b bytes.Buffer
session.Stdout = &b
if err := session.Run("/usr/bin/whoami"); err != nil {
	panic("Failed to run: " + err.Error())
}
fmt.Println(b.String())
Output:

func NewClient

func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client

NewClient creates a Client on top of the given connection.

func (*Client) Dial

func (c *Client) Dial(n, addr string) (net.Conn, error)

Dial initiates a connection to the addr from the remote host. The resulting connection has a zero LocalAddr() and RemoteAddr().

func (*Client) DialTCP

func (c *Client) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error)

DialTCP connects to the remote address raddr on the network net, which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used as the local address for the connection.

func (*Client) HandleChannelOpen

func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel

HandleChannelOpen returns a channel on which NewChannel requests for the given type are sent. If the type already is being handled, nil is returned. The channel is closed when the connection is closed.

func (*Client) Listen

func (c *Client) Listen(n, addr string) (net.Listener, error)

Listen requests the remote peer open a listening socket on addr. Incoming connections will be available by calling Accept on the returned net.Listener.

Example
config := &ClientConfig{
	User: "username",
	Auth: []AuthMethod{
		Password("password"),
	},
}
// Dial your ssh server.
conn, err := Dial("tcp", "localhost:22", config)
if err != nil {
	log.Fatalf("unable to connect: %s", err)
}
defer conn.Close()

// Request the remote side to open port 8080 on all interfaces.
l, err := conn.Listen("tcp", "0.0.0.0:8080")
if err != nil {
	log.Fatalf("unable to register tcp forward: %v", err)
}
defer l.Close()

// Serve HTTP with your SSH server acting as a reverse proxy.
http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(resp, "Hello world!\n")
}))
Output:

func (*Client) ListenTCP

func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error)

ListenTCP requests the remote peer open a listening socket on laddr. Incoming connections will be available by calling Accept on the returned net.Listener.

func (*Client) NewSession

func (c *Client) NewSession() (*Session, error)

NewSession opens a new Session for this client.

type ClientConfig

type ClientConfig struct {
	// Shared configuration.
	Config

	// The username to authenticate.
	User string

	// A slice of AuthMethod instances. Only the first
	// instance of a particular RFC 4252 method will be used
	// during authentication.
	Auth []AuthMethod

	// HostKeyCallback, if not nil, is called during the cryptographic
	// handshake to validate the server's host key. A nil HostKeyCallback
	// implies that all host keys are accepted.
	HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error

	// The identification string that will be used for the connection.
	// If empty, a reasonable default is used.
	ClientVersion string
}

A ClientConfig structure is used to configure a Client. After one has been passed to an SSH function it must not be modified.

type Config

type Config struct {
	// Rand provides the source of entropy for cryptographic
	// primitives. If Rand is nil, the cryptographic random reader
	// in package crypto/rand will be used.
	Rand io.Reader

	// The maximum number of bytes sent or received after which a
	// new key is negotiated. It must be at least 256. If
	// unspecified, 1 gigabyte is used.
	RekeyThreshold uint64

	// The allowed key exchanges algorithms. If unspecified then a
	// default set of algorithms is used.
	KeyExchanges []string

	// The allowed cipher algorithms. If unspecified then DefaultCipherOrder is
	// used.
	Ciphers []string

	// The allowed MAC algorithms. If unspecified then DefaultMACOrder is used.
	MACs []string
}

Config contains configuration data common to both ServerConfig and ClientConfig.

type Conn

type Conn interface {
	ConnMetadata

	// SendRequest sends a global request, and returns the
	// reply. If wantReply is true, it returns the response status
	// and payload. See also RFC4254, section 4.
	SendRequest(name string, wantReply bool, payload []byte) (bool, []byte, error)

	// OpenChannel tries to open an channel. If the request is
	// rejected, it returns *OpenChannelError. On success, returns
	// the SSH Channel, and a Go channel for incoming out-of-band
	// requests. The Go channel must be serviced, or the
	// connection will hang.
	OpenChannel(name string, data []byte) (Channel, <-chan *Request, error)

	// Close closes the underlying network connection
	Close() error

	// Wait blocks until the connection has shut down, and returns the
	// error causing the shutdown.
	Wait() error
}

Conn represents an SSH connection for both server and client roles. The Conn is the basis for implementing an application layer, such as ClientConn, which implements the traditional shell access for clients.

func NewClientConn

func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error)

NewClientConn establishes an authenticated SSH connection using c as the underlying transport. The Request and NewChannel channels must be serviced, or the connection will hang.

type ConnMetadata

type ConnMetadata interface {
	// User returns the user ID for this connection.
	// It is empty if no authentication is used.
	User() string

	// SessionID returns the sesson hash, also denoted by H.
	SessionID() []byte

	// ClientVersion returns the client's version string as hashed
	// into the session ID.
	ClientVersion() []byte

	// ServerVersion returns the client's version string as hashed
	// into the session ID.
	ServerVersion() []byte

	// RemoteAddr returns the remote address for this connection.
	RemoteAddr() net.Addr

	// LocalAddr returns the local address for this connection.
	LocalAddr() net.Addr
}

ConnMetadata holds metadata for the connection.

type ExitError

type ExitError struct {
	Waitmsg
}

An ExitError reports unsuccessful completion of a remote command.

func (*ExitError) Error

func (e *ExitError) Error() string

type KeyboardInteractiveChallenge

type KeyboardInteractiveChallenge func(user, instruction string, questions []string, echos []bool) (answers []string, err error)

KeyboardInteractiveChallenge should print questions, optionally disabling echoing (e.g. for passwords), and return all the answers. Challenge may be called multiple times in a single session. After successful authentication, the server may send a challenge with no questions, for which the user and instruction messages should be printed. RFC 4256 section 3.3 details how the UI should behave for both CLI and GUI environments.

type NewChannel

type NewChannel interface {
	// Accept accepts the channel creation request. It returns the
	// Channel and the side-channel for requests. The side-channel
	// must be serviced.
	Accept() (Channel, <-chan *Request, error)

	// Reject rejects the channel creation request. After calling
	// this, no other methods on the Channel may be called.
	Reject(reason RejectionReason, message string) error

	// ChannelType returns the type of the channel, as supplied by the
	// client.
	ChannelType() string

	// ExtraData returns the arbitrary payload for this channel, as supplied
	// by the client. This data is specific to the channel type.
	ExtraData() []byte
}

NewChannel is an incoming request to a channel. It must either be accepted for use with the Accept method or rejected with Reject.

type OpenChannelError

type OpenChannelError struct {
	Reason  RejectionReason
	Message string
}

OpenChannelError is returned if the other side rejects an OpenChannel request.

func (*OpenChannelError) Error

func (e *OpenChannelError) Error() string

type Permissions

type Permissions struct {
	// Critical options restrict default permissions. Common
	// restrictions are "source-address" and "force-command". If
	// the server cannot enforce the restriction, or does not
	// recognize it, the user should not authenticate.
	CriticalOptions map[string]string

	// Extensions are extra functionality that the server may
	// offer on authenticated connections. Common extensions are
	// "permit-agent-forwarding", "permit-X11-forwarding". Lack of
	// support for an extension does not preclude authenticating a
	// user.
	Extensions map[string]string
}

The Permissions type holds fine-grained permissions that are specific to a user or a specific authentication method for a user. Permissions, except for "source-address", must be enforced in the server application layer, after successful authentication. The Permissions are passed on in ServerConn so a server implementation can honor them.

type PublicKey

type PublicKey interface {
	// Type returns the key's type, e.g. "ssh-rsa".
	Type() string

	// Marshal returns the serialized key data in SSH wire format,
	// with the name prefix.
	Marshal() []byte

	// Verify that sig is a signature on the given data using this
	// key. This function will hash the data appropriately first.
	Verify(data []byte, sig *Signature) error
}

PublicKey is an abstraction of different types of public keys.

func NewPublicKey

func NewPublicKey(k interface{}) (PublicKey, error)

NewPublicKey takes a pointer to rsa, dsa or ecdsa PublicKey and returns a corresponding ssh PublicKey instance. EC keys should use P256, P384 or P521.

func ParseAuthorizedKey

func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error)

ParseAuthorizedKeys parses a public key from an authorized_keys file used in OpenSSH according to the sshd(8) manual page.

func ParsePublicKey

func ParsePublicKey(in []byte) (out PublicKey, err error)

ParsePublicKey parses an SSH public key formatted for use in the SSH wire protocol according to RFC 4253, section 6.6.

type RejectionReason

type RejectionReason uint32

RejectionReason is an enumeration used when rejecting channel creation requests. See RFC 4254, section 5.1.

const (
	Prohibited RejectionReason = iota + 1
	ConnectionFailed
	UnknownChannelType
	ResourceShortage
)

func (RejectionReason) String

func (r RejectionReason) String() string

String converts the rejection reason to human readable form.

type Request

type Request struct {
	Type      string
	WantReply bool
	Payload   []byte
	// contains filtered or unexported fields
}

Request is a request sent outside of the normal stream of data. Requests can either be specific to an SSH channel, or they can be global.

func (*Request) Reply

func (r *Request) Reply(ok bool, payload []byte) error

Reply sends a message back to the request. It should be called for all requests that have WantReply set. The payload argument is ignored for channel specific requests

type ServerConfig

type ServerConfig struct {
	// Shared configuration.
	Config

	// NoClientAuth is true if clients are allowed to connect without
	// authenticating.
	NoClientAuth bool

	// PasswordCallback, if non-nil, is called when a user
	// attempts to authenticate using a password.
	PasswordCallback func(conn ConnMetadata, password []byte) (*Permissions, error)

	// PublicKeyCallback, if non-nil, is called when a client attempts public
	// key authentication. It must return true if the given public key is
	// valid for the given user.
	PublicKeyCallback func(conn ConnMetadata, key PublicKey) (*Permissions, error)

	// KeyboardInteractiveCallback, if non-nil, is called when
	// keyboard-interactive authentication is selected (RFC
	// 4256). The client object's Challenge function should be
	// used to query the user. The callback may offer multiple
	// Challenge rounds. To avoid information leaks, the client
	// should be presented a challenge even if the user is
	// unknown.
	KeyboardInteractiveCallback func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error)

	// If set, all authentication attempts are logged with this method.
	AuthLogCallback func(conn ConnMetadata, method string, err error)
	// contains filtered or unexported fields
}

ServerConfig holds server specific configuration data.

func (*ServerConfig) AddHostKey

func (s *ServerConfig) AddHostKey(key Signer)

AddHostKey adds a private key as a host key. If an existing host key exists with the same algorithm, it is overwritten. Each server config must have at least one host key.

type ServerConn

type ServerConn struct {
	Conn

	// If the succeeding authentication callback returned a
	// non-nil Permissions pointer, it is stored here.
	Permissions *Permissions
}

ServerConn is an authenticated SSH connection, as seen from the server

func NewServerConn

func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error)

NewServerConn starts a new SSH server with c as the underlying transport. It starts with a handshake, and if the handshake is unsuccessful, it closes the connection and returns an error. The Request and NewChannel channels must be serviced, or the connection will hang.

Example
// An SSH server is represented by a ServerConfig, which holds
// certificate details and handles authentication of ServerConns.
config := &ServerConfig{
	PasswordCallback: func(c ConnMetadata, pass []byte) (*Permissions, error) {
		// Should use constant-time compare (or better, salt+hash) in
		// a production setting.
		if c.User() == "testuser" && string(pass) == "tiger" {
			return nil, nil
		}
		return nil, fmt.Errorf("password rejected for %q", c.User())
	},
}

privateBytes, err := ioutil.ReadFile("id_rsa")
if err != nil {
	panic("Failed to load private key")
}

private, err := ParsePrivateKey(privateBytes)
if err != nil {
	panic("Failed to parse private key")
}

config.AddHostKey(private)

// Once a ServerConfig has been configured, connections can be
// accepted.
listener, err := net.Listen("tcp", "0.0.0.0:2022")
if err != nil {
	panic("failed to listen for connection")
}
nConn, err := listener.Accept()
if err != nil {
	panic("failed to accept incoming connection")
}

// Before use, a handshake must be performed on the incoming
// net.Conn.
_, chans, reqs, err := NewServerConn(nConn, config)
if err != nil {
	panic("failed to handshake")
}
// The incoming Request channel must be serviced.
go DiscardRequests(reqs)

// Service the incoming Channel channel.
for newChannel := range chans {
	// Channels have a type, depending on the application level
	// protocol intended. In the case of a shell, the type is
	// "session" and ServerShell may be used to present a simple
	// terminal interface.
	if newChannel.ChannelType() != "session" {
		newChannel.Reject(UnknownChannelType, "unknown channel type")
		continue
	}
	channel, requests, err := newChannel.Accept()
	if err != nil {
		panic("could not accept channel.")
	}

	// Sessions have out-of-band requests such as "shell",
	// "pty-req" and "env".  Here we handle only the
	// "shell" request.
	go func(in <-chan *Request) {
		for req := range in {
			ok := false
			switch req.Type {
			case "shell":
				ok = true
				if len(req.Payload) > 0 {
					// We don't accept any
					// commands, only the
					// default shell.
					ok = false
				}
			}
			req.Reply(ok, nil)
		}
	}(requests)

	term := terminal.NewTerminal(channel, "> ")

	go func() {
		defer channel.Close()
		for {
			line, err := term.ReadLine()
			if err != nil {
				break
			}
			fmt.Println(line)
		}
	}()
}
Output:

type Session

type Session struct {
	// Stdin specifies the remote process's standard input.
	// If Stdin is nil, the remote process reads from an empty
	// bytes.Buffer.
	Stdin io.Reader

	// Stdout and Stderr specify the remote process's standard
	// output and error.
	//
	// If either is nil, Run connects the corresponding file
	// descriptor to an instance of ioutil.Discard. There is a
	// fixed amount of buffering that is shared for the two streams.
	// If either blocks it may eventually cause the remote
	// command to block.
	Stdout io.Writer
	Stderr io.Writer
	// contains filtered or unexported fields
}

A Session represents a connection to a remote command or shell.

func (*Session) Close

func (s *Session) Close() error

func (*Session) CombinedOutput

func (s *Session) CombinedOutput(cmd string) ([]byte, error)

CombinedOutput runs cmd on the remote host and returns its combined standard output and standard error.

func (*Session) Output

func (s *Session) Output(cmd string) ([]byte, error)

Output runs cmd on the remote host and returns its standard output.

func (*Session) RequestPty

func (s *Session) RequestPty(term string, h, w int, termmodes TerminalModes) error

RequestPty requests the association of a pty with the session on the remote host.

Example
// Create client config
config := &ClientConfig{
	User: "username",
	Auth: []AuthMethod{
		Password("password"),
	},
}
// Connect to ssh server
conn, err := Dial("tcp", "localhost:22", config)
if err != nil {
	log.Fatalf("unable to connect: %s", err)
}
defer conn.Close()
// Create a session
session, err := conn.NewSession()
if err != nil {
	log.Fatalf("unable to create session: %s", err)
}
defer session.Close()
// Set up terminal modes
modes := TerminalModes{
	ECHO:          0,     // disable echoing
	TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
	TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
// Request pseudo terminal
if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
	log.Fatalf("request for pseudo terminal failed: %s", err)
}
// Start remote shell
if err := session.Shell(); err != nil {
	log.Fatalf("failed to start shell: %s", err)
}
Output:

func (*Session) RequestSubsystem

func (s *Session) RequestSubsystem(subsystem string) error

RequestSubsystem requests the association of a subsystem with the session on the remote host. A subsystem is a predefined command that runs in the background when the ssh session is initiated

func (*Session) Run

func (s *Session) Run(cmd string) error

Run runs cmd on the remote host. Typically, the remote server passes cmd to the shell for interpretation. A Session only accepts one call to Run, Start, Shell, Output, or CombinedOutput.

The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

If the command fails to run or doesn't complete successfully, the error is of type *ExitError. Other error types may be returned for I/O problems.

func (*Session) SendRequest

func (s *Session) SendRequest(name string, wantReply bool, payload []byte) (bool, error)

SendRequest sends an out-of-band channel request on the SSH channel underlying the session.

func (*Session) Setenv

func (s *Session) Setenv(name, value string) error

Setenv sets an environment variable that will be applied to any command executed by Shell or Run.

func (*Session) Shell

func (s *Session) Shell() error

Shell starts a login shell on the remote host. A Session only accepts one call to Run, Start, Shell, Output, or CombinedOutput.

func (*Session) Signal

func (s *Session) Signal(sig Signal) error

Signal sends the given signal to the remote process. sig is one of the SIG* constants.

func (*Session) Start

func (s *Session) Start(cmd string) error

Start runs cmd on the remote host. Typically, the remote server passes cmd to the shell for interpretation. A Session only accepts one call to Run, Start or Shell.

func (*Session) StderrPipe

func (s *Session) StderrPipe() (io.Reader, error)

StderrPipe returns a pipe that will be connected to the remote command's standard error when the command starts. There is a fixed amount of buffering that is shared between stdout and stderr streams. If the StderrPipe reader is not serviced fast enough it may eventually cause the remote command to block.

func (*Session) StdinPipe

func (s *Session) StdinPipe() (io.WriteCloser, error)

StdinPipe returns a pipe that will be connected to the remote command's standard input when the command starts.

func (*Session) StdoutPipe

func (s *Session) StdoutPipe() (io.Reader, error)

StdoutPipe returns a pipe that will be connected to the remote command's standard output when the command starts. There is a fixed amount of buffering that is shared between stdout and stderr streams. If the StdoutPipe reader is not serviced fast enough it may eventually cause the remote command to block.

func (*Session) Wait

func (s *Session) Wait() error

Wait waits for the remote command to exit.

The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

If the command fails to run or doesn't complete successfully, the error is of type *ExitError. Other error types may be returned for I/O problems.

type Signal

type Signal string
const (
	SIGABRT Signal = "ABRT"
	SIGALRM Signal = "ALRM"
	SIGFPE  Signal = "FPE"
	SIGHUP  Signal = "HUP"
	SIGILL  Signal = "ILL"
	SIGINT  Signal = "INT"
	SIGKILL Signal = "KILL"
	SIGPIPE Signal = "PIPE"
	SIGQUIT Signal = "QUIT"
	SIGSEGV Signal = "SEGV"
	SIGTERM Signal = "TERM"
	SIGUSR1 Signal = "USR1"
	SIGUSR2 Signal = "USR2"
)

POSIX signals as listed in RFC 4254 Section 6.10.

type Signature

type Signature struct {
	Format string
	Blob   []byte
}

Signature represents a cryptographic signature.

type Signer

type Signer interface {
	// PublicKey returns an associated PublicKey instance.
	PublicKey() PublicKey

	// Sign returns raw signature for the given data. This method
	// will apply the hash specified for the keytype to the data.
	Sign(rand io.Reader, data []byte) (*Signature, error)
}

A Signer can create signatures that verify against a public key.

func NewCertSigner

func NewCertSigner(cert *Certificate, signer Signer) (Signer, error)

NewCertSigner constructs a Signer whose public key is the given certificate. The public key in cert.Key should be the same as signer.PublicKey().

func NewSignerFromKey

func NewSignerFromKey(k interface{}) (Signer, error)

NewSignerFromKey takes a pointer to rsa, dsa or ecdsa PrivateKey returns a corresponding Signer instance. EC keys should use P256, P384 or P521.

func ParsePrivateKey

func ParsePrivateKey(pemBytes []byte) (Signer, error)

ParsePrivateKey returns a Signer from a PEM encoded private key. It supports the same keys as ParseRawPrivateKey.

type TerminalModes

type TerminalModes map[uint8]uint32

type Waitmsg

type Waitmsg struct {
	// contains filtered or unexported fields
}

Waitmsg stores the information about an exited remote command as reported by Wait.

func (Waitmsg) ExitStatus

func (w Waitmsg) ExitStatus() int

ExitStatus returns the exit status of the remote command.

func (Waitmsg) Lang

func (w Waitmsg) Lang() string

Lang returns the language tag. See RFC 3066

func (Waitmsg) Msg

func (w Waitmsg) Msg() string

Msg returns the exit message given by the remote command

func (Waitmsg) Signal

func (w Waitmsg) Signal() string

Signal returns the exit signal of the remote command if it was terminated violently.

func (Waitmsg) String

func (w Waitmsg) String() string

Directories

Path Synopsis
Package agent implements a client to an ssh-agent daemon.
Package agent implements a client to an ssh-agent daemon.
Package terminal provides support functions for dealing with terminals, as commonly found on UNIX systems.
Package terminal provides support functions for dealing with terminals, as commonly found on UNIX systems.
This package contains integration tests for the github.com/coreos/fleet/third_party/code.google.com/p/gosshnew/ssh package.
This package contains integration tests for the github.com/coreos/fleet/third_party/code.google.com/p/gosshnew/ssh package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL