Movatterモバイル変換


[0]ホーム

URL:


ssh

package
v0.45.0Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2025 License:BSD-3-ClauseImports:51Imported by:21,403

Details

Repository

cs.opensource.google/go/x/crypto

Links

Documentation

Overview

Package ssh implements an SSH client and server.

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

References:

[PROTOCOL]: https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL?rev=HEAD[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[SSH-CERTS]:https://datatracker.ietf.org/doc/html/draft-miller-ssh-cert-01[FIPS 140-3 mode]: https://go.dev/doc/security/fips140

This package does not fall under the stability promise of the Go language itself,so its API may be changed when pressing needs arise.

FIPS 140-3 mode

When the program is in [FIPS 140-3 mode], this package behaves as if only SP800-140C and SP 800-140D approved cipher suites, signature algorithms,certificate public key types and sizes, and key exchange and derivationalgorithms were implemented. Others are silently ignored and not negotiated, orrejected. This set may depend on the algorithms supported by the FIPS 140-3 GoCryptographic Module selected with GOFIPS140, and may change across Go versions.

Index

Examples

Constants

View Source
const (CertAlgoRSAv01 = "ssh-rsa-cert-v01@openssh.com"// Deprecated: DSA is only supported at insecure key sizes, and was removed// from major implementations.CertAlgoDSAv01 =InsecureCertAlgoDSAv01// Deprecated: DSA is only supported at insecure key sizes, and was removed// from major implementations.InsecureCertAlgoDSAv01 = "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"CertAlgoSKECDSA256v01  = "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com"CertAlgoED25519v01     = "ssh-ed25519-cert-v01@openssh.com"CertAlgoSKED25519v01   = "sk-ssh-ed25519-cert-v01@openssh.com"// CertAlgoRSASHA256v01 and CertAlgoRSASHA512v01 can't appear as a// Certificate.Type (or PublicKey.Type), but only in// ClientConfig.HostKeyAlgorithms.CertAlgoRSASHA256v01 = "rsa-sha2-256-cert-v01@openssh.com"CertAlgoRSASHA512v01 = "rsa-sha2-512-cert-v01@openssh.com")

Certificate algorithm names from [PROTOCOL.certkeys]. These values can appearin Certificate.Type, PublicKey.Type, and ClientConfig.HostKeyAlgorithms.Unlike key algorithm names, these are not passed to AlgorithmSigner norreturned by MultiAlgorithmSigner and don't appear in the Signature.Formatfield.

View Source
const (// Deprecated: use CertAlgoRSAv01.CertSigAlgoRSAv01 =CertAlgoRSAv01// Deprecated: use CertAlgoRSASHA256v01.CertSigAlgoRSASHA2256v01 =CertAlgoRSASHA256v01// Deprecated: use CertAlgoRSASHA512v01.CertSigAlgoRSASHA2512v01 =CertAlgoRSASHA512v01)
View Source
const (UserCert = 1HostCert = 2)

Certificate types distinguish between host and usercertificates. The values can be set in the CertType field ofCertificate.

View Source
const (CipherAES128GCM            = "aes128-gcm@openssh.com"CipherAES256GCM            = "aes256-gcm@openssh.com"CipherChaCha20Poly1305     = "chacha20-poly1305@openssh.com"CipherAES128CTR            = "aes128-ctr"CipherAES192CTR            = "aes192-ctr"CipherAES256CTR            = "aes256-ctr"InsecureCipherAES128CBC    = "aes128-cbc"InsecureCipherTripleDESCBC = "3des-cbc"InsecureCipherRC4          = "arcfour"InsecureCipherRC4128       = "arcfour128"InsecureCipherRC4256       = "arcfour256")

The ciphers currently or previously implemented by this library, to use in[Config.Ciphers]. For a list, see the [Algorithms.Ciphers] returned bySupportedAlgorithms orInsecureAlgorithms.

View Source
const (InsecureKeyExchangeDH1SHA1   = "diffie-hellman-group1-sha1"InsecureKeyExchangeDH14SHA1  = "diffie-hellman-group14-sha1"KeyExchangeDH14SHA256        = "diffie-hellman-group14-sha256"KeyExchangeDH16SHA512        = "diffie-hellman-group16-sha512"KeyExchangeECDHP256          = "ecdh-sha2-nistp256"KeyExchangeECDHP384          = "ecdh-sha2-nistp384"KeyExchangeECDHP521          = "ecdh-sha2-nistp521"KeyExchangeCurve25519        = "curve25519-sha256"InsecureKeyExchangeDHGEXSHA1 = "diffie-hellman-group-exchange-sha1"KeyExchangeDHGEXSHA256       = "diffie-hellman-group-exchange-sha256"// KeyExchangeMLKEM768X25519 is supported from Go 1.24.KeyExchangeMLKEM768X25519 = "mlkem768x25519-sha256")

The key exchanges currently or previously implemented by this library, to usein [Config.KeyExchanges]. For a list, see the[Algorithms.KeyExchanges] returned bySupportedAlgorithms orInsecureAlgorithms.

View Source
const (HMACSHA256ETM      = "hmac-sha2-256-etm@openssh.com"HMACSHA512ETM      = "hmac-sha2-512-etm@openssh.com"HMACSHA256         = "hmac-sha2-256"HMACSHA512         = "hmac-sha2-512"HMACSHA1           = "hmac-sha1"InsecureHMACSHA196 = "hmac-sha1-96")

The message authentication code (MAC) currently or previously implemented bythis library, to use in [Config.MACs]. For a list, see the[Algorithms.MACs] returned bySupportedAlgorithms orInsecureAlgorithms.

View Source
const (KeyAlgoRSA = "ssh-rsa"// Deprecated: DSA is only supported at insecure key sizes, and was removed// from major implementations.KeyAlgoDSA =InsecureKeyAlgoDSA// Deprecated: DSA is only supported at insecure key sizes, and was removed// from major implementations.InsecureKeyAlgoDSA = "ssh-dss"KeyAlgoECDSA256    = "ecdsa-sha2-nistp256"KeyAlgoSKECDSA256  = "sk-ecdsa-sha2-nistp256@openssh.com"KeyAlgoECDSA384    = "ecdsa-sha2-nistp384"KeyAlgoECDSA521    = "ecdsa-sha2-nistp521"KeyAlgoED25519     = "ssh-ed25519"KeyAlgoSKED25519   = "sk-ssh-ed25519@openssh.com"// KeyAlgoRSASHA256 and KeyAlgoRSASHA512 are only public key algorithms, not// public key formats, so they can't appear as a PublicKey.Type. The// corresponding PublicKey.Type is KeyAlgoRSA. SeeRFC 8332, Section 2.KeyAlgoRSASHA256 = "rsa-sha2-256"KeyAlgoRSASHA512 = "rsa-sha2-512")

Public key algorithms names. These values can appear in PublicKey.Type,ClientConfig.HostKeyAlgorithms, Signature.Format, or as AlgorithmSignerarguments.

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

POSIX terminal mode flags as listed inRFC 4254 Section 8.

View Source
const CertTimeInfinity = 1<<64 - 1

CertTimeInfinity can be used for OpenSSHCertV01.ValidBefore to indicate thata certificate does not expire.

Variables

View Source
var ErrNoAuth =errors.New("ssh: no auth passed yet")

ErrNoAuth is the error value returned if noauthentication method has been passed yet. This happens as a normalpart of the authentication loop, since the client first tries'none' authentication to discover available methods.It is returned in ServerAuthError.Errors from NewServerConn.

Functions

funcDiscardRequests

func DiscardRequests(in <-chan *Request)

DiscardRequests consumes and rejects all requests from thepassed-in channel.

funcFingerprintLegacyMD5

func FingerprintLegacyMD5(pubKeyPublicKey)string

FingerprintLegacyMD5 returns the user presentation of the key'sfingerprint as described byRFC 4716 section 4.

funcFingerprintSHA256

func FingerprintSHA256(pubKeyPublicKey)string

FingerprintSHA256 returns the user presentation of the key'sfingerprint as unpadded base64 encoded sha256 hash.This format was introduced from OpenSSH 6.8.https://www.openssh.com/txt/release-6.8https://tools.ietf.org/html/rfc4648#section-3.2 (unpadded base64 encoding)

funcMarshal

func Marshal(msg interface{}) []byte

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

funcMarshalAuthorizedKey

func MarshalAuthorizedKey(keyPublicKey) []byte

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

funcMarshalPrivateKeyadded inv0.14.0

func MarshalPrivateKey(keycrypto.PrivateKey, commentstring) (*pem.Block,error)

MarshalPrivateKey returns a PEM block with the private key serialized in theOpenSSH format.

funcMarshalPrivateKeyWithPassphraseadded inv0.14.0

func MarshalPrivateKeyWithPassphrase(keycrypto.PrivateKey, commentstring, passphrase []byte) (*pem.Block,error)

MarshalPrivateKeyWithPassphrase returns a PEM block holding the encryptedprivate key serialized in the OpenSSH format.

funcParseDSAPrivateKey

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

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

funcParseRawPrivateKey

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

ParseRawPrivateKey returns a private key from a PEM encoded private key. It supportsRSA, DSA, ECDSA, and Ed25519 private keys in PKCS#1, PKCS#8, OpenSSL, and OpenSSHformats. If the private key is encrypted, it will return a PassphraseMissingError.

funcParseRawPrivateKeyWithPassphrase

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

ParseRawPrivateKeyWithPassphrase returns a private key decrypted withpassphrase from a PEM encoded private key. If the passphrase is wrong, itwill return x509.IncorrectPasswordError.

funcUnmarshal

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

Unmarshal parses data in SSH wire format into a structure. The outargument should be a pointer to struct. If the first member of thestruct has the "sshtype" tag set to a '|'-separated set of numbersin decimal, the packet must start with one of those numbers. Incase of error, Unmarshal returns a ParseError orUnexpectedMessageError.

Types

typeAlgorithmNegotiationErroradded inv0.40.0

type AlgorithmNegotiationError struct {Whatstring// RequestedAlgorithms lists the algorithms supported by the peer.RequestedAlgorithms []string// SupportedAlgorithms lists the algorithms supported on our side.SupportedAlgorithms []string}

AlgorithmNegotiationError defines the error returned if the client and theserver cannot agree on an algorithm for key exchange, host key, cipher, MAC.

func (*AlgorithmNegotiationError)Erroradded inv0.40.0

typeAlgorithmSigner

type AlgorithmSigner interface {Signer// SignWithAlgorithm is like Signer.Sign, but allows specifying a desired// signing algorithm. Callers may pass an empty string for the algorithm in// which case the AlgorithmSigner will use a default algorithm. This default// doesn't currently control any behavior in this package.SignWithAlgorithm(randio.Reader, data []byte, algorithmstring) (*Signature,error)}

An AlgorithmSigner is a Signer that also supports specifying an algorithm touse for signing.

An AlgorithmSigner can't advertise the algorithms it supports, unless it alsoimplements MultiAlgorithmSigner, so it should be prepared to be invoked withevery algorithm supported by the public key format.

typeAlgorithmsadded inv0.39.0

type Algorithms struct {KeyExchanges   []stringCiphers        []stringMACs           []stringHostKeys       []stringPublicKeyAuths []string}

Algorithms defines a set of algorithms that can be configured in the clientor server config for negotiation during a handshake.

funcInsecureAlgorithmsadded inv0.39.0

func InsecureAlgorithms()Algorithms

InsecureAlgorithms returns algorithms currently implemented by this packageand which have security issues.

funcSupportedAlgorithmsadded inv0.39.0

func SupportedAlgorithms()Algorithms

SupportedAlgorithms returns algorithms currently implemented by this package,excluding those with security issues, which are returned byInsecureAlgorithms. The algorithms listed here are in preference order.

typeAlgorithmsConnMetadataadded inv0.39.0

type AlgorithmsConnMetadata interface {ConnMetadataAlgorithms()NegotiatedAlgorithms}

AlgorithmsConnMetadata is a ConnMetadata that can return the algorithmsnegotiated between client and server.

typeAuthMethod

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

An AuthMethod represents an instance of anRFC 4252 authentication method.

funcGSSAPIWithMICAuthMethod

func GSSAPIWithMICAuthMethod(gssAPIClientGSSAPIClient, targetstring)AuthMethod

GSSAPIWithMICAuthMethod is an AuthMethod with "gssapi-with-mic" authentication.SeeRFC 4462 section 3gssAPIClient 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.

funcKeyboardInteractive

func KeyboardInteractive(challengeKeyboardInteractiveChallenge)AuthMethod

KeyboardInteractive returns an AuthMethod using a prompt/responsesequence controlled by the server.

funcPassword

func Password(secretstring)AuthMethod

Password returns an AuthMethod using the given password.

funcPasswordCallback

func PasswordCallback(prompt func() (secretstring, errerror))AuthMethod

PasswordCallback returns an AuthMethod that uses a callback forfetching a password.

funcPublicKeys

func PublicKeys(signers ...Signer)AuthMethod

PublicKeys returns an AuthMethod that uses the given keypairs.

Example
package mainimport ("log""os""golang.org/x/crypto/ssh")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 := os.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()}

funcPublicKeysCallback

func PublicKeysCallback(getSigners func() (signers []Signer, errerror))AuthMethod

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

funcRetryableAuthMethod

func RetryableAuthMethod(authAuthMethod, maxTriesint)AuthMethod

RetryableAuthMethod is a decorator for other auth methods enabling them tobe 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 typeauthentication (e.g. Keyboard-Interactive, Password, etc) where the usercould mistype their response resulting in the server issuing aSSH_MSG_USERAUTH_FAILURE (rfc4252 #8 [password] and rfc4256 #3.4[keyboard-interactive]); Without this decorator, the non-retryableAuthMethod would be removed from future consideration, and never tried again(and so the user would never be able to retry their entry).

Example
user := "testuser"NumberOfPrompts := 3// Normally this would be a callback that prompts the user to answer the// provided questionsCb := func(user, instruction string, questions []string, echos []bool) (answers []string, err error) {return []string{"answer1", "answer2"}, nil}config := &ClientConfig{HostKeyCallback: InsecureIgnoreHostKey(),User:            user,Auth: []AuthMethod{RetryableAuthMethod(KeyboardInteractiveChallenge(Cb), NumberOfPrompts),},}host := "mysshserver"netConn, err := net.Dial("tcp", host)if err != nil {log.Fatal(err)}sshConn, _, _, err := NewClientConn(netConn, host, config)if err != nil {log.Fatal(err)}_ = sshConn

typeBannerCallback

type BannerCallback func(messagestring)error

BannerCallback is the function type used for treat the banner sent bythe server. A BannerCallback receives the message sent by the remote server.

funcBannerDisplayStderr

func BannerDisplayStderr()BannerCallback

BannerDisplayStderr returns a function that can be used forClientConfig.BannerCallback to display banners on os.Stderr.

typeBannerErroradded inv0.24.0

type BannerError struct {ErrerrorMessagestring}

BannerError is an error that can be returned by authentication handlers inServerConfig to send a banner message to the client.

func (*BannerError)Erroradded inv0.24.0

func (b *BannerError) Error()string

func (*BannerError)Unwrapadded inv0.24.0

func (b *BannerError) Unwrap()error

typeCertChecker

type CertChecker struct {// SupportedCriticalOptions lists the CriticalOptions that the// server application layer understands. These are only used// for user certificates.SupportedCriticalOptions []string// IsUserAuthority should return true if the key is recognized as an// authority for user certificate. This must be set if this CertChecker// will be checking user certificates.IsUserAuthority func(authPublicKey)bool// IsHostAuthority should report whether the key is recognized as// an authority for this host. This must be set if this CertChecker// will be checking host certificates.IsHostAuthority func(authPublicKey, addressstring)bool// Clock is used for verifying time stamps. If nil, time.Now// is used.Clock func()time.Time// 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.UserKeyFallback func(connConnMetadata, keyPublicKey) (*Permissions,error)// 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.HostKeyFallbackHostKeyCallback// 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.IsRevoked func(cert *Certificate)bool}

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

func (*CertChecker)Authenticate

func (c *CertChecker) Authenticate(connConnMetadata, pubKeyPublicKey) (*Permissions,error)

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

func (*CertChecker)CheckCert

func (c *CertChecker) CheckCert(principalstring, cert *Certificate)error

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

func (*CertChecker)CheckHostKey

func (c *CertChecker) CheckHostKey(addrstring, remotenet.Addr, keyPublicKey)error

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

typeCertificate

type Certificate struct {Nonce           []byteKeyPublicKeySerialuint64CertTypeuint32KeyIdstringValidPrincipals []stringValidAfteruint64ValidBeforeuint64PermissionsReserved     []byteSignatureKeyPublicKeySignature    *Signature}

An Certificate represents an OpenSSH certificate as defined in[PROTOCOL.certkeys]?rev=1.8. The Certificate type implements thePublicKey interface, so it can be unmarshaled usingParsePublicKey.

func (*Certificate)Marshal

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

Marshal serializes c into OpenSSH's wire format. It is part of thePublicKey interface.

func (*Certificate)SignCert

func (c *Certificate) SignCert(randio.Reader, authoritySigner)error

SignCert signs the certificate with an authority, setting the Nonce,SignatureKey, and Signature fields. If the authority implements theMultiAlgorithmSigner interface the first algorithm in the list is used. Thisis useful if you want to sign with a specific algorithm. As specified in[SSH-CERTS], Section 2.1.1, authority can't be aCertificate.

Example
package mainimport ("crypto/rand""crypto/rsa""fmt""log""golang.org/x/crypto/ssh")func main() {// Sign a certificate with a specific algorithm.privateKey, err := rsa.GenerateKey(rand.Reader, 3072)if err != nil {log.Fatal("unable to generate RSA key: ", err)}publicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)if err != nil {log.Fatal("unable to get RSA public key: ", err)}caKey, err := rsa.GenerateKey(rand.Reader, 3072)if err != nil {log.Fatal("unable to generate CA key: ", err)}signer, err := ssh.NewSignerFromKey(caKey)if err != nil {log.Fatal("unable to generate signer from key: ", err)}mas, err := ssh.NewSignerWithAlgorithms(signer.(ssh.AlgorithmSigner), []string{ssh.KeyAlgoRSASHA256})if err != nil {log.Fatal("unable to create signer with algorithms: ", err)}certificate := ssh.Certificate{Key:      publicKey,CertType: ssh.UserCert,}if err := certificate.SignCert(rand.Reader, mas); err != nil {log.Fatal("unable to sign certificate: ", err)}// Save the public key to a file and check that rsa-sha-256 is used for// signing:// ssh-keygen -L -f <path to the file>fmt.Println(string(ssh.MarshalAuthorizedKey(&certificate)))}

func (*Certificate)Type

func (c *Certificate) Type()string

Type returns the certificate algorithm 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 publickey. It is part of the PublicKey interface.

typeChannel

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)// Close 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 dataCloseWrite()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.// If the channel is closed before a reply is returned, io.EOF// is returned.SendRequest(namestring, wantReplybool, payload []byte) (bool,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.Stderr()io.ReadWriter}

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

typeClient

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

Client implements a traditional SSH client that supports shells,subprocesses, TCP port/streamlocal forwarding and tunneled dialing.

funcDial

func Dial(network, addrstring, config *ClientConfig) (*Client,error)

Dial starts a client connection to the given SSH server. It is aconvenience function that connects to the given network address,initiates the SSH handshake, and then sets up a Client. For accessto incoming channels and requests, use net.Dial with NewClientConninstead.

Example
package mainimport ("bytes""fmt""log""golang.org/x/crypto/ssh")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.Buffersession.Stdout = &bif err := session.Run("/usr/bin/whoami"); err != nil {log.Fatal("Failed to run: " + err.Error())}fmt.Println(b.String())}

funcNewClient

func NewClient(cConn, chans <-chanNewChannel, reqs <-chan *Request) *Client

NewClient creates a Client on top of the given connection.

func (*Client)Dial

func (c *Client) Dial(n, addrstring) (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)DialContextadded inv0.16.0

func (c *Client) DialContext(ctxcontext.Context, n, addrstring) (net.Conn,error)

DialContext initiates a connection to the addr from the remote host.

The provided Context must be non-nil. If the context expires before theconnection is complete, an error is returned. Once successfully connected,any expiration of the context will not affect the connection.

See func Dial for additional information.

func (*Client)DialTCP

func (c *Client) DialTCP(nstring, 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 usedas the local address for the connection.

func (*Client)HandleChannelOpen

func (c *Client) HandleChannelOpen(channelTypestring) <-chanNewChannel

HandleChannelOpen returns a channel on which NewChannel requestsfor 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, addrstring) (net.Listener,error)

Listen requests the remote peer open a listening socket onaddr. Incoming connections will be available by calling Accept onthe returned net.Listener. The listener must be serviced, or theSSH connection may hang.N must be "tcp", "tcp4", "tcp6", or "unix".

If the address is a hostname, it is sent to the remote peer as-is, withoutbeing resolved locally, and the Listener Addr method will return a zero IP.

Example
package mainimport ("fmt""log""net/http""golang.org/x/crypto/ssh")func main() {var hostKey ssh.PublicKeyconfig := &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")}))}

func (*Client)ListenTCP

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

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

ListenTCP accepts an IP address, to provide a hostname useClient.Listenwith "tcp", "tcp4", or "tcp6" network instead.

func (*Client)ListenUnix

func (c *Client) ListenUnix(socketPathstring) (net.Listener,error)

ListenUnix is similar to ListenTCP but uses a Unix domain socket.

func (*Client)NewSession

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

NewSession opens a new Session for this client. (A session is a remoteexecution of a program.)

typeClientConfig

type ClientConfig struct {// Config contains configuration that is shared between clients and// servers.Config// User contains the username to authenticate as.Userstring// Auth contains possible authentication methods to use with the// server. Only the first instance of a particularRFC 4252 method will// be used during authentication.Auth []AuthMethod// 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.HostKeyCallbackHostKeyCallback// 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.BannerCallbackBannerCallback// ClientVersion contains the version identification string that will// be used for the connection. If empty, a reasonable default is used.ClientVersionstring// HostKeyAlgorithms lists the public key algorithms that the client will// accept from the server for host key authentication, in order of// preference. If empty, a reasonable default is used. Any// string returned from a PublicKey.Type method may be used, or// any of the CertAlgo and KeyAlgo constants.HostKeyAlgorithms []string// Timeout is the maximum amount of time for the TCP connection to establish.//// A Timeout of zero means no timeout.Timeouttime.Duration}

A ClientConfig structure is used to configure a Client. It must not bemodified after having been passed to an SSH function.

Example
package mainimport ("log""os""golang.org/x/crypto/ssh")func main() {var hostKey ssh.PublicKeykey, err := os.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)}// Minimal ClientConfig with SHA-1 algorithms disabled.// The algorithms returned by ssh.SupportedAlgorithms() are different from// the default ones and do not include algorithms that are considered// insecure, such as those using SHA-1, returned by// ssh.InsecureAlgorithms().algorithms := ssh.SupportedAlgorithms()config := &ssh.ClientConfig{Config: ssh.Config{KeyExchanges: algorithms.KeyExchanges,Ciphers:      algorithms.Ciphers,MACs:         algorithms.MACs,},User: "username",Auth: []ssh.AuthMethod{ssh.PublicKeys(signer),},HostKeyCallback: ssh.FixedHostKey(hostKey),// We should check that hostKey algorithm is included in// algorithms.HostKeys.HostKeyAlgorithms: algorithms.HostKeys,}client, err := ssh.Dial("tcp", "yourserver.com:22", config)if err != nil {log.Fatal("Failed to dial: ", err)}defer client.Close()}

typeConfig

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.Randio.Reader// 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.RekeyThresholduint64// The allowed key exchanges algorithms. If unspecified then a default set// of algorithms is used. Unsupported values are silently ignored.KeyExchanges []string// The allowed cipher algorithms. If unspecified then a sensible default is// used. Unsupported values are silently ignored.Ciphers []string// The allowed MAC algorithms. If unspecified then a sensible default is// used. Unsupported values are silently ignored.MACs []string}

Config contains configuration data common to both ServerConfig andClientConfig.

func (*Config)SetDefaults

func (c *Config) SetDefaults()

SetDefaults sets sensible values for unset fields in config. This isexported for testing: Configs passed to SSH functions are copied and havedefault values set automatically.

typeConn

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 alsoRFC 4254, section 4.SendRequest(namestring, wantReplybool, payload []byte) (bool, []byte,error)// 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.OpenChannel(namestring, data []byte) (Channel, <-chan *Request,error)// Close closes the underlying network connectionClose()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.Conn is the basis for implementing an application layer, suchas ClientConn, which implements the traditional shell access forclients.

funcNewClientConn

func NewClientConn(cnet.Conn, addrstring, config *ClientConfig) (Conn, <-chanNewChannel, <-chan *Request,error)

NewClientConn establishes an authenticated SSH connection using cas the underlying transport. The Request and NewChannel channelsmust be serviced or the connection will hang.

typeConnMetadata

type ConnMetadata interface {// User returns the user ID for this connection.User()string// SessionID returns the session 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 server'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.

typeCryptoPublicKey

type CryptoPublicKey interface {CryptoPublicKey()crypto.PublicKey}

CryptoPublicKey, if implemented by a PublicKey,returns the underlying crypto.PublicKey form of the key.

typeDirectionAlgorithmsadded inv0.39.0

type DirectionAlgorithms struct {CipherstringMACstring// contains filtered or unexported fields}

DirectionAlgorithms defines the algorithms negotiated in one direction(either read or write).

typeExitError

type ExitError struct {Waitmsg}

An ExitError reports unsuccessful completion of a remote command.

func (*ExitError)Error

func (e *ExitError) Error()string

typeExitMissingError

type ExitMissingError struct{}

ExitMissingError is returned if a session is torn down cleanly, butthe server sends no confirmation of the exit status.

func (*ExitMissingError)Error

func (e *ExitMissingError) Error()string

typeGSSAPIClient

type GSSAPIClient interface {// 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.// SeeRFC 2743 section 2.2.1 andRFC 4462 section 3.4.InitSecContext(targetstring, token []byte, isGSSDelegCredsbool) (outputToken []byte, needContinuebool, errerror)// 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"// SeeRFC 2743 section 2.3.1 andRFC 4462 3.5.GetMIC(micFiled []byte) ([]byte,error)// 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.// SeeRFC 2743 section 2.2.3.DeleteSecContext()error}

GSSAPIClient provides the API to plug-in GSSAPI authentication for client logins.

typeGSSAPIServer

type GSSAPIServer interface {// 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.// SeeRFC 2743 section 2.2.2 andRFC 4462 section 3.4.AcceptSecContext(token []byte) (outputToken []byte, srcNamestring, needContinuebool, errerror)// VerifyMIC verifies that a cryptographic MIC, contained in the token parameter,// fits the supplied message is received from the ssh client.// SeeRFC 2743 section 2.3.2.VerifyMIC(micField []byte, micToken []byte)error// 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.// SeeRFC 2743 section 2.2.3.DeleteSecContext()error}

GSSAPIServer provides the API to plug in GSSAPI authentication for server logins.

typeGSSAPIWithMICConfig

type GSSAPIWithMICConfig struct {// 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.AllowLogin func(connConnMetadata, srcNamestring) (*Permissions,error)// Server must be set. It's the implementation// of the GSSAPIServer interface. See GSSAPIServer interface for details.ServerGSSAPIServer}

typeHostKeyCallback

type HostKeyCallback func(hostnamestring, remotenet.Addr, keyPublicKey)error

HostKeyCallback is the function type used for verifying serverkeys. A HostKeyCallback must return nil if the host key is OK, oran error to reject it. It receives the hostname as passed to Dialor NewClientConn. The remote address is the RemoteAddr of thenet.Conn underlying the SSH connection.

funcFixedHostKey

func FixedHostKey(keyPublicKey)HostKeyCallback

FixedHostKey returns a function for use inClientConfig.HostKeyCallback to accept only a specific host key.

funcInsecureIgnoreHostKey

func InsecureIgnoreHostKey()HostKeyCallback

InsecureIgnoreHostKey returns a function that can be used forClientConfig.HostKeyCallback to accept any host key. It shouldnot be used for production code.

typeKeyboardInteractiveChallenge

type KeyboardInteractiveChallenge func(name, instructionstring, questions []string, echos []bool) (answers []string, errerror)

KeyboardInteractiveChallenge should print questions, optionallydisabling echoing (e.g. for passwords), and return all the answers.Challenge may be called multiple times in a single session. Aftersuccessful authentication, the server may send a challenge with noquestions, for which the name and instruction messages should beprinted.RFC 4256 section 3.3 details how the UI should behave forboth CLI and GUI environments.

typeMultiAlgorithmSigneradded inv0.14.0

type MultiAlgorithmSigner interface {AlgorithmSigner// Algorithms returns the available algorithms in preference order. The list// must not be empty, and it must not include certificate types.Algorithms() []string}

MultiAlgorithmSigner is an AlgorithmSigner that also reports the algorithmssupported by that signer.

funcNewSignerWithAlgorithmsadded inv0.14.0

func NewSignerWithAlgorithms(signerAlgorithmSigner, algorithms []string) (MultiAlgorithmSigner,error)

NewSignerWithAlgorithms returns a signer restricted to the specifiedalgorithms. The algorithms must be set in preference order. The list must notbe empty, and it must not include certificate types. An error is returned ifthe specified algorithms are incompatible with the public key type.

typeNegotiatedAlgorithmsadded inv0.39.0

type NegotiatedAlgorithms struct {KeyExchangestringHostKeystringReadDirectionAlgorithmsWriteDirectionAlgorithms}

NegotiatedAlgorithms defines algorithms negotiated between client and server.

typeNewChannel

type NewChannel interface {// 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.Accept() (Channel, <-chan *Request,error)// Reject rejects the channel creation request. After calling// this, no other methods on the Channel may be called.Reject(reasonRejectionReason, messagestring)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 represents an incoming request to a channel. It must either beaccepted for use by calling Accept, or rejected by calling Reject.

typeOpenChannelError

type OpenChannelError struct {ReasonRejectionReasonMessagestring}

OpenChannelError is returned if the other side rejects anOpenChannel request.

func (*OpenChannelError)Error

func (e *OpenChannelError) Error()string

typePartialSuccessErroradded inv0.22.0

type PartialSuccessError struct {// Next defines the authentication callbacks to apply to further steps. The// available methods communicated to the client are based on the non-nil// ServerAuthCallbacks fields.NextServerAuthCallbacks}

PartialSuccessError can be returned by any of theServerConfigauthentication callbacks to indicate to the client that authentication haspartially succeeded, but further steps are required.

func (*PartialSuccessError)Erroradded inv0.22.0

func (p *PartialSuccessError) Error()string

typePassphraseMissingError

type PassphraseMissingError struct {// PublicKey will be set if the private key format includes an unencrypted// public key along with the encrypted private key.PublicKeyPublicKey}

A PassphraseMissingError indicates that parsing this private key requires apassphrase. Use ParsePrivateKeyWithPassphrase.

func (*PassphraseMissingError)Error

typePermissions

type Permissions struct {// 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.CriticalOptions map[string]string// 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.Extensions map[string]string// ExtraData allows to store user defined data.ExtraData map[any]any}

The Permissions type holds fine-grained permissions that arespecific to a user or a specific authentication method for a user.The Permissions value for a successful authentication attempt isavailable in ServerConn, so it can be used to pass information fromthe user-authentication phase to the application layer.

typePublicKey

type PublicKey interface {// Type returns the key format name, e.g. "ssh-rsa".Type()string// Marshal returns the serialized key data in SSH wire format, with the name// prefix. To unmarshal the returned data, use the ParsePublicKey function.Marshal() []byte// Verify that sig is a signature on the given data using this key. This// method will hash the data appropriately first. sig.Format is allowed to// be any signature algorithm compatible with the key type, the caller// should check if it has more stringent requirements.Verify(data []byte, sig *Signature)error}

PublicKey represents a public key using an unspecified algorithm.

Some PublicKeys provided by this package also implement CryptoPublicKey.

funcNewPublicKey

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

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.

funcParseAuthorizedKey

func ParseAuthorizedKey(in []byte) (outPublicKey, commentstring, options []string, rest []byte, errerror)

ParseAuthorizedKey parses a public key from an authorized_keys file used inOpenSSH according to the sshd(8) manual page. Invalid lines are ignored.

funcParseKnownHosts

func ParseKnownHosts(in []byte) (markerstring, hosts []string, pubKeyPublicKey, commentstring, rest []byte, errerror)

ParseKnownHosts parses an entry in the format of the known_hosts file.

The known_hosts format is documented in the sshd(8) manual page. Thisfunction will parse a single entry from in. On successful return, markerwill 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 trailingcomment at the end of the line. See the sshd(8) manual page for the variousforms that a host string can take.

The unparsed remainder of the input will be returned in rest. This functioncan be called repeatedly to parse multiple entries.

If no entries were found in the input then err will be io.EOF. Otherwise anon-nil err value indicates a parse error.

funcParsePublicKey

func ParsePublicKey(in []byte) (outPublicKey, errerror)

ParsePublicKey parses an SSH public key or certificate formatted for use inthe SSH wire protocol according toRFC 4253, section 6.6.

typeRejectionReason

type RejectionReasonuint32

RejectionReason is an enumeration used when rejecting channel creationrequests. SeeRFC 4254, section 5.1.

const (ProhibitedRejectionReason =iota + 1ConnectionFailedUnknownChannelTypeResourceShortage)

func (RejectionReason)String

func (rRejectionReason) String()string

String converts the rejection reason to human readable form.

typeRequest

type Request struct {TypestringWantReplyboolPayload   []byte// contains filtered or unexported fields}

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

func (*Request)Reply

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

Reply sends a response to a request. It must be called for all requestswhere WantReply is true and is a no-op otherwise. The payload argument isignored for replies to channel-specific requests.

typeServerAuthCallbacksadded inv0.22.0

type ServerAuthCallbacks struct {// PasswordCallback behaves like [ServerConfig.PasswordCallback].PasswordCallback func(connConnMetadata, password []byte) (*Permissions,error)// PublicKeyCallback behaves like [ServerConfig.PublicKeyCallback].PublicKeyCallback func(connConnMetadata, keyPublicKey) (*Permissions,error)// KeyboardInteractiveCallback behaves like [ServerConfig.KeyboardInteractiveCallback].KeyboardInteractiveCallback func(connConnMetadata, clientKeyboardInteractiveChallenge) (*Permissions,error)// GSSAPIWithMICConfig behaves like [ServerConfig.GSSAPIWithMICConfig].GSSAPIWithMICConfig *GSSAPIWithMICConfig}

ServerAuthCallbacks defines server-side authentication callbacks.

typeServerAuthError

type ServerAuthError struct {// Errors contains authentication errors returned by the authentication// callback methods. The first entry is typically ErrNoAuth.Errors []error}

ServerAuthError represents server authentication errors and issometimes returned by NewServerConn. It appends any authenticationerrors that may occur, and is returned if all of the authenticationmethods provided by the user failed to authenticate.

func (ServerAuthError)Error

func (lServerAuthError) Error()string

typeServerConfig

type ServerConfig struct {// Config contains configuration shared between client and server.Config// PublicKeyAuthAlgorithms specifies the supported client public key// authentication algorithms. Note that this should not include certificate// types since those use the underlying algorithm. This list is sent to the// client if it supports the server-sig-algs extension. Order is irrelevant.// If unspecified then a default set of algorithms is used.PublicKeyAuthAlgorithms []string// NoClientAuth is true if clients are allowed to connect without// authenticating.// To determine NoClientAuth at runtime, set NoClientAuth to true// and the optional NoClientAuthCallback to a non-nil value.NoClientAuthbool// NoClientAuthCallback, if non-nil, is called when a user// attempts to authenticate with auth method "none".// NoClientAuth must also be set to true for this be used, or// this func is unused.NoClientAuthCallback func(ConnMetadata) (*Permissions,error)// 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.MaxAuthTriesint// PasswordCallback, if non-nil, is called when a user// attempts to authenticate using a password.PasswordCallback func(connConnMetadata, password []byte) (*Permissions,error)// 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.PublicKeyCallback func(connConnMetadata, keyPublicKey) (*Permissions,error)// VerifiedPublicKeyCallback, if non-nil, is called after a client// successfully confirms having control over a key that was previously// approved by PublicKeyCallback. The permissions object passed to the// callback is the one returned by PublicKeyCallback for the given public// key and its ownership is transferred to the callback. The returned// Permissions object can be the same object, optionally modified, or a// completely new object. If VerifiedPublicKeyCallback is non-nil,// PublicKeyCallback is not allowed to return a PartialSuccessError, which// can instead be returned by VerifiedPublicKeyCallback.//// VerifiedPublicKeyCallback does not affect which authentication methods// are included in the list of methods that can be attempted by the client.VerifiedPublicKeyCallback func(connConnMetadata, keyPublicKey, permissions *Permissions,signatureAlgorithmstring) (*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(connConnMetadata, clientKeyboardInteractiveChallenge) (*Permissions,error)// AuthLogCallback, if non-nil, is called to log all authentication// attempts.AuthLogCallback func(connConnMetadata, methodstring, errerror)// PreAuthConnCallback, if non-nil, is called upon receiving a new connection// before any authentication has started. The provided ServerPreAuthConn// can be used at any time before authentication is complete, including// after this callback has returned.PreAuthConnCallback func(ServerPreAuthConn)// ServerVersion is the version identification string to announce in// the public handshake.// If empty, a reasonable default is used.// Note thatRFC 4253 section 4.2 requires that this string start with// "SSH-2.0-".ServerVersionstring// BannerCallback, if present, is called and the return string is sent to// the client after key exchange completed but before authentication.BannerCallback func(connConnMetadata)string// GSSAPIWithMICConfig includes gssapi server and callback, which if both non-nil, is used// when gssapi-with-mic authentication is selected (RFC 4462 section 3).GSSAPIWithMICConfig *GSSAPIWithMICConfig// contains filtered or unexported fields}

ServerConfig holds server specific configuration data.

Example
package mainimport ("fmt""log""os""golang.org/x/crypto/ssh")func main() {// Minimal ServerConfig with SHA-1 algorithms disabled and supporting only// public key authentication.// The algorithms returned by ssh.SupportedAlgorithms() are different from// the default ones and do not include algorithms that are considered// insecure, such as those using SHA-1, returned by// ssh.InsecureAlgorithms().algorithms := ssh.SupportedAlgorithms()// Public key authentication is done by comparing// the public key of a received connection// with the entries in the authorized_keys file.authorizedKeysBytes, err := os.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())] = trueauthorizedKeysBytes = rest}config := &ssh.ServerConfig{Config: ssh.Config{KeyExchanges: algorithms.KeyExchanges,Ciphers:      algorithms.Ciphers,MACs:         algorithms.MACs,},// The configured PublicKeyAuthAlgorithms do not contain SHA-1 based// signature formats, so if the client attempts to use them the// authentication will fail before calling the defined callback.PublicKeyAuthAlgorithms: algorithms.PublicKeyAuths,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 := os.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)}// Restrict host key algorithms to disable ssh-rsa.signer, err := ssh.NewSignerWithAlgorithms(private.(ssh.AlgorithmSigner), []string{ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSASHA512})if err != nil {log.Fatal("Failed to create private key with restricted algorithms: ", err)}config.AddHostKey(signer)}

func (*ServerConfig)AddHostKey

func (s *ServerConfig) AddHostKey(keySigner)

AddHostKey adds a private key as a host key. If an existing hostkey exists with the same public key format, it is replaced. Each serverconfig must have at least one host key.

Example
package mainimport ("fmt""log""os""golang.org/x/crypto/ssh")func main() {// Minimal ServerConfig supporting only password authentication.config := &ssh.ServerConfig{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())},}privateBytes, err := os.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)}// Restrict host key algorithms to disable ssh-rsa.signer, err := ssh.NewSignerWithAlgorithms(private.(ssh.AlgorithmSigner), []string{ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSASHA512})if err != nil {log.Fatal("Failed to create private key with restricted algorithms: ", err)}config.AddHostKey(signer)}

typeServerConn

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 theserver

funcNewServerConn

func NewServerConn(cnet.Conn, config *ServerConfig) (*ServerConn, <-chanNewChannel, <-chan *Request,error)

NewServerConn starts a new SSH server with c as the underlyingtransport. It starts with a handshake and, if the handshake isunsuccessful, it closes the connection and returns an error. TheRequest and NewChannel channels must be serviced, or the connectionwill hang.

The returned error may be of type *ServerAuthError forauthentication errors.

Example
package mainimport ("fmt""log""net""os""sync""golang.org/x/crypto/ssh""golang.org/x/crypto/ssh/terminal")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 := os.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())] = trueauthorizedKeysBytes = 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 := os.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"])var wg sync.WaitGroupdefer wg.Wait()// The incoming Request channel must be serviced.wg.Add(1)go func() {ssh.DiscardRequests(reqs)wg.Done()}()// 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.wg.Add(1)go func(in <-chan *ssh.Request) {for req := range in {req.Reply(req.Type == "shell", nil)}wg.Done()}(requests)term := terminal.NewTerminal(channel, "> ")wg.Add(1)go func() {defer func() {channel.Close()wg.Done()}()for {line, err := term.ReadLine()if err != nil {break}fmt.Println(line)}}()}}

typeServerPreAuthConnadded inv0.33.0

type ServerPreAuthConn interface {ConnMetadata// SendAuthBanner sends a banner message to the client.// It returns an error once the authentication phase has ended.SendAuthBanner(string)error// contains filtered or unexported methods}

ServerPreAuthConn is the interface available on an incoming serverconnection before authentication has completed.

typeSession

type Session struct {// Stdin specifies the remote process's standard input.// If Stdin is nil, the remote process reads from an empty// bytes.Buffer.Stdinio.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 io.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.Stdoutio.WriterStderrio.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(cmdstring) ([]byte,error)

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

func (*Session)Output

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

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

func (*Session)RequestPty

func (s *Session) RequestPty(termstring, h, wint, termmodesTerminalModes)error

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

Example
package mainimport ("log""golang.org/x/crypto/ssh")func main() {var hostKey ssh.PublicKey// Create client configconfig := &ssh.ClientConfig{User: "username",Auth: []ssh.AuthMethod{ssh.Password("password"),},HostKeyCallback: ssh.FixedHostKey(hostKey),}// Connect to ssh serverconn, err := ssh.Dial("tcp", "localhost:22", config)if err != nil {log.Fatal("unable to connect: ", err)}defer conn.Close()// Create a sessionsession, err := conn.NewSession()if err != nil {log.Fatal("unable to create session: ", err)}defer session.Close()// Set up terminal modesmodes := ssh.TerminalModes{ssh.ECHO:          0,     // disable echoingssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaudssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud}// Request pseudo terminalif err := session.RequestPty("xterm", 40, 80, modes); err != nil {log.Fatal("request for pseudo terminal failed: ", err)}// Start remote shellif err := session.Shell(); err != nil {log.Fatal("failed to start shell: ", err)}}

func (*Session)RequestSubsystem

func (s *Session) RequestSubsystem(subsystemstring)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(cmdstring)error

Run runs cmd on the remote host. Typically, the remoteserver 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 problemscopying stdin, stdout, and stderr, and exits with a zero exitstatus.

If the remote server does not send an exit status, an error of type*ExitMissingError is returned. If the command completesunsuccessfully or is interrupted by a signal, the error is of type*ExitError. Other error types may be returned for I/O problems.

func (*Session)SendRequest

func (s *Session) SendRequest(namestring, wantReplybool, payload []byte) (bool,error)

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

func (*Session)Setenv

func (s *Session) Setenv(name, valuestring)error

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

func (*Session)Shell

func (s *Session) Shell()error

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

func (*Session)Signal

func (s *Session) Signal(sigSignal)error

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

func (*Session)Start

func (s *Session) Start(cmdstring)error

Start runs cmd on the remote host. Typically, the remoteserver 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 theremote command's standard error when the command starts.There is a fixed amount of buffering that is shared betweenstdout and stderr streams. If the StderrPipe reader isnot serviced fast enough it may eventually cause theremote command to block.

func (*Session)StdinPipe

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

StdinPipe returns a pipe that will be connected to theremote 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 theremote command's standard output when the command starts.There is a fixed amount of buffering that is shared betweenstdout and stderr streams. If the StdoutPipe reader isnot serviced fast enough it may eventually cause theremote 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 problemscopying stdin, stdout, and stderr, and exits with a zero exitstatus.

If the remote server does not send an exit status, an error of type*ExitMissingError is returned. If the command completesunsuccessfully or is interrupted by a signal, the error is of type*ExitError. Other error types may be returned for I/O problems.

func (*Session)WindowChange

func (s *Session) WindowChange(h, wint)error

WindowChange informs the remote host about a terminal window dimension change to h rows and w columns.

typeSignal

type Signalstring
const (SIGABRTSignal = "ABRT"SIGALRMSignal = "ALRM"SIGFPESignal = "FPE"SIGHUPSignal = "HUP"SIGILLSignal = "ILL"SIGINTSignal = "INT"SIGKILLSignal = "KILL"SIGPIPESignal = "PIPE"SIGQUITSignal = "QUIT"SIGSEGVSignal = "SEGV"SIGTERMSignal = "TERM"SIGUSR1Signal = "USR1"SIGUSR2Signal = "USR2")

POSIX signals as listed inRFC 4254 Section 6.10.

typeSignature

type Signature struct {FormatstringBlob   []byteRest   []byte `ssh:"rest"`}

Signature represents a cryptographic signature.

typeSigner

type Signer interface {// PublicKey returns the associated PublicKey.PublicKey()PublicKey// Sign returns a signature for the given data. This method will hash the// data appropriately first. The signature algorithm is expected to match// the key format returned by the PublicKey.Type method (and not to be any// alternative algorithm supported by the key format).Sign(randio.Reader, data []byte) (*Signature,error)}

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

Some Signers provided by this package also implement MultiAlgorithmSigner.

funcNewCertSigner

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

NewCertSigner returns a Signer that signs with the given Certificate, whoseprivate key is held by signer. It returns an error if the public key in certdoesn't match the key used by signer.

funcNewSignerFromKey

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

NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey,*ecdsa.PrivateKey or any other crypto.Signer and returns acorresponding Signer instance. ECDSA keys must use P-256, P-384 orP-521. DSA keys must use parameter size L1024N160.

funcNewSignerFromSigner

func NewSignerFromSigner(signercrypto.Signer) (Signer,error)

NewSignerFromSigner takes any crypto.Signer implementation andreturns a corresponding Signer interface. This can be used, forexample, with keys kept in hardware modules.

funcParsePrivateKey

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

ParsePrivateKey returns a Signer from a PEM encoded private key. It supportsthe same keys as ParseRawPrivateKey. If the private key is encrypted, itwill return a PassphraseMissingError.

funcParsePrivateKeyWithPassphrase

func ParsePrivateKeyWithPassphrase(pemBytes, passphrase []byte) (Signer,error)

ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded privatekey and passphrase. It supports the same keys asParseRawPrivateKeyWithPassphrase.

typeTerminalModes

type TerminalModes map[uint8]uint32

typeWaitmsg

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

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

func (Waitmsg)ExitStatus

func (wWaitmsg) ExitStatus()int

ExitStatus returns the exit status of the remote command.

func (Waitmsg)Lang

func (wWaitmsg) Lang()string

Lang returns the language tag. SeeRFC 3066

func (Waitmsg)Msg

func (wWaitmsg) Msg()string

Msg returns the exit message given by the remote command

func (Waitmsg)Signal

func (wWaitmsg) Signal()string

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

func (Waitmsg)String

func (wWaitmsg) String()string

Source Files

View all Source files

Directories

PathSynopsis
Package agent implements the ssh-agent protocol, and provides both a client and a server.
Package agent implements the ssh-agent protocol, and provides both a client and a server.
internal
bcrypt_pbkdf
Package bcrypt_pbkdf implements bcrypt_pbkdf(3) from OpenBSD.
Package bcrypt_pbkdf implements bcrypt_pbkdf(3) from OpenBSD.
Package knownhosts implements a parser for the OpenSSH known_hosts host key database, and provides utility functions for writing OpenSSH compliant known_hosts files.
Package knownhosts implements a parser for the OpenSSH known_hosts host key database, and provides utility functions for writing OpenSSH compliant known_hosts files.
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.
Package test contains integration tests for the golang.org/x/crypto/ssh package.
Package test contains integration tests for the golang.org/x/crypto/ssh package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp