pkg.go.dev
Open in
urlscan Pro
2600:1901:0:f535::
Public Scan
Submitted URL: http://golang.org/x/crypto/ssh
Effective URL: https://pkg.go.dev/golang.org/x/crypto/ssh
Submission: On September 09 via api from US — Scanned from GB
Effective URL: https://pkg.go.dev/golang.org/x/crypto/ssh
Submission: On September 09 via api from US — Scanned from GB
Form analysis
3 forms found in the DOM/search
<form class="go-InputGroup go-ShortcutKey go-SearchForm-form" action="/search" data-shortcut="/" data-shortcut-alt="search" data-gtmc="search form" aria-label="Search for a package" role="search">
<input name="q" class="go-Input js-searchFocus" aria-label="Search for a package" type="search" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" placeholder="Search packages or symbols" value="">
<input name="m" value="" hidden="">
<button class="go-Button go-Button--inverted" aria-label="Submit search">
<img class="go-Icon" height="24" width="24" src="/static/shared/icon/search_gm_grey_24dp.svg" alt="">
</button>
</form>
DIALOG
<form method="dialog" data-gmtc="jump to form" aria-label="Jump to Identifier">
<div class="Dialog-title go-Modal-header">
<h2>Jump to</h2>
<button class="go-Button go-Button--inline" type="button" data-modal-close="" data-gtmc="modal button" aria-label="Close">
<img class="go-Icon" height="24" width="24" src="/static/shared/icon/close_gm_grey_24dp.svg" alt="">
</button>
</div>
<div class="JumpDialog-filter">
<input class="JumpDialog-input go-Input" autocomplete="off" type="text">
</div>
<div class="JumpDialog-body go-Modal-body">
<div class="JumpDialog-list"></div>
</div>
<div class="go-Modal-actions">
<button class="go-Button" data-test-id="close-dialog">Close</button>
</div>
</form>
DIALOG
<form method="dialog">
<div class="go-Modal-header">
<h2>Keyboard shortcuts</h2>
<button class="go-Button go-Button--inline" type="button" data-modal-close="" data-gtmc="modal button" aria-label="Close">
<img class="go-Icon" height="24" width="24" src="/static/shared/icon/close_gm_grey_24dp.svg" alt="">
</button>
</div>
<div class="go-Modal-body">
<table>
<tbody>
<tr>
<td class="ShortcutsDialog-key">
<strong>?</strong>
</td>
<td> : This menu</td>
</tr>
<tr>
<td class="ShortcutsDialog-key">
<strong>/</strong>
</td>
<td> : Search site</td>
</tr>
<tr>
<td class="ShortcutsDialog-key">
<strong>f</strong> or <strong>F</strong>
</td>
<td> : Jump to</td>
</tr>
<tr>
<td class="ShortcutsDialog-key"><strong>y</strong> or <strong>Y</strong></td>
<td> : Canonical URL</td>
</tr>
</tbody>
</table>
</div>
<div class="go-Modal-actions">
<button class="go-Button" data-test-id="close-dialog">Close</button>
</div>
</form>
Text Content
Skip to Main Content * Why Go * Case Studies Common problems companies solve with Go * Use Cases Stories about how and why companies use Go * Security Policy How Go can help keep you secure by default * Learn * Docs * Effective Go Tips for writing clear, performant, and idiomatic Go code * Go User Manual A complete introduction to building software with Go * Standard library Reference documentation for Go's standard library * Release Notes Learn what's new in each Go release * Packages * Community * Recorded Talks Videos from prior events * Meetups Meet other local Go developers * Conferences Learn and network with Go developers from around the world * Go blog The Go project's official blog. * Go project Get help and stay informed from Go * Get connected * Why Go Why Go * Case Studies * Use Cases * Security Policy * Learn * Docs Docs * Effective Go * Go User Manual * Standard library * Release Notes * Packages * Community Community * Recorded Talks * Meetups * Conferences * Go blog * Go project * Get connected 1. Discover Packages 2. golang.org/x/crypto 3. ssh SSH package Version: v0.27.0 Opens a new window with list of versions in this module. Latest Latest This package is not in the latest version of its module. Go to latest Published: Sep 4, 2024 License: BSD-3-Clause Opens a new window with license information. Imports: 47 Opens a new window with list of imports. Imported by: 18,804 Opens a new window with list of known importers. Main Versions Licenses Imports Imported By DETAILS * Valid go.mod file The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go. * Redistributable license Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed. * Tagged version Modules with tagged versions give importers more predictable builds. * Stable version When a project reaches major version v1 it is considered stable. * Learn more about best practices REPOSITORY cs.opensource.google/go/x/crypto LINKS * Report a Vulnerability * Open Source Insights Jump to ... * Documentation * Overview * Index * Examples * Constants * Variables * Functions * DiscardRequests(in) * FingerprintLegacyMD5(pubKey) * FingerprintSHA256(pubKey) * Marshal(msg) * MarshalAuthorizedKey(key) * MarshalPrivateKey(key, comment) * MarshalPrivateKeyWithPassphrase(key, comment, passphrase) * ParseDSAPrivateKey(der) * ParseRawPrivateKey(pemBytes) * ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase) * Unmarshal(data, out) * Types * type AlgorithmSigner * type AuthMethod * GSSAPIWithMICAuthMethod(gssAPIClient, target) * KeyboardInteractive(challenge) * Password(secret) * PasswordCallback(prompt) * PublicKeys(signers) * PublicKeysCallback(getSigners) * RetryableAuthMethod(auth, maxTries) * type BannerCallback * BannerDisplayStderr() * type BannerError * (b) Error() * (b) Unwrap() * type CertChecker * (c) Authenticate(conn, pubKey) * (c) CheckCert(principal, cert) * (c) CheckHostKey(addr, remote, key) * type Certificate * (c) Marshal() * (c) SignCert(rand, authority) * (c) Type() * (c) Verify(data, sig) * type Channel * type Client * Dial(network, addr, config) * NewClient(c, chans, reqs) * (c) Dial(n, addr) * (c) DialContext(ctx, n, addr) * (c) DialTCP(n, laddr, raddr) * (c) HandleChannelOpen(channelType) * (c) Listen(n, addr) * (c) ListenTCP(laddr) * (c) ListenUnix(socketPath) * (c) NewSession() * type ClientConfig * type Config * (c) SetDefaults() * type Conn * NewClientConn(c, addr, config) * type ConnMetadata * type CryptoPublicKey * type ExitError * (e) Error() * type ExitMissingError * (e) Error() * type GSSAPIClient * type GSSAPIServer * type GSSAPIWithMICConfig * type HostKeyCallback * FixedHostKey(key) * InsecureIgnoreHostKey() * type KeyboardInteractiveChallenge * type MultiAlgorithmSigner * NewSignerWithAlgorithms(signer, algorithms) * type NewChannel * type OpenChannelError * (e) Error() * type PartialSuccessError * (p) Error() * type PassphraseMissingError * Error() * type Permissions * type PublicKey * NewPublicKey(key) * ParseAuthorizedKey(in) * ParseKnownHosts(in) * ParsePublicKey(in) * type RejectionReason * (r) String() * type Request * (r) Reply(ok, payload) * type ServerAuthCallbacks * type ServerAuthError * (l) Error() * type ServerConfig * (s) AddHostKey(key) * type ServerConn * NewServerConn(c, config) * type Session * (s) Close() * (s) CombinedOutput(cmd) * (s) Output(cmd) * (s) RequestPty(term, h, w, termmodes) * (s) RequestSubsystem(subsystem) * (s) Run(cmd) * (s) SendRequest(name, wantReply, payload) * (s) Setenv(name, value) * (s) Shell() * (s) Signal(sig) * (s) Start(cmd) * (s) StderrPipe() * (s) StdinPipe() * (s) StdoutPipe() * (s) Wait() * (s) WindowChange(h, w) * type Signal * type Signature * type Signer * NewCertSigner(cert, signer) * NewSignerFromKey(key) * NewSignerFromSigner(signer) * ParsePrivateKey(pemBytes) * ParsePrivateKeyWithPassphrase(pemBytes, passphrase) * type TerminalModes * type Waitmsg * (w) ExitStatus() * (w) Lang() * (w) Msg() * (w) Signal() * (w) String() * Source Files * Directories DocumentationSource FilesDirectoriesOverviewIndexConstantsVariablesFunctionsTypesExamplesDiscardRequests(in)FingerprintLegacyMD5(pubKey)FingerprintSHA256(pubKey)Marshal(msg)MarshalAuthorizedKey(key)MarshalPrivateKey(key, comment)MarshalPrivateKeyWithPassphrase(key, comment, passphrase)ParseDSAPrivateKey(der)ParseRawPrivateKey(pemBytes)ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase)Unmarshal(data, out)type AlgorithmSignertype AuthMethodtype BannerCallbacktype BannerErrortype CertCheckertype Certificatetype Channeltype Clienttype ClientConfigtype Configtype Conntype ConnMetadatatype CryptoPublicKeytype ExitErrortype ExitMissingErrortype GSSAPIClienttype GSSAPIServertype GSSAPIWithMICConfigtype HostKeyCallbacktype KeyboardInteractiveChallengetype MultiAlgorithmSignertype NewChanneltype OpenChannelErrortype PartialSuccessErrortype PassphraseMissingErrortype Permissionstype PublicKeytype RejectionReasontype Requesttype ServerAuthCallbackstype ServerAuthErrortype ServerConfigtype ServerConntype Sessiontype Signaltype Signaturetype Signertype TerminalModestype WaitmsgGSSAPIWithMICAuthMethod(gssAPIClient, target)KeyboardInteractive(challenge)Password(secret)PasswordCallback(prompt)PublicKeys(signers)PublicKeysCallback(getSigners)RetryableAuthMethod(auth, maxTries)BannerDisplayStderr()(b) Error()(b) Unwrap()(c) Authenticate(conn, pubKey)(c) CheckCert(principal, cert)(c) CheckHostKey(addr, remote, key)(c) Marshal()(c) SignCert(rand, authority)(c) Type()(c) Verify(data, sig)Dial(network, addr, config)NewClient(c, chans, reqs)(c) Dial(n, addr)(c) DialContext(ctx, n, addr)(c) DialTCP(n, laddr, raddr)(c) HandleChannelOpen(channelType)(c) Listen(n, addr)(c) ListenTCP(laddr)(c) ListenUnix(socketPath)(c) NewSession()(c) SetDefaults()NewClientConn(c, addr, config)(e) Error()(e) Error()FixedHostKey(key)InsecureIgnoreHostKey()NewSignerWithAlgorithms(signer, algorithms)(e) Error()(p) Error()Error()NewPublicKey(key)ParseAuthorizedKey(in)ParseKnownHosts(in)ParsePublicKey(in)(r) String()(r) Reply(ok, payload)(l) Error()(s) AddHostKey(key)NewServerConn(c, config)(s) Close()(s) CombinedOutput(cmd)(s) Output(cmd)(s) RequestPty(term, h, w, termmodes)(s) RequestSubsystem(subsystem)(s) Run(cmd)(s) SendRequest(name, wantReply, payload)(s) Setenv(name, value)(s) Shell()(s) Signal(sig)(s) Start(cmd)(s) StderrPipe()(s) StdinPipe()(s) StdoutPipe()(s) Wait()(s) WindowChange(h, w)NewCertSigner(cert, signer)NewSignerFromKey(key)NewSignerFromSigner(signer)ParsePrivateKey(pemBytes)ParsePrivateKeyWithPassphrase(pemBytes, passphrase)(w) ExitStatus()(w) Lang()(w) Msg()(w) Signal()(w) String() DOCUMENTATION ¶ OVERVIEW ¶ Package ssh implements an SSH client and server. SSH is a transport security protocol, an authentication protocol and a family of application protocols. The most typical application level protocol is a remote shell and this is specifically implemented. However, the multiplexed nature of SSH is exposed to users that wish to support others. References: [PROTOCOL]: 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 This package does not fall under the stability promise of the Go language itself, so its API may be changed when pressing needs arise. INDEX ¶ * Constants * Variables * func DiscardRequests(in <-chan *Request) * func FingerprintLegacyMD5(pubKey PublicKey) string * func FingerprintSHA256(pubKey PublicKey) string * func Marshal(msg interface{}) []byte * func MarshalAuthorizedKey(key PublicKey) []byte * func MarshalPrivateKey(key crypto.PrivateKey, comment string) (*pem.Block, error) * func MarshalPrivateKeyWithPassphrase(key crypto.PrivateKey, comment string, passphrase []byte) (*pem.Block, error) * func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) * func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) * func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{}, error) * func Unmarshal(data []byte, out interface{}) error * type AlgorithmSigner * type AuthMethod * * func GSSAPIWithMICAuthMethod(gssAPIClient GSSAPIClient, target string) AuthMethod * func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod * func Password(secret string) AuthMethod * func PasswordCallback(prompt func() (secret string, err error)) AuthMethod * func PublicKeys(signers ...Signer) AuthMethod * func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod * func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod * type BannerCallback * * func BannerDisplayStderr() BannerCallback * type BannerError * * func (b *BannerError) Error() string * func (b *BannerError) Unwrap() error * type CertChecker * * func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permissions, error) * func (c *CertChecker) CheckCert(principal string, cert *Certificate) error * func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey) error * type Certificate * * func (c *Certificate) Marshal() []byte * func (c *Certificate) SignCert(rand io.Reader, authority Signer) error * func (c *Certificate) Type() string * func (c *Certificate) Verify(data []byte, sig *Signature) error * type Channel * type Client * * func Dial(network, addr string, config *ClientConfig) (*Client, error) * func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client * * func (c *Client) Dial(n, addr string) (net.Conn, error) * func (c *Client) DialContext(ctx context.Context, n, addr string) (net.Conn, error) * func (c *Client) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) * func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel * func (c *Client) Listen(n, addr string) (net.Listener, error) * func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) * func (c *Client) ListenUnix(socketPath string) (net.Listener, error) * func (c *Client) NewSession() (*Session, error) * type ClientConfig * type Config * * func (c *Config) SetDefaults() * type Conn * * func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error) * type ConnMetadata * type CryptoPublicKey * type ExitError * * func (e *ExitError) Error() string * type ExitMissingError * * func (e *ExitMissingError) Error() string * type GSSAPIClient * type GSSAPIServer * type GSSAPIWithMICConfig * type HostKeyCallback * * func FixedHostKey(key PublicKey) HostKeyCallback * func InsecureIgnoreHostKey() HostKeyCallback * type KeyboardInteractiveChallenge * type MultiAlgorithmSigner * * func NewSignerWithAlgorithms(signer AlgorithmSigner, algorithms []string) (MultiAlgorithmSigner, error) * type NewChannel * type OpenChannelError * * func (e *OpenChannelError) Error() string * type PartialSuccessError * * func (p *PartialSuccessError) Error() string * type PassphraseMissingError * * func (*PassphraseMissingError) Error() string * type Permissions * type PublicKey * * func NewPublicKey(key interface{}) (PublicKey, error) * func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) * func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey, comment string, rest []byte, ...) * func ParsePublicKey(in []byte) (out PublicKey, err error) * type RejectionReason * * func (r RejectionReason) String() string * type Request * * func (r *Request) Reply(ok bool, payload []byte) error * type ServerAuthCallbacks * type ServerAuthError * * func (l ServerAuthError) Error() string * type ServerConfig * * func (s *ServerConfig) AddHostKey(key Signer) * type ServerConn * * func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error) * type Session * * func (s *Session) Close() error * func (s *Session) CombinedOutput(cmd string) ([]byte, error) * func (s *Session) Output(cmd string) ([]byte, error) * func (s *Session) RequestPty(term string, h, w int, termmodes TerminalModes) error * func (s *Session) RequestSubsystem(subsystem string) error * func (s *Session) Run(cmd string) error * func (s *Session) SendRequest(name string, wantReply bool, payload []byte) (bool, error) * func (s *Session) Setenv(name, value string) error * func (s *Session) Shell() error * func (s *Session) Signal(sig Signal) error * func (s *Session) Start(cmd string) error * func (s *Session) StderrPipe() (io.Reader, error) * func (s *Session) StdinPipe() (io.WriteCloser, error) * func (s *Session) StdoutPipe() (io.Reader, error) * func (s *Session) Wait() error * func (s *Session) WindowChange(h, w int) error * type Signal * type Signature * type Signer * * func NewCertSigner(cert *Certificate, signer Signer) (Signer, error) * func NewSignerFromKey(key interface{}) (Signer, error) * func NewSignerFromSigner(signer crypto.Signer) (Signer, error) * func ParsePrivateKey(pemBytes []byte) (Signer, error) * func ParsePrivateKeyWithPassphrase(pemBytes, passphrase []byte) (Signer, error) * type TerminalModes * type Waitmsg * * func (w Waitmsg) ExitStatus() int * func (w Waitmsg) Lang() string * func (w Waitmsg) Msg() string * func (w Waitmsg) Signal() string * func (w Waitmsg) String() string EXAMPLES ¶ * Certificate.SignCert * Client.Listen * Dial * NewServerConn * PublicKeys * RetryableAuthMethod * ServerConfig.AddHostKey * Session.RequestPty CONSTANTS ¶ View Source const ( CertAlgoRSAv01 = "ssh-rsa-cert-v01@openssh.com" CertAlgoDSAv01 = "ssh-dss-cert-v01@openssh.com" CertAlgoECDSA256v01 = "ecdsa-sha2-nistp256-cert-v01@openssh.com" CertAlgoECDSA384v01 = "ecdsa-sha2-nistp384-cert-v01@openssh.com" CertAlgoECDSA521v01 = "ecdsa-sha2-nistp521-cert-v01@openssh.com" 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 appear in Certificate.Type, PublicKey.Type, and ClientConfig.HostKeyAlgorithms. Unlike key algorithm names, these are not passed to AlgorithmSigner nor returned by MultiAlgorithmSigner and don't appear in the Signature.Format field. View Source const ( // Deprecated: use CertAlgoRSAv01. CertSigAlgoRSAv01 = CertAlgoRSAv01 // Deprecated: use CertAlgoRSASHA256v01. CertSigAlgoRSASHA2256v01 = CertAlgoRSASHA256v01 // Deprecated: use CertAlgoRSASHA512v01. CertSigAlgoRSASHA2512v01 = CertAlgoRSASHA512v01 ) View Source const ( UserCert = 1 HostCert = 2 ) Certificate types distinguish between host and user certificates. The values can be set in the CertType field of Certificate. View Source const ( KeyAlgoRSA = "ssh-rsa" KeyAlgoDSA = "ssh-dss" KeyAlgoECDSA256 = "ecdsa-sha2-nistp256" 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. See RFC 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 AlgorithmSigner arguments. View Source const ( // Deprecated: use KeyAlgoRSA. SigAlgoRSA = KeyAlgoRSA // Deprecated: use KeyAlgoRSASHA256. SigAlgoRSASHA2256 = KeyAlgoRSASHA256 // Deprecated: use KeyAlgoRSASHA512. SigAlgoRSASHA2512 = KeyAlgoRSASHA512 ) View Source const ( VINTR = 1 VQUIT = 2 VERASE = 3 VKILL = 4 VEOF = 5 VEOL = 6 VEOL2 = 7 VSTART = 8 VSTOP = 9 VSUSP = 10 VDSUSP = 11 VREPRINT = 12 VWERASE = 13 VLNEXT = 14 VFLUSH = 15 VSWTCH = 16 VSTATUS = 17 VDISCARD = 18 IGNPAR = 30 PARMRK = 31 INPCK = 32 ISTRIP = 33 INLCR = 34 IGNCR = 35 ICRNL = 36 IUCLC = 37 IXON = 38 IXANY = 39 IXOFF = 40 IMAXBEL = 41 IUTF8 = 42 // RFC 8160 ISIG = 50 ICANON = 51 XCASE = 52 ECHO = 53 ECHOE = 54 ECHOK = 55 ECHONL = 56 NOFLSH = 57 TOSTOP = 58 IEXTEN = 59 ECHOCTL = 60 ECHOKE = 61 PENDIN = 62 OPOST = 70 OLCUC = 71 ONLCR = 72 OCRNL = 73 ONOCR = 74 ONLRET = 75 CS7 = 90 CS8 = 91 PARENB = 92 PARODD = 93 TTY_OP_ISPEED = 128 TTY_OP_OSPEED = 129 ) POSIX terminal mode flags as listed in RFC 4254 Section 8. View Source const CertTimeInfinity = 1<<64 - 1 CertTimeInfinity can be used for OpenSSHCertV01.ValidBefore to indicate that a certificate does not expire. VARIABLES ¶ View Source var ErrNoAuth = errors.New("ssh: no auth passed yet") 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. FUNCTIONS ¶ FUNC DISCARDREQUESTS ¶ func DiscardRequests(in <-chan *Request) DiscardRequests consumes and rejects all requests from the passed-in channel. FUNC FINGERPRINTLEGACYMD5 ¶ func FingerprintLegacyMD5(pubKey PublicKey) string FingerprintLegacyMD5 returns the user presentation of the key's fingerprint as described by RFC 4716 section 4. FUNC FINGERPRINTSHA256 ¶ func FingerprintSHA256(pubKey PublicKey) string 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) FUNC MARSHAL ¶ func Marshal(msg interface{}) []byte Marshal serializes the message in msg to SSH wire format. The msg argument should be a struct or pointer to struct. If the first member has the "sshtype" tag set to a number in decimal, that number is prepended to the result. If the last of member has the "ssh" tag set to "rest", its contents are appended to the output. FUNC MARSHALAUTHORIZEDKEY ¶ func MarshalAuthorizedKey(key PublicKey) []byte MarshalAuthorizedKey serializes key for inclusion in an OpenSSH authorized_keys file. The return value ends with newline. FUNC MARSHALPRIVATEKEY ¶ ADDED IN V0.14.0 func MarshalPrivateKey(key crypto.PrivateKey, comment string) (*pem.Block, error) MarshalPrivateKey returns a PEM block with the private key serialized in the OpenSSH format. FUNC MARSHALPRIVATEKEYWITHPASSPHRASE ¶ ADDED IN V0.14.0 func MarshalPrivateKeyWithPassphrase(key crypto.PrivateKey, comment string, passphrase []byte) (*pem.Block, error) MarshalPrivateKeyWithPassphrase returns a PEM block holding the encrypted private key serialized in the OpenSSH format. FUNC PARSEDSAPRIVATEKEY ¶ func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as specified by the OpenSSL DSA man page. FUNC PARSERAWPRIVATEKEY ¶ func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) ParseRawPrivateKey returns a private key from a PEM encoded private key. It supports RSA, DSA, ECDSA, and Ed25519 private keys in PKCS#1, PKCS#8, OpenSSL, and OpenSSH formats. If the private key is encrypted, it will return a PassphraseMissingError. FUNC PARSERAWPRIVATEKEYWITHPASSPHRASE ¶ func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{}, error) ParseRawPrivateKeyWithPassphrase returns a private key decrypted with passphrase from a PEM encoded private key. If the passphrase is wrong, it will return x509.IncorrectPasswordError. FUNC UNMARSHAL ¶ func Unmarshal(data []byte, out interface{}) error Unmarshal parses data in SSH wire format into a structure. The out argument should be a pointer to struct. If the first member of the struct has the "sshtype" tag set to a '|'-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. TYPES ¶ TYPE ALGORITHMSIGNER ¶ 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(rand io.Reader, data []byte, algorithm string) (*Signature, error) } An AlgorithmSigner is a Signer that also supports specifying an algorithm to use for signing. An AlgorithmSigner can't advertise the algorithms it supports, unless it also implements MultiAlgorithmSigner, so it should be prepared to be invoked with every algorithm supported by the public key format. TYPE AUTHMETHOD ¶ type AuthMethod interface { // contains filtered or unexported methods } An AuthMethod represents an instance of an RFC 4252 authentication method. FUNC GSSAPIWITHMICAUTHMETHOD ¶ func GSSAPIWithMICAuthMethod(gssAPIClient GSSAPIClient, target string) AuthMethod 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. FUNC KEYBOARDINTERACTIVE ¶ func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod KeyboardInteractive returns an AuthMethod using a prompt/response sequence controlled by the server. FUNC PASSWORD ¶ func Password(secret string) AuthMethod Password returns an AuthMethod using the given password. FUNC PASSWORDCALLBACK ¶ func PasswordCallback(prompt func() (secret string, err error)) AuthMethod PasswordCallback returns an AuthMethod that uses a callback for fetching a password. FUNC PUBLICKEYS ¶ func PublicKeys(signers ...Signer) AuthMethod PublicKeys returns an AuthMethod that uses the given key pairs. Example ¶ Output: Share Format Run FUNC PUBLICKEYSCALLBACK ¶ func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod PublicKeysCallback returns an AuthMethod that runs the given function to obtain a list of key pairs. FUNC RETRYABLEAUTHMETHOD ¶ func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod 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). Example ¶ Output: TYPE BANNERCALLBACK ¶ type BannerCallback func(message string) error 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 ¶ func BannerDisplayStderr() BannerCallback BannerDisplayStderr returns a function that can be used for ClientConfig.BannerCallback to display banners on os.Stderr. TYPE BANNERERROR ¶ ADDED IN V0.24.0 type BannerError struct { Err error Message string } BannerError is an error that can be returned by authentication handlers in ServerConfig to send a banner message to the client. FUNC (*BANNERERROR) ERROR ¶ ADDED IN V0.24.0 func (b *BannerError) Error() string FUNC (*BANNERERROR) UNWRAP ¶ ADDED IN V0.24.0 func (b *BannerError) Unwrap() error TYPE CERTCHECKER ¶ 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 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. IsUserAuthority func(auth PublicKey) bool // 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. IsHostAuthority func(auth PublicKey, address string) 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(conn ConnMetadata, key PublicKey) (*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. HostKeyFallback HostKeyCallback // 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 methods can be plugged into ClientConfig.HostKeyCallback and ServerConfig.PublicKeyCallback. For the CertChecker to work, minimally, the IsAuthority callback should be set. FUNC (*CERTCHECKER) AUTHENTICATE ¶ func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permissions, error) Authenticate checks a user certificate. Authenticate can be used as a value for ServerConfig.PublicKeyCallback. FUNC (*CERTCHECKER) CHECKCERT ¶ func (c *CertChecker) CheckCert(principal string, cert *Certificate) error CheckCert checks CriticalOptions, ValidPrincipals, revocation, timestamp and the signature of the certificate. FUNC (*CERTCHECKER) CHECKHOSTKEY ¶ func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey) error CheckHostKey checks a host key certificate. This method can be plugged into ClientConfig.HostKeyCallback. TYPE CERTIFICATE ¶ type Certificate struct { Nonce []byte Key PublicKey Serial uint64 CertType uint32 KeyId string ValidPrincipals []string ValidAfter uint64 ValidBefore uint64 Permissions Reserved []byte SignatureKey PublicKey Signature *Signature } An Certificate represents an OpenSSH certificate as defined in [PROTOCOL.certkeys]?rev=1.8. The Certificate type implements the PublicKey interface, so it can be unmarshaled using ParsePublicKey. FUNC (*CERTIFICATE) MARSHAL ¶ func (c *Certificate) Marshal() []byte Marshal serializes c into OpenSSH's wire format. It is part of the PublicKey interface. FUNC (*CERTIFICATE) SIGNCERT ¶ func (c *Certificate) SignCert(rand io.Reader, authority Signer) error SignCert signs the certificate with an authority, setting the Nonce, SignatureKey, and Signature fields. If the authority implements the MultiAlgorithmSigner interface the first algorithm in the list is used. This is useful if you want to sign with a specific algorithm. Example ¶ Output: Share Format Run 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 public key. It is part of the PublicKey interface. TYPE CHANNEL ¶ type Channel interface { // Read reads up to len(data) bytes from the channel. Read(data []byte) (int, error) // Write writes len(data) bytes to the channel. Write(data []byte) (int, error) // 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 data CloseWrite() error // SendRequest sends a channel request. If wantReply is true, // it will wait for a reply and return the result as a // boolean, otherwise the return value will be false. Channel // requests are out-of-band messages so they may be sent even // if the data stream is closed or blocked by flow control. // If the channel is closed before a reply is returned, io.EOF // is returned. SendRequest(name string, wantReply bool, payload []byte) (bool, error) // Stderr returns an io.ReadWriter that writes to this channel // with the extended data type set to stderr. Stderr 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 stream that is multiplexed over an SSH connection. TYPE CLIENT ¶ type Client struct { Conn // contains filtered or unexported fields } Client implements a traditional SSH client that supports shells, subprocesses, TCP port/streamlocal forwarding and tunneled dialing. FUNC DIAL ¶ func Dial(network, addr string, config *ClientConfig) (*Client, error) 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. Example ¶ Output: Share Format Run FUNC NEWCLIENT ¶ func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client NewClient creates a Client on top of the given connection. FUNC (*CLIENT) DIAL ¶ func (c *Client) Dial(n, addr string) (net.Conn, error) Dial initiates a connection to the addr from the remote host. The resulting connection has a zero LocalAddr() and RemoteAddr(). FUNC (*CLIENT) DIALCONTEXT ¶ ADDED IN V0.16.0 func (c *Client) DialContext(ctx context.Context, n, addr string) (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 the connection 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(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) DialTCP connects to the remote address raddr on the network net, which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used as the local address for the connection. FUNC (*CLIENT) HANDLECHANNELOPEN ¶ func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel HandleChannelOpen returns a channel on which NewChannel requests for the given type are sent. If the type already is being handled, nil is returned. The channel is closed when the connection is closed. FUNC (*CLIENT) LISTEN ¶ func (c *Client) Listen(n, addr string) (net.Listener, error) Listen requests the remote peer open a listening socket on addr. Incoming connections will be available by calling Accept on the returned net.Listener. The listener must be serviced, or the SSH connection may hang. N must be "tcp", "tcp4", "tcp6", or "unix". Example ¶ Output: Share Format Run FUNC (*CLIENT) LISTENTCP ¶ func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) ListenTCP requests the remote peer open a listening socket on laddr. Incoming connections will be available by calling Accept on the returned net.Listener. FUNC (*CLIENT) LISTENUNIX ¶ func (c *Client) ListenUnix(socketPath string) (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 remote execution of a program.) TYPE CLIENTCONFIG ¶ type ClientConfig struct { // Config contains configuration that is shared between clients and // servers. Config // User contains the username to authenticate as. User string // 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. 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. HostKeyCallback HostKeyCallback // 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. BannerCallback BannerCallback // ClientVersion contains the version identification string that will // be used for the connection. If empty, a reasonable default is used. ClientVersion string // 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. Timeout time.Duration } A ClientConfig structure is used to configure a Client. It must not be modified after having been passed to an SSH function. TYPE CONFIG ¶ type Config struct { // Rand provides the source of entropy for cryptographic // primitives. If Rand is nil, the cryptographic random reader // in package crypto/rand will be used. Rand io.Reader // The maximum number of bytes sent or received after which a // new key is negotiated. It must be at least 256. If // unspecified, a size suitable for the chosen cipher is used. RekeyThreshold uint64 // 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 and ClientConfig. FUNC (*CONFIG) SETDEFAULTS ¶ func (c *Config) SetDefaults() 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. TYPE CONN ¶ type Conn interface { ConnMetadata // SendRequest sends a global request, and returns the // reply. If wantReply is true, it returns the response status // and payload. See also RFC 4254, section 4. SendRequest(name string, wantReply bool, payload []byte) (bool, []byte, error) // OpenChannel tries to open an channel. If the request is // rejected, it returns *OpenChannelError. On success 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(name string, data []byte) (Channel, <-chan *Request, error) // Close closes the underlying network connection Close() error // Wait blocks until the connection has shut down, and returns the // error causing the shutdown. Wait() error } Conn represents an SSH connection for both server and client roles. Conn is the basis for implementing an application layer, such as ClientConn, which implements the traditional shell access for clients. FUNC NEWCLIENTCONN ¶ func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error) NewClientConn establishes an authenticated SSH connection using c as the underlying transport. The Request and NewChannel channels must be serviced or the connection will hang. TYPE CONNMETADATA ¶ type ConnMetadata interface { // User returns the user ID for this connection. 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. TYPE CRYPTOPUBLICKEY ¶ type CryptoPublicKey interface { CryptoPublicKey() crypto.PublicKey } CryptoPublicKey, if implemented by a PublicKey, returns the underlying crypto.PublicKey form of the key. TYPE EXITERROR ¶ type ExitError struct { Waitmsg } An ExitError reports unsuccessful completion of a remote command. FUNC (*EXITERROR) ERROR ¶ func (e *ExitError) Error() string TYPE EXITMISSINGERROR ¶ type ExitMissingError struct{} ExitMissingError is returned if a session is torn down cleanly, but the server sends no confirmation of the exit status. FUNC (*EXITMISSINGERROR) ERROR ¶ func (e *ExitMissingError) Error() string TYPE GSSAPICLIENT ¶ 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. // See RFC 2743 section 2.2.1 and RFC 4462 section 3.4. InitSecContext(target string, token []byte, isGSSDelegCreds bool) (outputToken []byte, needContinue bool, err error) // 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. 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. // See RFC 2743 section 2.2.3. DeleteSecContext() error } GSSAPIClient provides the API to plug-in GSSAPI authentication for client logins. TYPE GSSAPISERVER ¶ 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. // See RFC 2743 section 2.2.2 and RFC 4462 section 3.4. AcceptSecContext(token []byte) (outputToken []byte, srcName string, needContinue bool, err error) // 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. 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. // See RFC 2743 section 2.2.3. DeleteSecContext() error } GSSAPIServer provides the API to plug in GSSAPI authentication for server logins. TYPE GSSAPIWITHMICCONFIG ¶ 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(conn ConnMetadata, srcName string) (*Permissions, error) // Server must be set. It's the implementation // of the GSSAPIServer interface. See GSSAPIServer interface for details. Server GSSAPIServer } TYPE HOSTKEYCALLBACK ¶ type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) 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 ¶ func FixedHostKey(key PublicKey) HostKeyCallback FixedHostKey returns a function for use in ClientConfig.HostKeyCallback to accept only a specific host key. FUNC INSECUREIGNOREHOSTKEY ¶ func InsecureIgnoreHostKey() HostKeyCallback InsecureIgnoreHostKey returns a function that can be used for ClientConfig.HostKeyCallback to accept any host key. It should not be used for production code. TYPE KEYBOARDINTERACTIVECHALLENGE ¶ type KeyboardInteractiveChallenge func(name, instruction string, questions []string, echos []bool) (answers []string, err error) KeyboardInteractiveChallenge should print questions, optionally disabling echoing (e.g. for passwords), and return all the answers. Challenge may be called multiple times in a single session. After successful authentication, the server may send a challenge with no questions, for which the name and instruction messages should be printed. RFC 4256 section 3.3 details how the UI should behave for both CLI and GUI environments. TYPE MULTIALGORITHMSIGNER ¶ ADDED IN V0.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 algorithms supported by that signer. FUNC NEWSIGNERWITHALGORITHMS ¶ ADDED IN V0.14.0 func NewSignerWithAlgorithms(signer AlgorithmSigner, algorithms []string) (MultiAlgorithmSigner, error) NewSignerWithAlgorithms returns a signer restricted to the specified algorithms. The algorithms must be set in preference order. The list must not be empty, and it must not include certificate types. An error is returned if the specified algorithms are incompatible with the public key type. TYPE NEWCHANNEL ¶ 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(reason RejectionReason, message string) error // ChannelType returns the type of the channel, as supplied by the // client. ChannelType() string // ExtraData returns the arbitrary payload for this channel, as supplied // by the client. This data is specific to the channel type. ExtraData() []byte } NewChannel represents an incoming request to a channel. It must either be accepted for use by calling Accept, or rejected by calling Reject. TYPE OPENCHANNELERROR ¶ type OpenChannelError struct { Reason RejectionReason Message string } OpenChannelError is returned if the other side rejects an OpenChannel request. FUNC (*OPENCHANNELERROR) ERROR ¶ func (e *OpenChannelError) Error() string TYPE PARTIALSUCCESSERROR ¶ ADDED IN V0.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. Next ServerAuthCallbacks } PartialSuccessError can be returned by any of the ServerConfig authentication callbacks to indicate to the client that authentication has partially succeeded, but further steps are required. FUNC (*PARTIALSUCCESSERROR) ERROR ¶ ADDED IN V0.22.0 func (p *PartialSuccessError) Error() string TYPE PASSPHRASEMISSINGERROR ¶ type PassphraseMissingError struct { // PublicKey will be set if the private key format includes an unencrypted // public key along with the encrypted private key. PublicKey PublicKey } A PassphraseMissingError indicates that parsing this private key requires a passphrase. Use ParsePrivateKeyWithPassphrase. FUNC (*PASSPHRASEMISSINGERROR) ERROR ¶ func (*PassphraseMissingError) Error() string TYPE PERMISSIONS ¶ 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 } 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. TYPE PUBLICKEY ¶ 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. FUNC NEWPUBLICKEY ¶ 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. FUNC PARSEAUTHORIZEDKEY ¶ func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) ParseAuthorizedKey parses a public key from an authorized_keys file used in OpenSSH according to the sshd(8) manual page. FUNC PARSEKNOWNHOSTS ¶ func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey, comment string, rest []byte, err error) 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. FUNC PARSEPUBLICKEY ¶ func ParsePublicKey(in []byte) (out PublicKey, err error) ParsePublicKey parses an SSH public key formatted for use in the SSH wire protocol according to RFC 4253, section 6.6. TYPE REJECTIONREASON ¶ type RejectionReason uint32 RejectionReason is an enumeration used when rejecting channel creation requests. See RFC 4254, section 5.1. const ( Prohibited RejectionReason = iota + 1 ConnectionFailed UnknownChannelType ResourceShortage ) FUNC (REJECTIONREASON) STRING ¶ func (r RejectionReason) String() string String converts the rejection reason to human readable form. TYPE REQUEST ¶ type Request struct { Type string WantReply bool Payload []byte // contains filtered or unexported fields } Request is a request sent outside of the normal stream of data. Requests can either be specific to an SSH channel, or they can be global. FUNC (*REQUEST) REPLY ¶ func (r *Request) Reply(ok bool, payload []byte) error Reply sends a response to a request. It must be called for all requests where WantReply is true and is a no-op otherwise. The payload argument is ignored for replies to channel-specific requests. TYPE SERVERAUTHCALLBACKS ¶ ADDED IN V0.22.0 type ServerAuthCallbacks struct { // PasswordCallback behaves like [ServerConfig.PasswordCallback]. PasswordCallback func(conn ConnMetadata, password []byte) (*Permissions, error) // PublicKeyCallback behaves like [ServerConfig.PublicKeyCallback]. PublicKeyCallback func(conn ConnMetadata, key PublicKey) (*Permissions, error) // KeyboardInteractiveCallback behaves like [ServerConfig.KeyboardInteractiveCallback]. KeyboardInteractiveCallback func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) // GSSAPIWithMICConfig behaves like [ServerConfig.GSSAPIWithMICConfig]. GSSAPIWithMICConfig *GSSAPIWithMICConfig } ServerAuthCallbacks defines server-side authentication callbacks. TYPE SERVERAUTHERROR ¶ 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 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. FUNC (SERVERAUTHERROR) ERROR ¶ func (l ServerAuthError) Error() string TYPE SERVERCONFIG ¶ 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. NoClientAuth bool // 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. MaxAuthTries int // PasswordCallback, if non-nil, is called when a user // attempts to authenticate using a password. PasswordCallback func(conn ConnMetadata, password []byte) (*Permissions, error) // PublicKeyCallback, if non-nil, is called when a client // 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(conn ConnMetadata, key PublicKey) (*Permissions, error) // KeyboardInteractiveCallback, if non-nil, is called when // keyboard-interactive authentication is selected (RFC // 4256). The client object's Challenge function should be // used to query the user. The callback may offer multiple // Challenge rounds. To avoid information leaks, the client // should be presented a challenge even if the user is // unknown. KeyboardInteractiveCallback func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) // AuthLogCallback, if non-nil, is called to log all authentication // attempts. AuthLogCallback func(conn ConnMetadata, method string, err error) // 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-". ServerVersion string // BannerCallback, if present, is called and the return string is sent to // the client after key exchange completed but before authentication. BannerCallback func(conn ConnMetadata) 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. FUNC (*SERVERCONFIG) ADDHOSTKEY ¶ func (s *ServerConfig) AddHostKey(key Signer) AddHostKey adds a private key as a host key. If an existing host key exists with the same public key format, it is replaced. Each server config must have at least one host key. Example ¶ Output: Share Format Run TYPE SERVERCONN ¶ type ServerConn struct { Conn // If the succeeding authentication callback returned a // non-nil Permissions pointer, it is stored here. Permissions *Permissions } ServerConn is an authenticated SSH connection, as seen from the server FUNC NEWSERVERCONN ¶ func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error) NewServerConn starts a new SSH server with c as the underlying transport. It starts with a handshake and, if the handshake is unsuccessful, it closes the connection and returns an error. The Request and NewChannel channels must be serviced, or the connection will hang. The returned error may be of type *ServerAuthError for authentication errors. Example ¶ Output: Share Format Run TYPE SESSION ¶ type Session struct { // Stdin specifies the remote process's standard input. // If Stdin is nil, the remote process reads from an empty // bytes.Buffer. Stdin io.Reader // Stdout and Stderr specify the remote process's standard // output and error. // // If either is nil, Run connects the corresponding file // descriptor to an instance of 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. Stdout io.Writer Stderr io.Writer // contains filtered or unexported fields } A Session represents a connection to a remote command or shell. FUNC (*SESSION) CLOSE ¶ func (s *Session) Close() error FUNC (*SESSION) COMBINEDOUTPUT ¶ func (s *Session) CombinedOutput(cmd string) ([]byte, error) CombinedOutput runs cmd on the remote host and returns its combined standard output and standard error. FUNC (*SESSION) OUTPUT ¶ func (s *Session) Output(cmd string) ([]byte, error) Output runs cmd on the remote host and returns its standard output. FUNC (*SESSION) REQUESTPTY ¶ func (s *Session) RequestPty(term string, h, w int, termmodes TerminalModes) error RequestPty requests the association of a pty with the session on the remote host. Example ¶ Output: Share Format Run FUNC (*SESSION) REQUESTSUBSYSTEM ¶ func (s *Session) RequestSubsystem(subsystem string) error RequestSubsystem requests the association of a subsystem with the session on the remote host. A subsystem is a predefined command that runs in the background when the ssh session is initiated FUNC (*SESSION) RUN ¶ func (s *Session) Run(cmd string) error Run runs cmd on the remote host. Typically, the remote server passes cmd to the shell for interpretation. A Session only accepts one call to Run, Start, Shell, Output, or CombinedOutput. The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status. If the 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. FUNC (*SESSION) SENDREQUEST ¶ func (s *Session) SendRequest(name string, wantReply bool, payload []byte) (bool, error) SendRequest sends an out-of-band channel request on the SSH channel underlying the session. FUNC (*SESSION) SETENV ¶ func (s *Session) Setenv(name, value string) error Setenv sets an environment variable that will be applied to any command executed by Shell or Run. FUNC (*SESSION) SHELL ¶ func (s *Session) Shell() error Shell starts a login shell on the remote host. A Session only accepts one call to Run, Start, Shell, Output, or CombinedOutput. FUNC (*SESSION) SIGNAL ¶ func (s *Session) Signal(sig Signal) error Signal sends the given signal to the remote process. sig is one of the SIG* constants. FUNC (*SESSION) START ¶ func (s *Session) Start(cmd string) error Start runs cmd on the remote host. Typically, the remote server passes cmd to the shell for interpretation. A Session only accepts one call to Run, Start or Shell. FUNC (*SESSION) STDERRPIPE ¶ func (s *Session) StderrPipe() (io.Reader, error) StderrPipe returns a pipe that will be connected to the remote command's standard error when the command starts. There is a fixed amount of buffering that is shared between stdout and stderr streams. If the StderrPipe reader is not serviced fast enough it may eventually cause the remote command to block. FUNC (*SESSION) STDINPIPE ¶ func (s *Session) StdinPipe() (io.WriteCloser, error) StdinPipe returns a pipe that will be connected to the remote command's standard input when the command starts. FUNC (*SESSION) STDOUTPIPE ¶ func (s *Session) StdoutPipe() (io.Reader, error) StdoutPipe returns a pipe that will be connected to the remote command's standard output when the command starts. There is a fixed amount of buffering that is shared between stdout and stderr streams. If the StdoutPipe reader is not serviced fast enough it may eventually cause the remote command to block. FUNC (*SESSION) WAIT ¶ func (s *Session) Wait() error Wait waits for the remote command to exit. The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status. If the 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. FUNC (*SESSION) WINDOWCHANGE ¶ func (s *Session) WindowChange(h, w int) error WindowChange informs the remote host about a terminal window dimension change to h rows and w columns. TYPE SIGNAL ¶ type Signal string const ( SIGABRT Signal = "ABRT" SIGALRM Signal = "ALRM" SIGFPE Signal = "FPE" SIGHUP Signal = "HUP" SIGILL Signal = "ILL" SIGINT Signal = "INT" SIGKILL Signal = "KILL" SIGPIPE Signal = "PIPE" SIGQUIT Signal = "QUIT" SIGSEGV Signal = "SEGV" SIGTERM Signal = "TERM" SIGUSR1 Signal = "USR1" SIGUSR2 Signal = "USR2" ) POSIX signals as listed in RFC 4254 Section 6.10. TYPE SIGNATURE ¶ type Signature struct { Format string Blob []byte Rest []byte `ssh:"rest"` } Signature represents a cryptographic signature. TYPE SIGNER ¶ 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(rand io.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. FUNC NEWCERTSIGNER ¶ func NewCertSigner(cert *Certificate, signer Signer) (Signer, error) 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. FUNC NEWSIGNERFROMKEY ¶ func NewSignerFromKey(key interface{}) (Signer, error) 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. FUNC NEWSIGNERFROMSIGNER ¶ func NewSignerFromSigner(signer crypto.Signer) (Signer, error) NewSignerFromSigner takes any crypto.Signer implementation and returns a corresponding Signer interface. This can be used, for example, with keys kept in hardware modules. FUNC PARSEPRIVATEKEY ¶ func ParsePrivateKey(pemBytes []byte) (Signer, error) ParsePrivateKey returns a Signer from a PEM encoded private key. It supports the same keys as ParseRawPrivateKey. If the private key is encrypted, it will return a PassphraseMissingError. FUNC PARSEPRIVATEKEYWITHPASSPHRASE ¶ func ParsePrivateKeyWithPassphrase(pemBytes, passphrase []byte) (Signer, error) ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private key and passphrase. It supports the same keys as ParseRawPrivateKeyWithPassphrase. TYPE TERMINALMODES ¶ type TerminalModes map[uint8]uint32 TYPE WAITMSG ¶ type Waitmsg struct { // contains filtered or unexported fields } Waitmsg stores the information about an exited remote command as reported by Wait. FUNC (WAITMSG) EXITSTATUS ¶ func (w Waitmsg) ExitStatus() int ExitStatus returns the exit status of the remote command. FUNC (WAITMSG) LANG ¶ func (w Waitmsg) Lang() string Lang returns the language tag. See RFC 3066 FUNC (WAITMSG) MSG ¶ func (w Waitmsg) Msg() string Msg returns the exit message given by the remote command FUNC (WAITMSG) SIGNAL ¶ func (w Waitmsg) Signal() string Signal returns the exit signal of the remote command if it was terminated violently. FUNC (WAITMSG) STRING ¶ func (w Waitmsg) String() string SOURCE FILES ¶ View all Source files * buffer.go * certs.go * channel.go * cipher.go * client.go * client_auth.go * common.go * connection.go * doc.go * handshake.go * kex.go * keys.go * mac.go * messages.go * mux.go * server.go * session.go * ssh_gss.go * streamlocal.go * tcpip.go * transport.go DIRECTORIES ¶ Show internal Expand all Path Synopsis agent 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. knownhosts 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. terminal 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. test 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. Click to show internal directories. Click to hide internal directories. Why Go Use Cases Case Studies Get Started Playground Tour Stack Overflow Help Packages Standard Library Sub-repositories About Go Packages About Download Blog Issue Tracker Release Notes Brand Guidelines Code of Conduct Connect Twitter GitHub Slack r/golang Meetup Golang Weekly * Copyright * Terms of Service * Privacy Policy * Report an Issue * Theme Toggle * Shortcuts Modal JUMP TO Close KEYBOARD SHORTCUTS ? : This menu / : Search site f or F : Jump to y or Y : Canonical URL Close go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. Learn more. Okay