Involved Source Filesbuffer.gocerts.gochannel.gocipher.goclient.goclient_auth.gocommon.goconnection.go
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://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys?rev=HEAD
[SSH-PARAMETERS]: http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1
This package does not fall under the stability promise of the Go language itself,
so its API may be changed when pressing needs arise.
handshake.gokex.gokeys.gomac.gomessages.gomux.goserver.gosession.gossh_gss.gostreamlocal.gotcpip.gotransport.go
Code Examples
package main
import (
"bufio"
"golang.org/x/crypto/ssh"
"log"
"os"
"path/filepath"
"strings"
)
func main() {
// Every client must provide a host key check. Here is a
// simple-minded parse of OpenSSH's known_hosts file
host := "hostname"
file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var hostKey ssh.PublicKey
for scanner.Scan() {
fields := strings.Split(scanner.Text(), " ")
if len(fields) != 3 {
continue
}
if strings.Contains(fields[0], host) {
var err error
hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
if err != nil {
log.Fatalf("error parsing %q: %v", fields[2], err)
}
break
}
}
if hostKey == nil {
log.Fatalf("no hostkey for %s", host)
}
config := ssh.ClientConfig{
User: os.Getenv("USER"),
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
_, err = ssh.Dial("tcp", host+":22", &config)
log.Println(err)
}
package main
import (
"fmt"
"golang.org/x/crypto/ssh"
"log"
"net/http"
)
func main() {
var hostKey ssh.PublicKey
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
// Dial your ssh server.
conn, err := ssh.Dial("tcp", "localhost:22", config)
if err != nil {
log.Fatal("unable to connect: ", 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.Fatal("unable to register tcp forward: ", 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")
}))
}
package main
import (
"bytes"
"fmt"
"golang.org/x/crypto/ssh"
"log"
)
func main() {
var hostKey ssh.PublicKey
// An SSH client is represented with a ClientConn.
//
// To authenticate with the remote server you must pass at least one
// implementation of AuthMethod via the Auth field in ClientConfig,
// and provide a HostKeyCallback.
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("yourpassword"),
},
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
client, err := ssh.Dial("tcp", "yourserver.com:22", config)
if err != nil {
log.Fatal("Failed to dial: ", err)
}
defer client.Close()
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := client.NewSession()
if err != nil {
log.Fatal("Failed to create session: ", err)
}
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 {
log.Fatal("Failed to run: " + err.Error())
}
fmt.Println(b.String())
}
package main
import (
"fmt"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
"io/ioutil"
"log"
"net"
)
func main() {
// Public key authentication is done by comparing
// the public key of a received connection
// with the entries in the authorized_keys file.
authorizedKeysBytes, err := ioutil.ReadFile("authorized_keys")
if err != nil {
log.Fatalf("Failed to load authorized_keys, err: %v", err)
}
authorizedKeysMap := map[string]bool{}
for len(authorizedKeysBytes) > 0 {
pubKey, _, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes)
if err != nil {
log.Fatal(err)
}
authorizedKeysMap[string(pubKey.Marshal())] = true
authorizedKeysBytes = rest
}
// An SSH server is represented by a ServerConfig, which holds
// certificate details and handles authentication of ServerConns.
config := &ssh.ServerConfig{
// Remove to disable password auth.
PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.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())
},
// Remove to disable public key auth.
PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
if authorizedKeysMap[string(pubKey.Marshal())] {
return &ssh.Permissions{
// Record the public key used for authentication.
Extensions: map[string]string{
"pubkey-fp": ssh.FingerprintSHA256(pubKey),
},
}, nil
}
return nil, fmt.Errorf("unknown public key for %q", c.User())
},
}
privateBytes, err := ioutil.ReadFile("id_rsa")
if err != nil {
log.Fatal("Failed to load private key: ", err)
}
private, err := ssh.ParsePrivateKey(privateBytes)
if err != nil {
log.Fatal("Failed to parse private key: ", err)
}
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 {
log.Fatal("failed to listen for connection: ", err)
}
nConn, err := listener.Accept()
if err != nil {
log.Fatal("failed to accept incoming connection: ", err)
}
// Before use, a handshake must be performed on the incoming
// net.Conn.
conn, chans, reqs, err := ssh.NewServerConn(nConn, config)
if err != nil {
log.Fatal("failed to handshake: ", err)
}
log.Printf("logged in with key %s", conn.Permissions.Extensions["pubkey-fp"])
// The incoming Request channel must be serviced.
go ssh.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(ssh.UnknownChannelType, "unknown channel type")
continue
}
channel, requests, err := newChannel.Accept()
if err != nil {
log.Fatalf("Could not accept channel: %v", err)
}
// Sessions have out-of-band requests such as "shell",
// "pty-req" and "env". Here we handle only the
// "shell" request.
go func(in <-chan *ssh.Request) {
for req := range in {
req.Reply(req.Type == "shell", nil)
}
}(requests)
term := terminal.NewTerminal(channel, "> ")
go func() {
defer channel.Close()
for {
line, err := term.ReadLine()
if err != nil {
break
}
fmt.Println(line)
}
}()
}
}
package main
import (
"golang.org/x/crypto/ssh"
"io/ioutil"
"log"
)
func main() {
var hostKey ssh.PublicKey
// A public key may be used to authenticate against the remote
// server by using an unencrypted PEM-encoded private key file.
//
// If you have an encrypted private key, the crypto/x509 package
// can be used to decrypt it.
key, err := ioutil.ReadFile("/home/user/.ssh/id_rsa")
if err != nil {
log.Fatalf("unable to read private key: %v", err)
}
// Create the Signer for this private key.
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
log.Fatalf("unable to parse private key: %v", err)
}
config := &ssh.ClientConfig{
User: "user",
Auth: []ssh.AuthMethod{
// Use the PublicKeys method for remote authentication.
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
// Connect to the remote server and perform the SSH handshake.
client, err := ssh.Dial("tcp", "host.com:22", config)
if err != nil {
log.Fatalf("unable to connect: %v", err)
}
defer client.Close()
}
package main
import (
"golang.org/x/crypto/ssh"
"log"
)
func main() {
var hostKey ssh.PublicKey
// Create client config
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
// Connect to ssh server
conn, err := ssh.Dial("tcp", "localhost:22", config)
if err != nil {
log.Fatal("unable to connect: ", err)
}
defer conn.Close()
// Create a session
session, err := conn.NewSession()
if err != nil {
log.Fatal("unable to create session: ", err)
}
defer session.Close()
// Set up terminal modes
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
// Request pseudo terminal
if err := session.RequestPty("xterm", 40, 80, modes); err != nil {
log.Fatal("request for pseudo terminal failed: ", err)
}
// Start remote shell
if err := session.Shell(); err != nil {
log.Fatal("failed to start shell: ", err)
}
}
Package-Level Type Names (total 156, in which 35 are exported)
/* sort exporteds by: | */
A AlgorithmSigner is a Signer that also supports specifying a specific
algorithm to use for signing.
PublicKey returns an associated PublicKey instance.
Sign returns raw signature for the given data. This method
will apply the hash specified for the keytype to the data.
SignWithAlgorithm is like Signer.Sign, but allows specification of a
non-default signing algorithm. See the SigAlgo* constants in this
package for signature algorithms supported by this package. Callers may
pass an empty string for the algorithm in which case the AlgorithmSigner
will use its default algorithm.
*algorithmOpenSSHCertSigner
*dsaPrivateKey
*wrappedSigner
T : Signer
BannerCallback is the function type used for treat the banner sent by
the server. A BannerCallback receives the message sent by the remote server.
func BannerDisplayStderr() BannerCallback
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.
Clock is used for verifying time stamps. If nil, time.Now
is used.
HostKeyFallback is called when CertChecker.CheckHostKey encounters a
public key that is not a certificate. It must implement host key
validation or else, if nil, all such keys are rejected.
IsHostAuthority should report whether the key is recognized as
an authority for this host. This allows for certificates to be
signed by other keys, and for those other keys to only be valid
signers for particular hostnames. This must be set if this
CertChecker will be checking host certificates.
IsRevoked is called for each certificate so that revocation checking
can be implemented. It should return true if the given certificate
is revoked and false otherwise. If nil, no certificates are
considered to have been revoked.
IsUserAuthority should return true if the key is recognized as an
authority for the given user certificate. This allows for
certificates to be signed by other certificates. This must be set
if this CertChecker will be checking user certificates.
SupportedCriticalOptions lists the CriticalOptions that the
server application layer understands. These are only used
for user certificates.
UserKeyFallback is called when CertChecker.Authenticate encounters a
public key that is not a certificate. It must implement validation
of user keys or else, if nil, all such keys are rejected.
Authenticate checks a user certificate. Authenticate can be used as
a value for ServerConfig.PublicKeyCallback.
CheckCert checks CriticalOptions, ValidPrincipals, revocation, timestamp and
the signature of the certificate.
CheckHostKey checks a host key certificate. This method can be
plugged into ClientConfig.HostKeyCallback.
An Certificate represents an OpenSSH certificate as defined in
[PROTOCOL.certkeys]?rev=1.8. The Certificate type implements the
PublicKey interface, so it can be unmarshaled using
ParsePublicKey.
CertTypeuint32KeyPublicKeyKeyIdstringNonce[]bytePermissionsPermissions
CriticalOptions indicate restrictions to the default
permissions, and are typically used in conjunction with
user certificates. The standard for SSH certificates
defines "force-command" (only allow the given command to
execute) and "source-address" (only allow connections from
the given address). The SSH package currently only enforces
the "source-address" critical option. It is up to server
implementations to enforce other critical options, such as
"force-command", by checking them after the SSH handshake
is successful. In general, SSH servers should reject
connections that specify critical options that are unknown
or not supported.
Extensions are extra functionality that the server may
offer on authenticated connections. Lack of support for an
extension does not preclude authenticating a user. Common
extensions are "permit-agent-forwarding",
"permit-X11-forwarding". The Go SSH library currently does
not act on any extension, and it is up to server
implementations to honor them. Extensions can be used to
pass data from the authentication callbacks to the server
application layer.
Reserved[]byteSerialuint64Signature*SignatureSignatureKeyPublicKeyValidAfteruint64ValidBeforeuint64ValidPrincipals[]string
Marshal serializes c into OpenSSH's wire format. It is part of the
PublicKey interface.
SignCert signs the certificate with an authority, setting the Nonce,
SignatureKey, and Signature fields.
Type returns the key name. It is part of the PublicKey interface.
Verify verifies a signature against the certificate's public
key. It is part of the PublicKey interface.
(*T) bytesForSigning() []byte
*T : PublicKey
func parseCert(in []byte, privAlgo string) (*Certificate, error)
func NewCertSigner(cert *Certificate, signer Signer) (Signer, error)
func (*CertChecker).CheckCert(principal string, cert *Certificate) error
A Channel is an ordered, reliable, flow-controlled, duplex stream
that is multiplexed over an SSH connection.
Close signals end of channel use. No data may be sent after this
call.
CloseWrite signals the end of sending in-band
data. Requests may still be sent, and the other side may
still send data
Read reads up to len(data) bytes from the channel.
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.
If the channel is closed before a reply is returned, io.EOF
is returned.
Stderr returns an io.ReadWriter that writes to this channel
with the extended data type set to stderr. Stderr may
safely be read and written from a different goroutine than
Read and Write respectively.
Write writes len(data) bytes to the channel.
chanConn
*channeltcpChan
T : github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband.Progress
T : github.com/jbenet/go-context/io.Reader
T : github.com/jbenet/go-context/io.Writer
T : io.Closer
T : io.ReadCloser
T : io.Reader
T : io.ReadWriteCloser
T : io.ReadWriter
T : io.WriteCloser
T : io.Writer
T : net/http.closeWriter
func Conn.OpenChannel(name string, data []byte) (Channel, <-chan *Request, error)
func NewChannel.Accept() (Channel, <-chan *Request, error)
func (*Client).dial(laddr string, lport int, raddr string, rport int) (Channel, error)
func (*Client).dialStreamLocal(socketPath string) (Channel, error)
func newSession(ch Channel, reqs <-chan *Request) (*Session, error)
func golang.org/x/crypto/ssh/agent.forwardUnixSocket(channel Channel, addr string)
Client implements a traditional SSH client that supports shells,
subprocesses, TCP port/streamlocal forwarding and tunneled dialing.
ConnConnchannelHandlersmap[string]chan NewChannel
// forwarded tcpip connections from the remote side
// guards calling (*Client).handleForwards
musync.Mutex
ClientVersion returns the client's version string as hashed
into the session ID.
Close closes the underlying network connection
Dial initiates a connection to the addr from the remote host.
The resulting connection has a zero LocalAddr() and RemoteAddr().
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.
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.
Listen requests the remote peer open a listening socket on
addr. Incoming connections will be available by calling Accept on
the returned net.Listener. The listener must be serviced, or the
SSH connection may hang.
N must be "tcp", "tcp4", "tcp6", or "unix".
ListenTCP requests the remote peer open a listening socket
on laddr. Incoming connections will be available by calling
Accept on the returned net.Listener.
ListenUnix is similar to ListenTCP but uses a Unix domain socket.
LocalAddr returns the local address for this connection.
NewSession opens a new Session for this client. (A session is a remote
execution of a program.)
OpenChannel tries to open an channel. If the request is
rejected, it returns *OpenChannelError. On success it 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.
RemoteAddr returns the remote address for this connection.
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.
ServerVersion returns the server's version string as hashed
into the session ID.
SessionID returns the session hash, also denoted by H.
User returns the user ID for this connection.
Wait blocks until the connection has shut down, and returns the
error causing the shutdown.
autoPortListenWorkaround simulates automatic port allocation by
trying random ports repeatedly.
(*T) dial(laddr string, lport int, raddr string, rport int) (Channel, error)(*T) dialStreamLocal(socketPath string) (Channel, error)
handleChannelOpens channel open messages from the remote side.
handleForwards starts goroutines handling forwarded connections.
It's called on first use by (*Client).ListenTCP to not launch
goroutines until needed.
(*T) handleGlobalRequests(incoming <-chan *Request)
T : Conn
T : ConnMetadata
*T : golang.org/x/net/proxy.Dialer
T : io.Closer
func Dial(network, addr string, config *ClientConfig) (*Client, error)
func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client
func github.com/go-git/go-git/v5/plumbing/transport/ssh.dial(network, addr string, config *ClientConfig) (*Client, error)
func golang.org/x/crypto/ssh/agent.ForwardToAgent(client *Client, keyring agent.Agent) error
func golang.org/x/crypto/ssh/agent.ForwardToRemote(client *Client, addr string) error
A ClientConfig structure is used to configure a Client. It must not be
modified after having been passed to an SSH function.
Auth contains possible authentication methods to use with the
server. Only the first instance of a particular RFC 4252 method will
be used during authentication.
BannerCallback is called during the SSH dance to display a custom
server's message. The client configuration can supply this callback to
handle it as wished. The function BannerDisplayStderr can be used for
simplistic display on Stderr.
ClientVersion contains the version identification string that will
be used for the connection. If empty, a reasonable default is used.
Config contains configuration that is shared between clients and
servers.
The allowed cipher algorithms. If unspecified then a sensible
default is used.
The allowed key exchanges algorithms. If unspecified then a
default set of algorithms is used.
The allowed MAC algorithms. If unspecified then a sensible default
is used.
Rand provides the source of entropy for cryptographic
primitives. If Rand is nil, the cryptographic random reader
in package crypto/rand will be used.
The maximum number of bytes sent or received after which a
new key is negotiated. It must be at least 256. If
unspecified, a size suitable for the chosen cipher is used.
HostKeyAlgorithms lists the key types that the client will
accept from the server as host key, in order of
preference. If empty, a reasonable default is used. Any
string returned from PublicKey.Type method may be used, or
any of the CertAlgoXxxx and KeyAlgoXxxx constants.
HostKeyCallback is called during the cryptographic
handshake to validate the server's host key. The client
configuration must supply this callback for the connection
to succeed. The functions InsecureIgnoreHostKey or
FixedHostKey can be used for simplistic host key checks.
Timeout is the maximum amount of time for the TCP connection to establish.
A Timeout of zero means no timeout.
User contains the username to authenticate as.
SetDefaults sets sensible values for unset fields in config. This is
exported for testing: Configs passed to SSH functions are copied and have
default values set automatically.
func github.com/go-git/go-git/v5/plumbing/transport/ssh.AuthMethod.ClientConfig() (*ClientConfig, error)
func github.com/go-git/go-git/v5/plumbing/transport/ssh.(*HostKeyCallbackHelper).SetHostKeyCallback(cfg *ClientConfig) (*ClientConfig, error)
func github.com/go-git/go-git/v5/plumbing/transport/ssh.(*KeyboardInteractive).ClientConfig() (*ClientConfig, error)
func github.com/go-git/go-git/v5/plumbing/transport/ssh.(*Password).ClientConfig() (*ClientConfig, error)
func github.com/go-git/go-git/v5/plumbing/transport/ssh.(*PasswordCallback).ClientConfig() (*ClientConfig, error)
func github.com/go-git/go-git/v5/plumbing/transport/ssh.(*PublicKeys).ClientConfig() (*ClientConfig, error)
func github.com/go-git/go-git/v5/plumbing/transport/ssh.(*PublicKeysCallback).ClientConfig() (*ClientConfig, error)
func Dial(network, addr string, config *ClientConfig) (*Client, error)
func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error)
func github.com/go-git/go-git/v5/plumbing/transport/ssh.NewClient(config *ClientConfig) transport.Transport
func github.com/go-git/go-git/v5/plumbing/transport/ssh.(*HostKeyCallbackHelper).SetHostKeyCallback(cfg *ClientConfig) (*ClientConfig, error)
func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport
func github.com/go-git/go-git/v5/plumbing/transport/ssh.dial(network, addr string, config *ClientConfig) (*Client, error)
func github.com/go-git/go-git/v5/plumbing/transport/ssh.overrideConfig(overrides *ClientConfig, c *ClientConfig)
func github.com/go-git/go-git/v5/plumbing/transport/ssh.overrideConfig(overrides *ClientConfig, c *ClientConfig)
Config contains configuration data common to both ServerConfig and
ClientConfig.
The allowed cipher algorithms. If unspecified then a sensible
default is used.
The allowed key exchanges algorithms. If unspecified then a
default set of algorithms is used.
The allowed MAC algorithms. If unspecified then a sensible default
is used.
Rand provides the source of entropy for cryptographic
primitives. If Rand is nil, the cryptographic random reader
in package crypto/rand will be used.
The maximum number of bytes sent or received after which a
new key is negotiated. It must be at least 256. If
unspecified, a size suitable for the chosen cipher is used.
SetDefaults sets sensible values for unset fields in config. This is
exported for testing: Configs passed to SSH functions are copied and have
default values set automatically.
func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport
Conn represents an SSH connection for both server and client roles.
Conn is the basis for implementing an application layer, such
as ClientConn, which implements the traditional shell access for
clients.
ClientVersion returns the client's version string as hashed
into the session ID.
Close closes the underlying network connection
LocalAddr returns the local address for this connection.
OpenChannel tries to open an channel. If the request is
rejected, it returns *OpenChannelError. On success it 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.
RemoteAddr returns the remote address for this connection.
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.
ServerVersion returns the server's version string as hashed
into the session ID.
SessionID returns the session hash, also denoted by H.
User returns the user ID for this connection.
Wait blocks until the connection has shut down, and returns the
error causing the shutdown.
ClientServerConn
*connectionsshClientKeyboardInteractive
T : ConnMetadata
T : io.Closer
func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error)
func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client
ConnMetadata holds metadata for the connection.
ClientVersion returns the client's version string as hashed
into the session ID.
LocalAddr returns the local address for this connection.
RemoteAddr returns the remote address for this connection.
ServerVersion returns the server's version string as hashed
into the session ID.
SessionID returns the session hash, also denoted by H.
User returns the user ID for this connection.
ClientConn(interface)ServerConn
*connectionsshClientKeyboardInteractive
*sshConn
func (*CertChecker).Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permissions, error)
ExitMissingError is returned if a session is torn down cleanly, but
the server sends no confirmation of the exit status.
(*T) Error() string
*T : error
GSSAPIClient provides the API to plug-in GSSAPI authentication for client logins.
Whenever possible, it should be possible for
DeleteSecContext() calls to be successfully processed even
if other calls cannot succeed, thereby enabling context-related
resources to be released.
In addition to deleting established security contexts,
gss_delete_sec_context must also be able to delete "half-built"
security contexts resulting from an incomplete sequence of
InitSecContext()/AcceptSecContext() calls.
See RFC 2743 section 2.2.3.
GetMIC generates a cryptographic MIC for the SSH2 message, and places
the MIC in a token for transfer to the ssh server.
The contents of the MIC field are obtained by calling GSS_GetMIC()
over the following, using the GSS-API context that was just
established:
string session identifier
byte SSH_MSG_USERAUTH_REQUEST
string user name
string service
string "gssapi-with-mic"
See RFC 2743 section 2.3.1 and RFC 4462 3.5.
InitSecContext initiates the establishment of a security context for GSS-API between the
ssh client and ssh server. Initially the token parameter should be specified as nil.
The routine may return a outputToken which should be transferred to
the ssh server, where the ssh server will present it to
AcceptSecContext. If no token need be sent, InitSecContext will indicate this by setting
needContinue to false. To complete the context
establishment, one or more reply tokens may be required from the ssh
server;if so, InitSecContext will return a needContinue which is true.
In this case, InitSecContext should be called again when the
reply token is received from the ssh server, passing the reply
token to InitSecContext via the token parameters.
See RFC 2743 section 2.2.1 and RFC 4462 section 3.4.
func GSSAPIWithMICAuthMethod(gssAPIClient GSSAPIClient, target string) AuthMethod
GSSAPIServer provides the API to plug in GSSAPI authentication for server logins.
AcceptSecContext allows a remotely initiated security context between the application
and a remote peer to be established by the ssh client. The routine may return a
outputToken which should be transferred to the ssh client,
where the ssh client will present it to InitSecContext.
If no token need be sent, AcceptSecContext will indicate this
by setting the needContinue to false. To
complete the context establishment, one or more reply tokens may be
required from the ssh client. if so, AcceptSecContext
will return a needContinue which is true, in which case it
should be called again when the reply token is received from the ssh
client, passing the token to AcceptSecContext via the
token parameters.
The srcName return value is the authenticated username.
See RFC 2743 section 2.2.2 and RFC 4462 section 3.4.
Whenever possible, it should be possible for
DeleteSecContext() calls to be successfully processed even
if other calls cannot succeed, thereby enabling context-related
resources to be released.
In addition to deleting established security contexts,
gss_delete_sec_context must also be able to delete "half-built"
security contexts resulting from an incomplete sequence of
InitSecContext()/AcceptSecContext() calls.
See RFC 2743 section 2.2.3.
VerifyMIC verifies that a cryptographic MIC, contained in the token parameter,
fits the supplied message is received from the ssh client.
See RFC 2743 section 2.3.2.
AllowLogin, must be set, is called when gssapi-with-mic
authentication is selected (RFC 4462 section 3). The srcName is from the
results of the GSS-API authentication. The format is username@DOMAIN.
GSSAPI just guarantees to the server who the user is, but not if they can log in, and with what permissions.
This callback is called after the user identity is established with GSSAPI to decide if the user can login with
which permissions. If the user is allowed to login, it should return a nil error.
Server must be set. It's the implementation
of the GSSAPIServer interface. See GSSAPIServer interface for details.
func gssExchangeToken(gssapiConfig *GSSAPIWithMICConfig, firstToken []byte, s *connection, sessionID []byte, userAuthReq userAuthRequestMsg) (authErr error, perms *Permissions, err error)
HostKeyCallback is the function type used for verifying server
keys. A HostKeyCallback must return nil if the host key is OK, or
an error to reject it. It receives the hostname as passed to Dial
or NewClientConn. The remote address is the RemoteAddr of the
net.Conn underlying the SSH connection.
func FixedHostKey(key PublicKey) HostKeyCallback
func InsecureIgnoreHostKey() HostKeyCallback
func golang.org/x/crypto/ssh/knownhosts.New(files ...string) (HostKeyCallback, error)
func github.com/go-git/go-git/v5/plumbing/transport/ssh.NewKnownHostsCallback(files ...string) (HostKeyCallback, 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.
( T) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error)( T) method() string
T : AuthMethod
func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod
NewChannel represents an incoming request to a channel. It must either be
accepted for use by calling Accept, or rejected by calling Reject.
Accept accepts the channel creation request. It returns the Channel
and a Go channel containing SSH requests. The Go channel must be
serviced otherwise the Channel will hang.
ChannelType returns the type of the channel, as supplied by the
client.
ExtraData returns the arbitrary payload for this channel, as supplied
by the client. This data is specific to the channel type.
Reject rejects the channel creation request. After calling
this, no other methods on the Channel may be called.
*channel
func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error)
func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error)
func (*Client).HandleChannelOpen(channelType string) <-chan NewChannel
func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client
func (*Client).handleChannelOpens(in <-chan NewChannel)
A PassphraseMissingError indicates that parsing this private key requires a
passphrase. Use ParsePrivateKeyWithPassphrase.
PublicKey will be set if the private key format includes an unencrypted
public key along with the encrypted private key.
(*T) Error() string
*T : error
The Permissions type holds fine-grained permissions that are
specific to a user or a specific authentication method for a user.
The Permissions value for a successful authentication attempt is
available in ServerConn, so it can be used to pass information from
the user-authentication phase to the application layer.
CriticalOptions indicate restrictions to the default
permissions, and are typically used in conjunction with
user certificates. The standard for SSH certificates
defines "force-command" (only allow the given command to
execute) and "source-address" (only allow connections from
the given address). The SSH package currently only enforces
the "source-address" critical option. It is up to server
implementations to enforce other critical options, such as
"force-command", by checking them after the SSH handshake
is successful. In general, SSH servers should reject
connections that specify critical options that are unknown
or not supported.
Extensions are extra functionality that the server may
offer on authenticated connections. Lack of support for an
extension does not preclude authenticating a user. Common
extensions are "permit-agent-forwarding",
"permit-X11-forwarding". The Go SSH library currently does
not act on any extension, and it is up to server
implementations to honor them. Extensions can be used to
pass data from the authentication callbacks to the server
application layer.
func (*CertChecker).Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permissions, error)
func gssExchangeToken(gssapiConfig *GSSAPIWithMICConfig, firstToken []byte, s *connection, sessionID []byte, userAuthReq userAuthRequestMsg) (authErr error, perms *Permissions, err error)
ServerAuthError represents server authentication errors and is
sometimes returned by NewServerConn. It appends any authentication
errors that may occur, and is returned if all of the authentication
methods provided by the user failed to authenticate.
Errors contains authentication errors returned by the authentication
callback methods. The first entry is typically ErrNoAuth.
( T) Error() string
T : error
ServerConfig holds server specific configuration data.
AuthLogCallback, if non-nil, is called to log all authentication
attempts.
BannerCallback, if present, is called and the return string is sent to
the client after key exchange completed but before authentication.
Config contains configuration shared between client and server.
The allowed cipher algorithms. If unspecified then a sensible
default is used.
The allowed key exchanges algorithms. If unspecified then a
default set of algorithms is used.
The allowed MAC algorithms. If unspecified then a sensible default
is used.
Rand provides the source of entropy for cryptographic
primitives. If Rand is nil, the cryptographic random reader
in package crypto/rand will be used.
The maximum number of bytes sent or received after which a
new key is negotiated. It must be at least 256. If
unspecified, a size suitable for the chosen cipher is used.
GSSAPIWithMICConfig includes gssapi server and callback, which if both non-nil, is used
when gssapi-with-mic authentication is selected (RFC 4462 section 3).
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.
MaxAuthTries specifies the maximum number of authentication attempts
permitted per connection. If set to a negative number, the number of
attempts are unlimited. If set to zero, the number of attempts are limited
to 6.
NoClientAuth is true if clients are allowed to connect without
authenticating.
PasswordCallback, if non-nil, is called when a user
attempts to authenticate using a password.
PublicKeyCallback, if non-nil, is called when a client
offers a public key for authentication. It must return a nil error
if the given public key can be used to authenticate the
given user. For example, see CertChecker.Authenticate. A
call to this function does not guarantee that the key
offered is in fact used to authenticate. To record any data
depending on the public key, store it inside a
Permissions.Extensions entry.
ServerVersion is the version identification string to announce in
the public handshake.
If empty, a reasonable default is used.
Note that RFC 4253 section 4.2 requires that this string start with
"SSH-2.0-".
hostKeys[]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.
SetDefaults sets sensible values for unset fields in config. This is
exported for testing: Configs passed to SSH functions are copied and have
default values set automatically.
func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error)
func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport
ServerConn is an authenticated SSH connection, as seen from the
server
ConnConn
If the succeeding authentication callback returned a
non-nil Permissions pointer, it is stored here.
ClientVersion returns the client's version string as hashed
into the session ID.
Close closes the underlying network connection
LocalAddr returns the local address for this connection.
OpenChannel tries to open an channel. If the request is
rejected, it returns *OpenChannelError. On success it 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.
RemoteAddr returns the remote address for this connection.
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.
ServerVersion returns the server's version string as hashed
into the session ID.
SessionID returns the session hash, also denoted by H.
User returns the user ID for this connection.
Wait blocks until the connection has shut down, and returns the
error causing the shutdown.
T : Conn
T : ConnMetadata
T : io.Closer
func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error)
A Session represents a connection to a remote command or shell.
Stderrio.Writer
Stdin specifies the remote process's standard input.
If Stdin is nil, the remote process reads from an empty
bytes.Buffer.
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.
// the channel backing this session
copyFuncs[]func() error
// one send per copyFunc
exitStatuschan error
// true once Start, Run or Shell is invoked.
true if pipe method is active
stdinPipeWriter is non-nil if StdinPipe has not been called
and Stdin was specified by the user; it is the write end of
a pipe connecting Session.Stdin to the stdin channel.
true if pipe method is active
true if pipe method is active
(*T) Close() error
CombinedOutput runs cmd on the remote host and returns its combined
standard output and standard error.
Output runs cmd on the remote host and returns its standard output.
RequestPty requests the association of a pty with the session on the remote host.
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
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 remote server does not send an exit status, an error of type
*ExitMissingError is returned. If the command completes
unsuccessfully or is interrupted by a signal, the error is of type
*ExitError. Other error types may be returned for I/O problems.
SendRequest sends an out-of-band channel request on the SSH channel
underlying the session.
Setenv sets an environment variable that will be applied to any
command executed by Shell or Run.
Shell starts a login shell on the remote host. A Session only
accepts one call to Run, Start, Shell, Output, or CombinedOutput.
Signal sends the given signal to the remote process.
sig is one of the SIG* constants.
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.
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.
StdinPipe returns a pipe that will be connected to the
remote command's standard input when the command starts.
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.
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 remote server does not send an exit status, an error of type
*ExitMissingError is returned. If the command completes
unsuccessfully or is interrupted by a signal, the error is of type
*ExitError. Other error types may be returned for I/O problems.
WindowChange informs the remote host about a terminal window dimension change to h rows and w columns.
(*T) start() error(*T) stderr()(*T) stdin()(*T) stdout()(*T) wait(reqs <-chan *Request) error
*T : io.Closer
func (*Client).NewSession() (*Session, error)
func newSession(ch Channel, reqs <-chan *Request) (*Session, error)
func golang.org/x/crypto/ssh/agent.RequestAgentForwarding(session *Session) error
Waitmsg stores the information about an exited remote command
as reported by Wait.
langstringmsgstringsignalstringstatusint
ExitStatus returns the exit status of the remote command.
Lang returns the language tag. See RFC 3066
Msg returns the exit message given by the remote command
Signal returns the exit signal of the remote command if
it was terminated violently.
( T) String() string
T : expvar.Var
T : fmt.Stringer
T : context.stringer
T : runtime.stringer
buffer provides a linked list buffer for data exchange
between producer and consumer. Theoretically the buffer is
of unlimited capacity as it does no allocation of its own.
protects concurrent access to head, tail and closed
L is held while observing or changing the condition
closedboolCond.checkersync.copyCheckerCond.noCopysync.noCopyCond.notifysync.notifyList
// the buffer that will be read first
// the buffer that will be read last
Broadcast wakes all goroutines waiting on c.
It is allowed but not required for the caller to hold c.L
during the call.
Read reads data from the internal buffer in buf. Reads will block
if no data is available, or until the buffer is closed.
Signal wakes one goroutine waiting on c, if there is any.
It is allowed but not required for the caller to hold c.L
during the call.
Wait atomically unlocks c.L and suspends execution
of the calling goroutine. After later resuming execution,
Wait locks c.L before returning. Unlike in other systems,
Wait cannot return unless awoken by Broadcast or Signal.
Because c.L is not locked when Wait first resumes, the caller
typically cannot assume that the condition is true when
Wait returns. Instead, the caller should Wait in a loop:
c.L.Lock()
for !condition() {
c.Wait()
}
... make use of condition ...
c.L.Unlock()
eof closes the buffer. Reads from the buffer once all
the data has been consumed will receive io.EOF.
write makes buf available for Read to receive.
buf must not be modified after the call to write.
*T : github.com/jbenet/go-context/io.Reader
*T : io.Reader
func newBuffer() *buffer
chanConn fulfills the net.Conn interface without
the tcpChan having to hold laddr or raddr directly.
ChannelChannelladdrnet.Addrraddrnet.Addr
Close signals end of channel use. No data may be sent after this
call.
CloseWrite signals the end of sending in-band
data. Requests may still be sent, and the other side may
still send data
LocalAddr returns the local network address.
Read reads up to len(data) bytes from the channel.
RemoteAddr returns the remote network address.
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.
If the channel is closed before a reply is returned, io.EOF
is returned.
SetDeadline sets the read and write deadlines associated
with the connection.
SetReadDeadline sets the read deadline.
A zero value for t means Read will not time out.
After the deadline, the error from Read will implement net.Error
with Timeout() == true.
SetWriteDeadline exists to satisfy the net.Conn interface
but is not implemented by this type. It always returns an error.
Stderr returns an io.ReadWriter that writes to this channel
with the extended data type set to stderr. Stderr may
safely be read and written from a different goroutine than
Read and Write respectively.
Write writes len(data) bytes to the channel.
T : Channel
T : github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband.Progress
T : github.com/jbenet/go-context/io.Reader
T : github.com/jbenet/go-context/io.Writer
T : io.Closer
T : io.ReadCloser
T : io.Reader
T : io.ReadWriteCloser
T : io.ReadWriter
T : io.WriteCloser
T : io.Writer
*T : net.Conn
T : net/http.closeWriter
chanList is a thread safe channel list.
protects concurrent access to chans
chans are indexed by the local id of the channel, which the
other side should send in the PeersId field.
Mutex.semauint32Mutex.stateint32
This is a debugging aid: it offsets all IDs by this
amount. This helps distinguish otherwise identical
server/client muxes
Lock locks m.
If the lock is already in use, the calling goroutine
blocks until the mutex is available.
Unlock unlocks m.
It is a run-time error if m is not locked on entry to Unlock.
A locked Mutex is not associated with a particular goroutine.
It is allowed for one goroutine to lock a Mutex and then
arrange for another goroutine to unlock it.
Assigns a channel ID to the given channel.
dropAll forgets all channels it knows, returning them in a slice.
getChan returns the channel for the given ID.
(*T) lockSlow()(*T) remove(id uint32)(*T) unlockSlow(new int32)
*T : sync.Locker
channel is an implementation of the Channel interface that works
with the mux class.
R/O after creation
decided is set to true if an accept or reject message has been sent
(for outbound channels) or received (for inbound channels).
direction contains either channelOutbound, for channels created
locally, or channelInbound, for channels created by the peer.
extPending*bufferextraData[]byteincomingRequestschan *RequestlocalIduint32
maxIncomingPayload and maxRemotePayload are the maximum
payload sizes of normal and extended data packets for
receiving and sending, respectively. The wire packet will
be 9 or 13 bytes larger (excluding encryption overhead).
maxRemotePayloaduint32
Pending internal channel messages.
mux*muxmyWindowuint32
packetPool has a buffer for each extended channel ID to
save allocations during writes.
pending*bufferremoteIduint32
thread-safe data
sentCloseboolsentEOFbool
Since requests have no ID, there can be only one request
with WantReply=true outstanding. This lock is held by a
goroutine that has such an outgoing request pending.
windowMu protects myWindow, the flow-control window.
writeMu serializes calls to mux.conn.writePacket() and
protects sentClose and packetPool. This mutex must be
different from windowMu, as writePacket can block if there
is a key exchange pending.
(*T) Accept() (Channel, <-chan *Request, error)(*T) ChannelType() string(*T) Close() error(*T) CloseWrite() error
Extended returns an io.ReadWriter that sends and receives data on the given,
SSH extended stream. Such streams are used, for example, for stderr.
(*T) ExtraData() []byte(*T) Read(data []byte) (int, error)(*T) ReadExtended(data []byte, extended uint32) (n int, err error)(*T) Reject(reason RejectionReason, message string) error(*T) SendRequest(name string, wantReply bool, payload []byte) (bool, error)(*T) Stderr() io.ReadWriter(*T) Write(data []byte) (int, error)
WriteExtended writes data to a specific extended stream. These streams are
used, for example, for stderr.
ackRequest either sends an ack or nack to the channel request.
(*T) adjustWindow(n uint32) error(*T) close()(*T) handleData(packet []byte) error(*T) handlePacket(packet []byte) error
responseMessageReceived is called when a success or failure message is
received on a channel to check that such a message is reasonable for the
given channel.
(*T) sendMessage(msg interface{}) error
writePacket sends a packet. If the packet is a channel close, it updates
sentClose. This method takes the lock c.writeMu.
*T : Channel
*T : NewChannel
*T : github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband.Progress
*T : github.com/jbenet/go-context/io.Reader
*T : github.com/jbenet/go-context/io.Writer
*T : io.Closer
*T : io.ReadCloser
*T : io.Reader
*T : io.ReadWriteCloser
*T : io.ReadWriter
*T : io.WriteCloser
*T : io.Writer
*T : net/http.closeWriter
dhGEXSHA implements the diffie-hellman-group-exchange-sha1 and
diffie-hellman-group-exchange-sha256 key agreement protocols,
as described in RFC 4419
g*big.InthashFunccrypto.Hashp*big.Int( T) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error)
Server half implementation of the Diffie Hellman Key Exchange with SHA1 and SHA256.
This is a minimal implementation to satisfy the automated tests.
(*T) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error)
T : kexAlgorithm
Curveelliptic.CurveX*big.IntY*big.Int
Add returns the sum of (x1,y1) and (x2,y2)
(*T) CryptoPublicKey() crypto.PublicKey
Double returns 2*(x,y)
IsOnCurve reports whether the given (x,y) lies on the curve.
(*T) Marshal() []byte
Params returns the parameters for the curve.
ScalarBaseMult returns k*G, where G is the base point of the group
and k is an integer in big-endian form.
ScalarMult returns k*(Bx,By) where k is a number in big-endian form.
(*T) Type() string(*T) Verify(data []byte, sig *Signature) error(*T) nistID() string
*T : CryptoPublicKey
*T : PublicKey
T : crypto/elliptic.Curve
forward represents an incoming forwarded tcpip connection. The
arguments to add/remove/lookup should be address as specified in
the original forward-request.
// the ssh client channel underlying this forward
// the raddr of the incoming connection
forwardedStreamLocalPayload is a struct used for SSH_MSG_CHANNEL_OPEN message
with "forwarded-streamlocal@openssh.com" string.
Reserved0stringSocketPathstring
forwardEntry represents an established mapping of a laddr on a
remote ssh server to a channel connected to a tcpListener.
cchan forwardladdrnet.Addr
forwardList stores a mapping between remote
forward requests and the tcpListeners.
Mutexsync.Mutexentries[]forwardEntryMutex.semauint32Mutex.stateint32
Lock locks m.
If the lock is already in use, the calling goroutine
blocks until the mutex is available.
Unlock unlocks m.
It is a run-time error if m is not locked on entry to Unlock.
A locked Mutex is not associated with a particular goroutine.
It is allowed for one goroutine to lock a Mutex and then
arrange for another goroutine to unlock it.
(*T) add(addr net.Addr) chan forward
closeAll closes and clears all forwards.
(*T) forward(laddr, raddr net.Addr, ch NewChannel) bool(*T) handleChannels(in <-chan NewChannel)(*T) lockSlow()
remove removes the forward entry, and the channel feeding its
listener.
(*T) unlockSlow(new int32)
*T : sync.Locker
kexAlgorithm abstracts different key exchange algorithms.
Client runs the client-side key agreement. Caller is
responsible for verifying the host key signature.
Server runs server-side key agreement, signing the result
with a hostkey.
*curve25519sha256dhGEXSHA
*dhGroup
*ecdh
kexResult captures the outcome of a key exchange.
Session hash. See also RFC 4253, section 8.
A cryptographic hash function that matches the security
level of the key exchange algorithm. It is used for
calculating H, and for deriving keys from H and K.
Host key as hashed into H.
Shared secret. See also RFC 4253, section 8.
The session ID, which is the first H computed. This is used
to derive key material inside the transport.
Signature of H.
func generateKeyMaterial(out, tag []byte, r *kexResult)
func newPacketCipher(d direction, algs directionAlgorithms, kex *kexResult) (packetCipher, error)
func verifyHostKeySignature(hostKey PublicKey, result *kexResult) error
keyingTransport is a packet based transport that supports key
changes. It need not be thread-safe. It should pass through
msgNewKeys in both directions.
Close closes the write-side of the connection.
prepareKeyChange sets up a key change. The key change for a
direction will be effected if a msgNewKeys message is sent
or received.
Read a packet from the connection. The read is blocking,
i.e. if error is nil, then the returned byte slice is
always non-empty.
Encrypt and send a packet of data to the remote peer.
*transport
T : io.Closer
T : packetConn
func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport
func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport
func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport
noneCipher implements cipher.Stream and provides no encryption. It is used
by the transport before the first key-exchange.
( T) XORKeyStream(dst, src []byte)
T : crypto/cipher.Stream
pubKeyCache caches tests for public keys. Since SSH clients
will query whether a public key is acceptable before attempting to
authenticate with it, we end up with duplicate queries for public
key validity. The cache only applies to a single ServerConn.
keys[]cachedPubKey
add adds the given tuple to the cache.
get returns the result for a given user/algo/key tuple.
Algonamestring
HasSig indicates to the receiver packet that the auth request is signed and
should be used for authentication of the request.
MethodstringPubKey[]byteServicestring
Sig is tagged with "rest" so Marshal will exclude it during
validateKey
Userstring
PublicKeyecdsa.PublicKeyPublicKey.Curveelliptic.CurvePublicKey.X*big.IntPublicKey.Y*big.Int
application is a URL-like string, typically "ssh:" for SSH.
see openssh/PROTOCOL.u2f for details.
Add returns the sum of (x1,y1) and (x2,y2)
Double returns 2*(x,y)
Equal reports whether pub and x have the same value.
Two keys are only considered to have the same value if they have the same Curve value.
Note that for example elliptic.P256() and elliptic.P256().Params() are different
values, as the latter is a generic not constant time implementation.
IsOnCurve reports whether the given (x,y) lies on the curve.
(*T) Marshal() []byte
Params returns the parameters for the curve.
ScalarBaseMult returns k*G, where G is the base point of the group
and k is an integer in big-endian form.
ScalarMult returns k*(Bx,By) where k is a number in big-endian form.
(*T) Type() string(*T) Verify(data []byte, sig *Signature) error(*T) nistID() string
*T : PublicKey
T : crypto/elliptic.Curve
skFields holds the additional fields present in U2F/FIDO2 signatures.
See openssh/PROTOCOL.u2f 'SSH U2F Signatures' for details.
Counter is a monotonic signature counter which can be
used to detect concurrent use of a private key, should
it be extracted from hardware.
Flags contains U2F/FIDO2 flags such as 'user present'
streamLocalChannelForwardMsg is a struct used for SSH2_MSG_GLOBAL_REQUEST message
with "streamlocal-forward@openssh.com"/"cancel-streamlocal-forward@openssh.com" string.
socketPathstring
streamLocalChannelOpenDirectMsg is a struct used for SSH_MSG_CHANNEL_OPEN message
with "direct-streamlocal@openssh.com" string.
See openssh-portable/PROTOCOL, section 2.4. connection: Unix domain socket forwarding
https://github.com/openssh/openssh-portable/blob/master/PROTOCOL#L235
reserved0stringreserved1uint32socketPathstring
// the backing channel
Close signals end of channel use. No data may be sent after this
call.
CloseWrite signals the end of sending in-band
data. Requests may still be sent, and the other side may
still send data
Read reads up to len(data) bytes from the channel.
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.
If the channel is closed before a reply is returned, io.EOF
is returned.
Stderr returns an io.ReadWriter that writes to this channel
with the extended data type set to stderr. Stderr may
safely be read and written from a different goroutine than
Read and Write respectively.
Write writes len(data) bytes to the channel.
T : Channel
T : github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband.Progress
T : github.com/jbenet/go-context/io.Reader
T : github.com/jbenet/go-context/io.Writer
T : io.Closer
T : io.ReadCloser
T : io.Reader
T : io.ReadWriteCloser
T : io.ReadWriter
T : io.WriteCloser
T : io.Writer
T : net/http.closeWriter
conn*Clientin<-chan forwardladdr*net.TCPAddr
Accept waits for and returns the next connection to the listener.
Addr returns the listener's network address.
Close closes the listener.
*T : io.Closer
*T : net.Listener
conn*Clientin<-chan forwardsocketPathstring
Accept waits for and returns the next connection to the listener.
Addr returns the listener's network address.
Close closes the listener.
*T : io.Closer
*T : net.Listener
unused, but required to allow message parsing
Messagestring
window represents the buffer available to clients
wishing to write to a channel.
Cond*sync.Cond
L is held while observing or changing the condition
closedboolCond.checkersync.copyCheckerCond.noCopysync.noCopyCond.notifysync.notifyList
// RFC 4254 5.2 says the window size can grow to 2^32-1
writeWaitersint
Broadcast wakes all goroutines waiting on c.
It is allowed but not required for the caller to hold c.L
during the call.
Signal wakes one goroutine waiting on c, if there is any.
It is allowed but not required for the caller to hold c.L
during the call.
Wait atomically unlocks c.L and suspends execution
of the calling goroutine. After later resuming execution,
Wait locks c.L before returning. Unlike in other systems,
Wait cannot return unless awoken by Broadcast or Signal.
Because c.L is not locked when Wait first resumes, the caller
typically cannot assume that the condition is true when
Wait returns. Instead, the caller should Wait in a loop:
c.L.Lock()
for !condition() {
c.Wait()
}
... make use of condition ...
c.L.Unlock()
add adds win to the amount of window available
for consumers.
close sets the window to closed, so all reservations fail
immediately.
reserve reserves win from the available window capacity.
If no capacity remains, reserve will block. reserve may
return less than requested.
waitWriterBlocked waits until some goroutine is blocked for further
writes. It is used in tests only.
Package-Level Functions (total 126, in which 32 are exported)
BannerDisplayStderr returns a function that can be used for
ClientConfig.BannerCallback to display banners on os.Stderr.
Dial starts a client connection 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.
DiscardRequests consumes and rejects all requests from the
passed-in channel.
FingerprintLegacyMD5 returns the user presentation of the key's
fingerprint as described by RFC 4716 section 4.
FingerprintSHA256 returns the user presentation of the key's
fingerprint as unpadded base64 encoded sha256 hash.
This format was introduced from OpenSSH 6.8.
https://www.openssh.com/txt/release-6.8
https://tools.ietf.org/html/rfc4648#section-3.2 (unpadded base64 encoding)
FixedHostKey returns a function for use in
ClientConfig.HostKeyCallback to accept only a specific host key.
GSSAPIWithMICAuthMethod is an AuthMethod with "gssapi-with-mic" authentication.
See RFC 4462 section 3
gssAPIClient is implementation of the GSSAPIClient interface, see the definition of the interface for details.
target is the server host you want to log in to.
InsecureIgnoreHostKey returns a function that can be used for
ClientConfig.HostKeyCallback to accept any host key. It should
not be used for production code.
KeyboardInteractive returns an AuthMethod using a prompt/response
sequence controlled by the server.
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.
MarshalAuthorizedKey serializes key for inclusion in an OpenSSH
authorized_keys file. The return value ends with newline.
NewCertSigner returns a Signer that signs with the given Certificate, whose
private key is held by signer. It returns an error if the public key in cert
doesn't match the key used by signer.
NewClient creates a Client on top of the given connection.
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.
NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,
or ed25519.PublicKey returns a corresponding PublicKey instance.
ECDSA keys must use P-256, P-384 or P-521.
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.
The returned error may be of type *ServerAuthError for
authentication errors.
NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey,
*ecdsa.PrivateKey or any other crypto.Signer and returns a
corresponding Signer instance. ECDSA keys must use P-256, P-384 or
P-521. DSA keys must use parameter size L1024N160.
NewSignerFromSigner takes any crypto.Signer implementation and
returns a corresponding Signer interface. This can be used, for
example, with keys kept in hardware modules.
ParseAuthorizedKeys parses a public key from an authorized_keys
file used in OpenSSH according to the sshd(8) manual page.
ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as
specified by the OpenSSL DSA man page.
ParseKnownHosts parses an entry in the format of the known_hosts file.
The known_hosts format is documented in the sshd(8) manual page. This
function will parse a single entry from in. On successful return, marker
will contain the optional marker value (i.e. "cert-authority" or "revoked")
or else be empty, hosts will contain the hosts that this entry matches,
pubKey will contain the public key and comment will contain any trailing
comment at the end of the line. See the sshd(8) manual page for the various
forms that a host string can take.
The unparsed remainder of the input will be returned in rest. This function
can be called repeatedly to parse multiple entries.
If no entries were found in the input then err will be io.EOF. Otherwise a
non-nil err value indicates a parse error.
ParsePrivateKey returns a Signer from a PEM encoded private key. It supports
the same keys as ParseRawPrivateKey. If the private key is encrypted, it
will return a PassphraseMissingError.
ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private
key and passphrase. It supports the same keys as
ParseRawPrivateKeyWithPassphrase.
ParsePublicKey parses an SSH public key formatted for use in
the SSH wire protocol according to RFC 4253, section 6.6.
ParseRawPrivateKey returns a private key from a PEM encoded private key. It
supports RSA (PKCS#1), PKCS#8, DSA (OpenSSL), and ECDSA private keys. If the
private key is encrypted, it will return a PassphraseMissingError.
ParseRawPrivateKeyWithPassphrase returns a private key decrypted with
passphrase from a PEM encoded private key. If the passphrase is wrong, it
will return x509.IncorrectPasswordError.
Password returns an AuthMethod using the given password.
PasswordCallback returns an AuthMethod that uses a callback for
fetching a password.
PublicKeys returns an AuthMethod that uses the given key
pairs.
PublicKeysCallback returns an AuthMethod that runs the given
function to obtain a list of key pairs.
RetryableAuthMethod is a decorator for other auth methods enabling them to
be retried up to maxTries before considering that AuthMethod itself failed.
If maxTries is <= 0, will retry indefinitely
This is useful for interactive clients using challenge/response type
authentication (e.g. Keyboard-Interactive, Password, etc) where the user
could mistype their response resulting in the server issuing a
SSH_MSG_USERAUTH_FAILURE (rfc4252 #8 [password] and rfc4256 #3.4
[keyboard-interactive]); Without this decorator, the non-retryable
AuthMethod would be removed from future consideration, and never tried again
(and so the user would never be able to retry their entry).
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 '|'-separated set of numbers
in decimal, the packet must start with one of those numbers. In
case of error, Unmarshal returns a ParseError or
UnexpectedMessageError.
ecHash returns the hash to match the given elliptic curve, see RFC
5656, section 6.2.1
encryptedBlock tells whether a private key is
encrypted by examining its Proc-Type header
for a mention of ENCRYPTED
according to RFC 1421 Section 4.6.1.1.
Sends and receives a version line. The versionLine string should
be US ASCII, start with "SSH-2.0-", and should not include a
newline. exchangeVersions returns the other side's version line.
handleAuthResponse returns whether the preceding authentication request succeeded
along with a list of remaining authentication methods to try next and
an error if an unexpected response was received.
serialize a map of critical options or extensions
issue #10569 - per [PROTOCOL.certkeys] and SSH implementation,
we need two length prefixes for a non-empty string value
newMux returns a mux that runs over the given connection.
setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as
described in RFC 4253, section 6.4. direction should either be serverKeys
(to setup server->client keys) or clientKeys (for client->server keys).
parseAuthorizedKey parses a public key in OpenSSH authorized_keys format
(see sshd(8) manual page) once the options and key type fields have been
removed.
parseOpenSSHPrivateKey parses an OpenSSH private key, using the decrypt
function to unwrap the encrypted portion. unencryptedOpenSSHKey can be used
as the decrypt function to parse an unencrypted private key. See
https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key.
parsePubKey parses a public key of the given algorithm.
Use ParsePublicKey for keys with prepended algorithm.
parseRSA parses an RSA key according to RFC 4253, section 6.6.
Package-Level Variables (total 30, in which 1 are exported)
ErrNoAuth is the error value returned if no
authentication method has been passed yet. This happens as a normal
part of the authentication loop, since the client first tries
'none' authentication to discover available methods.
It is returned in ServerAuthError.Errors from NewServerConn.
cipherModes documents properties of supported ciphers. Ciphers not included
are not supported and will not be negotiated, even if explicitly requested in
ClientConfig.Crypto.Ciphers.
curve25519Zeros is just an array of 32 zero bytes so that we have something
convenient to compare against in order to reject curve25519 points with the
wrong order.
supportedHostKeyAlgos specifies the supported host-key algorithms (i.e. methods
of authenticating servers) in preference order.
supportedKexAlgos specifies the supported key-exchange algorithms in
preference order.
supportedMACs specifies a default set of MAC algorithms in preference order.
This is based on RFC 4253, section 6.4, but with hmac-md5 variants removed
because they have reached the end of their useful life.
Package-Level Constants (total 181, in which 94 are exported)
These constants from [PROTOCOL.certkeys] represent the algorithm names
for certificate types supported by this package.
These constants from [PROTOCOL.certkeys] represent the algorithm names
for certificate types supported by this package.
These constants from [PROTOCOL.certkeys] represent the algorithm names
for certificate types supported by this package.
These constants from [PROTOCOL.certkeys] represent the algorithm names
for certificate types supported by this package.
These constants from [PROTOCOL.certkeys] represent the algorithm names
for certificate types supported by this package.
These constants from [PROTOCOL.certkeys] represent the algorithm names
for certificate types supported by this package.
These constants from [PROTOCOL.certkeys] represent the algorithm names
for certificate types supported by this package.
These constants from [PROTOCOL.certkeys] represent the algorithm names
for certificate types supported by this package.
CertTimeInfinity can be used for OpenSSHCertV01.ValidBefore to indicate that
a certificate does not expire.
These constants represent non-default signature algorithms that are supported
as algorithm parameters to AlgorithmSigner.SignWithAlgorithm methods. See
[PROTOCOL.agent] section 4.5.1 and
https://tools.ietf.org/html/draft-ietf-curdle-rsa-sha2-10
These constants represent non-default signature algorithms that are supported
as algorithm parameters to AlgorithmSigner.SignWithAlgorithm methods. See
[PROTOCOL.agent] section 4.5.1 and
https://tools.ietf.org/html/draft-ietf-curdle-rsa-sha2-10
These constants represent non-default signature algorithms that are supported
as algorithm parameters to AlgorithmSigner.SignWithAlgorithm methods. See
[PROTOCOL.agent] section 4.5.1 and
https://tools.ietf.org/html/draft-ietf-curdle-rsa-sha2-10
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX signals as listed in RFC 4254 Section 6.10.
POSIX terminal mode flags as listed in RFC 4254 Section 8.
POSIX terminal mode flags as listed in RFC 4254 Section 8.
POSIX terminal mode flags as listed in RFC 4254 Section 8.
chanSize sets the amount of buffering SSH connections. This is
primarily for testing: setting chanSize=0 uncovers deadlocks more
quickly.
These are string constants in the SSH protocol.
debugHandshake, if set, prints messages sent and received. Key
exchange messages are printed as if DH were used, so the debug
messages are wrong when using ECDH.
debugMux, if set, causes messages in the connection protocol to be
logged.
debugTransport if set, will print packet types as they go over the
wire. No message decoding is done, to minimize the impact on timing.
For the following kex only the client half contains a production
ready implementation. The server half only consists of a minimal
implementation to satisfy the automated tests.
RFC 4253 section 6.1 defines a minimum packet size of 32768 that implementations
MUST be able to process (plus a few more kilobytes for padding and mac). The RFC
indicates implementations SHOULD be able to handle larger packet sizes, but then
waffles on about reasonable limits.
OpenSSH caps their maxPacket at 256kB so we choose to do
the same. maxPacket is also used to ensure that uint32
length fields do not overflow, so it should remain well
below 4G.
maxVersionStringBytes is the maximum number of bytes that we'll
accept as a version string. RFC 4253 section 4.2 limits this at 255
chars
The protocol uses uint32 for packet counters, so we can't let them
reach 1<<32. We will actually read and write more packets than
this, though: the other side may send more packets, and after we
hit this limit on writing we will send a few more packets for the
key exchange itself.
POSIX terminal mode flags as listed in RFC 4254 Section 8.
The pages are generated with Goldsv0.3.2-preview. (GOOS=darwin GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.