code
stringlengths 11
335k
| docstring
stringlengths 20
11.8k
| func_name
stringlengths 1
100
| language
stringclasses 1
value | repo
stringclasses 245
values | path
stringlengths 4
144
| url
stringlengths 43
214
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
func (c *Config) SetDefaults() {
if c.Rand == nil {
c.Rand = rand.Reader
}
if c.Ciphers == nil {
c.Ciphers = preferredCiphers
}
var ciphers []string
for _, c := range c.Ciphers {
if cipherModes[c] != nil {
// reject the cipher if we have no cipherModes definition
ciphers = append(ciphers, c)
}
}
c.Ciphers = ciphers
if c.KeyExchanges == nil {
c.KeyExchanges = preferredKexAlgos
}
if c.MACs == nil {
c.MACs = supportedMACs
}
if c.RekeyThreshold == 0 {
// cipher specific default
} else if c.RekeyThreshold < minRekeyThreshold {
c.RekeyThreshold = minRekeyThreshold
} else if c.RekeyThreshold >= math.MaxInt64 {
// Avoid weirdness if somebody uses -1 as a threshold.
c.RekeyThreshold = math.MaxInt64
}
} | 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. | SetDefaults | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/common.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/common.go | BSD-3-Clause |
func buildDataSignedForAuth(sessionID []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte {
data := struct {
Session []byte
Type byte
User string
Service string
Method string
Sign bool
Algo []byte
PubKey []byte
}{
sessionID,
msgUserAuthRequest,
req.User,
req.Service,
req.Method,
true,
algo,
pubKey,
}
return Marshal(data)
} | buildDataSignedForAuth returns the data that is signed in order to prove
possession of a private key. See RFC 4252, section 7. | buildDataSignedForAuth | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/common.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/common.go | BSD-3-Clause |
func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) } | newCond is a helper to hide the fact that there is no usable zero
value for sync.Cond. | newCond | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/common.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/common.go | BSD-3-Clause |
func (w *window) add(win uint32) bool {
// a zero sized window adjust is a noop.
if win == 0 {
return true
}
w.L.Lock()
if w.win+win < win {
w.L.Unlock()
return false
}
w.win += win
// It is unusual that multiple goroutines would be attempting to reserve
// window space, but not guaranteed. Use broadcast to notify all waiters
// that additional window is available.
w.Broadcast()
w.L.Unlock()
return true
} | add adds win to the amount of window available
for consumers. | add | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/common.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/common.go | BSD-3-Clause |
func (w *window) close() {
w.L.Lock()
w.closed = true
w.Broadcast()
w.L.Unlock()
} | close sets the window to closed, so all reservations fail
immediately. | close | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/common.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/common.go | BSD-3-Clause |
func (w *window) reserve(win uint32) (uint32, error) {
var err error
w.L.Lock()
w.writeWaiters++
w.Broadcast()
for w.win == 0 && !w.closed {
w.Wait()
}
w.writeWaiters--
if w.win < win {
win = w.win
}
w.win -= win
if w.closed {
err = io.EOF
}
w.L.Unlock()
return win, err
} | reserve reserves win from the available window capacity.
If no capacity remains, reserve will block. reserve may
return less than requested. | reserve | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/common.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/common.go | BSD-3-Clause |
func (w *window) waitWriterBlocked() {
w.Cond.L.Lock()
for w.writeWaiters == 0 {
w.Cond.Wait()
}
w.Cond.L.Unlock()
} | waitWriterBlocked waits until some goroutine is blocked for further
writes. It is used in tests only. | waitWriterBlocked | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/common.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/common.go | BSD-3-Clause |
func (s *Session) SendRequest(name string, wantReply bool, payload []byte) (bool, error) {
return s.ch.SendRequest(name, wantReply, payload)
} | SendRequest sends an out-of-band channel request on the SSH channel
underlying the session. | SendRequest | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) Setenv(name, value string) error {
msg := setenvRequest{
Name: name,
Value: value,
}
ok, err := s.ch.SendRequest("env", true, Marshal(&msg))
if err == nil && !ok {
err = errors.New("ssh: setenv failed")
}
return err
} | Setenv sets an environment variable that will be applied to any
command executed by Shell or Run. | Setenv | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) RequestPty(term string, h, w int, termmodes TerminalModes) error {
var tm []byte
for k, v := range termmodes {
kv := struct {
Key byte
Val uint32
}{k, v}
tm = append(tm, Marshal(&kv)...)
}
tm = append(tm, tty_OP_END)
req := ptyRequestMsg{
Term: term,
Columns: uint32(w),
Rows: uint32(h),
Width: uint32(w * 8),
Height: uint32(h * 8),
Modelist: string(tm),
}
ok, err := s.ch.SendRequest("pty-req", true, Marshal(&req))
if err == nil && !ok {
err = errors.New("ssh: pty-req failed")
}
return err
} | RequestPty requests the association of a pty with the session on the remote host. | RequestPty | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) RequestSubsystem(subsystem string) error {
msg := subsystemRequestMsg{
Subsystem: subsystem,
}
ok, err := s.ch.SendRequest("subsystem", true, Marshal(&msg))
if err == nil && !ok {
err = errors.New("ssh: subsystem request failed")
}
return err
} | 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 | RequestSubsystem | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) WindowChange(h, w int) error {
req := ptyWindowChangeMsg{
Columns: uint32(w),
Rows: uint32(h),
Width: uint32(w * 8),
Height: uint32(h * 8),
}
_, err := s.ch.SendRequest("window-change", false, Marshal(&req))
return err
} | WindowChange informs the remote host about a terminal window dimension change to h rows and w columns. | WindowChange | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) Signal(sig Signal) error {
msg := signalMsg{
Signal: string(sig),
}
_, err := s.ch.SendRequest("signal", false, Marshal(&msg))
return err
} | Signal sends the given signal to the remote process.
sig is one of the SIG* constants. | Signal | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) Start(cmd string) error {
if s.started {
return errors.New("ssh: session already started")
}
req := execMsg{
Command: cmd,
}
ok, err := s.ch.SendRequest("exec", true, Marshal(&req))
if err == nil && !ok {
err = fmt.Errorf("ssh: command %v failed", cmd)
}
if err != nil {
return err
}
return s.start()
} | 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. | Start | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) Run(cmd string) error {
err := s.Start(cmd)
if err != nil {
return err
}
return s.Wait()
} | 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. | Run | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) Output(cmd string) ([]byte, error) {
if s.Stdout != nil {
return nil, errors.New("ssh: Stdout already set")
}
var b bytes.Buffer
s.Stdout = &b
err := s.Run(cmd)
return b.Bytes(), err
} | Output runs cmd on the remote host and returns its standard output. | Output | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) CombinedOutput(cmd string) ([]byte, error) {
if s.Stdout != nil {
return nil, errors.New("ssh: Stdout already set")
}
if s.Stderr != nil {
return nil, errors.New("ssh: Stderr already set")
}
var b singleWriter
s.Stdout = &b
s.Stderr = &b
err := s.Run(cmd)
return b.b.Bytes(), err
} | CombinedOutput runs cmd on the remote host and returns its combined
standard output and standard error. | CombinedOutput | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) Shell() error {
if s.started {
return errors.New("ssh: session already started")
}
ok, err := s.ch.SendRequest("shell", true, nil)
if err == nil && !ok {
return errors.New("ssh: could not start shell")
}
if err != nil {
return err
}
return s.start()
} | Shell starts a login shell on the remote host. A Session only
accepts one call to Run, Start, Shell, Output, or CombinedOutput. | Shell | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) Wait() error {
if !s.started {
return errors.New("ssh: session not started")
}
waitErr := <-s.exitStatus
if s.stdinPipeWriter != nil {
s.stdinPipeWriter.Close()
}
var copyError error
for range s.copyFuncs {
if err := <-s.errors; err != nil && copyError == nil {
copyError = err
}
}
if waitErr != nil {
return waitErr
}
return copyError
} | 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. | Wait | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) StdinPipe() (io.WriteCloser, error) {
if s.Stdin != nil {
return nil, errors.New("ssh: Stdin already set")
}
if s.started {
return nil, errors.New("ssh: StdinPipe after process started")
}
s.stdinpipe = true
return &sessionStdin{s.ch, s.ch}, nil
} | StdinPipe returns a pipe that will be connected to the
remote command's standard input when the command starts. | StdinPipe | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) StdoutPipe() (io.Reader, error) {
if s.Stdout != nil {
return nil, errors.New("ssh: Stdout already set")
}
if s.started {
return nil, errors.New("ssh: StdoutPipe after process started")
}
s.stdoutpipe = true
return s.ch, nil
} | 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. | StdoutPipe | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *Session) StderrPipe() (io.Reader, error) {
if s.Stderr != nil {
return nil, errors.New("ssh: Stderr already set")
}
if s.started {
return nil, errors.New("ssh: StderrPipe after process started")
}
s.stderrpipe = true
return s.ch.Stderr(), nil
} | 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. | StderrPipe | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func newSession(ch Channel, reqs <-chan *Request) (*Session, error) {
s := &Session{
ch: ch,
}
s.exitStatus = make(chan error, 1)
go func() {
s.exitStatus <- s.wait(reqs)
}()
return s, nil
} | newSession returns a new interactive session on the remote host. | newSession | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (w Waitmsg) ExitStatus() int {
return w.status
} | ExitStatus returns the exit status of the remote command. | ExitStatus | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (w Waitmsg) Signal() string {
return w.signal
} | Signal returns the exit signal of the remote command if
it was terminated violently. | Signal | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (w Waitmsg) Msg() string {
return w.msg
} | Msg returns the exit message given by the remote command | Msg | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (w Waitmsg) Lang() string {
return w.lang
} | Lang returns the language tag. See RFC 3066 | Lang | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/session.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/session.go | BSD-3-Clause |
func (s *streamPacketCipher) readCipherPacket(seqNum uint32, r io.Reader) ([]byte, error) {
if _, err := io.ReadFull(r, s.prefix[:]); err != nil {
return nil, err
}
var encryptedPaddingLength [1]byte
if s.mac != nil && s.etm {
copy(encryptedPaddingLength[:], s.prefix[4:5])
s.cipher.XORKeyStream(s.prefix[4:5], s.prefix[4:5])
} else {
s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
}
length := binary.BigEndian.Uint32(s.prefix[0:4])
paddingLength := uint32(s.prefix[4])
var macSize uint32
if s.mac != nil {
s.mac.Reset()
binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
s.mac.Write(s.seqNumBytes[:])
if s.etm {
s.mac.Write(s.prefix[:4])
s.mac.Write(encryptedPaddingLength[:])
} else {
s.mac.Write(s.prefix[:])
}
macSize = uint32(s.mac.Size())
}
if length <= paddingLength+1 {
return nil, errors.New("ssh: invalid packet length, packet too small")
}
if length > maxPacket {
return nil, errors.New("ssh: invalid packet length, packet too large")
}
// the maxPacket check above ensures that length-1+macSize
// does not overflow.
if uint32(cap(s.packetData)) < length-1+macSize {
s.packetData = make([]byte, length-1+macSize)
} else {
s.packetData = s.packetData[:length-1+macSize]
}
if _, err := io.ReadFull(r, s.packetData); err != nil {
return nil, err
}
mac := s.packetData[length-1:]
data := s.packetData[:length-1]
if s.mac != nil && s.etm {
s.mac.Write(data)
}
s.cipher.XORKeyStream(data, data)
if s.mac != nil {
if !s.etm {
s.mac.Write(data)
}
s.macResult = s.mac.Sum(s.macResult[:0])
if subtle.ConstantTimeCompare(s.macResult, mac) != 1 {
return nil, errors.New("ssh: MAC failure")
}
}
return s.packetData[:length-paddingLength-1], nil
} | readCipherPacket reads and decrypt a single packet from the reader argument. | readCipherPacket | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/cipher.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/cipher.go | BSD-3-Clause |
func (s *streamPacketCipher) writeCipherPacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
if len(packet) > maxPacket {
return errors.New("ssh: packet too large")
}
aadlen := 0
if s.mac != nil && s.etm {
// packet length is not encrypted for EtM modes
aadlen = 4
}
paddingLength := packetSizeMultiple - (prefixLen+len(packet)-aadlen)%packetSizeMultiple
if paddingLength < 4 {
paddingLength += packetSizeMultiple
}
length := len(packet) + 1 + paddingLength
binary.BigEndian.PutUint32(s.prefix[:], uint32(length))
s.prefix[4] = byte(paddingLength)
padding := s.padding[:paddingLength]
if _, err := io.ReadFull(rand, padding); err != nil {
return err
}
if s.mac != nil {
s.mac.Reset()
binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
s.mac.Write(s.seqNumBytes[:])
if s.etm {
// For EtM algorithms, the packet length must stay unencrypted,
// but the following data (padding length) must be encrypted
s.cipher.XORKeyStream(s.prefix[4:5], s.prefix[4:5])
}
s.mac.Write(s.prefix[:])
if !s.etm {
// For non-EtM algorithms, the algorithm is applied on unencrypted data
s.mac.Write(packet)
s.mac.Write(padding)
}
}
if !(s.mac != nil && s.etm) {
// For EtM algorithms, the padding length has already been encrypted
// and the packet length must remain unencrypted
s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
}
s.cipher.XORKeyStream(packet, packet)
s.cipher.XORKeyStream(padding, padding)
if s.mac != nil && s.etm {
// For EtM algorithms, packet and padding must be encrypted
s.mac.Write(packet)
s.mac.Write(padding)
}
if _, err := w.Write(s.prefix[:]); err != nil {
return err
}
if _, err := w.Write(packet); err != nil {
return err
}
if _, err := w.Write(padding); err != nil {
return err
}
if s.mac != nil {
s.macResult = s.mac.Sum(s.macResult[:0])
if _, err := w.Write(s.macResult); err != nil {
return err
}
}
return nil
} | writeCipherPacket encrypts and sends a packet of data to the writer argument | writeCipherPacket | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/cipher.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/cipher.go | BSD-3-Clause |
func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err error) {
switch algo {
case KeyAlgoRSA:
return parseRSA(in)
case KeyAlgoDSA:
return parseDSA(in)
case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
return parseECDSA(in)
case KeyAlgoED25519:
return parseED25519(in)
case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01:
cert, err := parseCert(in, certToPrivAlgo(algo))
if err != nil {
return nil, nil, err
}
return cert, nil, nil
}
return nil, nil, fmt.Errorf("ssh: unknown key algorithm: %v", algo)
} | parsePubKey parses a public key of the given algorithm.
Use ParsePublicKey for keys with prepended algorithm. | parsePubKey | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func parseAuthorizedKey(in []byte) (out PublicKey, comment string, err error) {
in = bytes.TrimSpace(in)
i := bytes.IndexAny(in, " \t")
if i == -1 {
i = len(in)
}
base64Key := in[:i]
key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key)))
n, err := base64.StdEncoding.Decode(key, base64Key)
if err != nil {
return nil, "", err
}
key = key[:n]
out, err = ParsePublicKey(key)
if err != nil {
return nil, "", err
}
comment = string(bytes.TrimSpace(in[i:]))
return out, comment, nil
} | parseAuthorizedKey parses a public key in OpenSSH authorized_keys format
(see sshd(8) manual page) once the options and key type fields have been
removed. | parseAuthorizedKey | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey, comment string, rest []byte, err error) {
for len(in) > 0 {
end := bytes.IndexByte(in, '\n')
if end != -1 {
rest = in[end+1:]
in = in[:end]
} else {
rest = nil
}
end = bytes.IndexByte(in, '\r')
if end != -1 {
in = in[:end]
}
in = bytes.TrimSpace(in)
if len(in) == 0 || in[0] == '#' {
in = rest
continue
}
i := bytes.IndexAny(in, " \t")
if i == -1 {
in = rest
continue
}
// Strip out the beginning of the known_host key.
// This is either an optional marker or a (set of) hostname(s).
keyFields := bytes.Fields(in)
if len(keyFields) < 3 || len(keyFields) > 5 {
return "", nil, nil, "", nil, errors.New("ssh: invalid entry in known_hosts data")
}
// keyFields[0] is either "@cert-authority", "@revoked" or a comma separated
// list of hosts
marker := ""
if keyFields[0][0] == '@' {
marker = string(keyFields[0][1:])
keyFields = keyFields[1:]
}
hosts := string(keyFields[0])
// keyFields[1] contains the key type (e.g. “ssh-rsa”).
// However, that information is duplicated inside the
// base64-encoded key and so is ignored here.
key := bytes.Join(keyFields[2:], []byte(" "))
if pubKey, comment, err = parseAuthorizedKey(key); err != nil {
return "", nil, nil, "", nil, err
}
return marker, strings.Split(hosts, ","), pubKey, comment, rest, nil
}
return "", nil, nil, "", nil, io.EOF
} | 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. | ParseKnownHosts | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) {
for len(in) > 0 {
end := bytes.IndexByte(in, '\n')
if end != -1 {
rest = in[end+1:]
in = in[:end]
} else {
rest = nil
}
end = bytes.IndexByte(in, '\r')
if end != -1 {
in = in[:end]
}
in = bytes.TrimSpace(in)
if len(in) == 0 || in[0] == '#' {
in = rest
continue
}
i := bytes.IndexAny(in, " \t")
if i == -1 {
in = rest
continue
}
if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
return out, comment, options, rest, nil
}
// No key type recognised. Maybe there's an options field at
// the beginning.
var b byte
inQuote := false
var candidateOptions []string
optionStart := 0
for i, b = range in {
isEnd := !inQuote && (b == ' ' || b == '\t')
if (b == ',' && !inQuote) || isEnd {
if i-optionStart > 0 {
candidateOptions = append(candidateOptions, string(in[optionStart:i]))
}
optionStart = i + 1
}
if isEnd {
break
}
if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) {
inQuote = !inQuote
}
}
for i < len(in) && (in[i] == ' ' || in[i] == '\t') {
i++
}
if i == len(in) {
// Invalid line: unmatched quote
in = rest
continue
}
in = in[i:]
i = bytes.IndexAny(in, " \t")
if i == -1 {
in = rest
continue
}
if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
options = candidateOptions
return out, comment, options, rest, nil
}
in = rest
continue
}
return nil, "", nil, nil, errors.New("ssh: no key found")
} | ParseAuthorizedKeys parses a public key from an authorized_keys
file used in OpenSSH according to the sshd(8) manual page. | ParseAuthorizedKey | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func ParsePublicKey(in []byte) (out PublicKey, err error) {
algo, in, ok := parseString(in)
if !ok {
return nil, errShortRead
}
var rest []byte
out, rest, err = parsePubKey(in, string(algo))
if len(rest) > 0 {
return nil, errors.New("ssh: trailing junk in public key")
}
return out, err
} | ParsePublicKey parses an SSH public key formatted for use in
the SSH wire protocol according to RFC 4253, section 6.6. | ParsePublicKey | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func MarshalAuthorizedKey(key PublicKey) []byte {
b := &bytes.Buffer{}
b.WriteString(key.Type())
b.WriteByte(' ')
e := base64.NewEncoder(base64.StdEncoding, b)
e.Write(key.Marshal())
e.Close()
b.WriteByte('\n')
return b.Bytes()
} | MarshalAuthorizedKey serializes key for inclusion in an OpenSSH
authorized_keys file. The return value ends with newline. | MarshalAuthorizedKey | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func parseRSA(in []byte) (out PublicKey, rest []byte, err error) {
var w struct {
E *big.Int
N *big.Int
Rest []byte `ssh:"rest"`
}
if err := Unmarshal(in, &w); err != nil {
return nil, nil, err
}
if w.E.BitLen() > 24 {
return nil, nil, errors.New("ssh: exponent too large")
}
e := w.E.Int64()
if e < 3 || e&1 == 0 {
return nil, nil, errors.New("ssh: incorrect exponent")
}
var key rsa.PublicKey
key.E = int(e)
key.N = w.N
return (*rsaPublicKey)(&key), w.Rest, nil
} | parseRSA parses an RSA key according to RFC 4253, section 6.6. | parseRSA | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func parseDSA(in []byte) (out PublicKey, rest []byte, err error) {
var w struct {
P, Q, G, Y *big.Int
Rest []byte `ssh:"rest"`
}
if err := Unmarshal(in, &w); err != nil {
return nil, nil, err
}
param := dsa.Parameters{
P: w.P,
Q: w.Q,
G: w.G,
}
if err := checkDSAParams(¶m); err != nil {
return nil, nil, err
}
key := &dsaPublicKey{
Parameters: param,
Y: w.Y,
}
return key, w.Rest, nil
} | parseDSA parses an DSA key according to RFC 4253, section 6.6. | parseDSA | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func ecHash(curve elliptic.Curve) crypto.Hash {
bitSize := curve.Params().BitSize
switch {
case bitSize <= 256:
return crypto.SHA256
case bitSize <= 384:
return crypto.SHA384
}
return crypto.SHA512
} | ecHash returns the hash to match the given elliptic curve, see RFC
5656, section 6.2.1 | ecHash | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
var w struct {
Curve string
KeyBytes []byte
Rest []byte `ssh:"rest"`
}
if err := Unmarshal(in, &w); err != nil {
return nil, nil, err
}
key := new(ecdsa.PublicKey)
switch w.Curve {
case "nistp256":
key.Curve = elliptic.P256()
case "nistp384":
key.Curve = elliptic.P384()
case "nistp521":
key.Curve = elliptic.P521()
default:
return nil, nil, errors.New("ssh: unsupported curve")
}
key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
if key.X == nil || key.Y == nil {
return nil, nil, errors.New("ssh: invalid curve point")
}
return (*ecdsaPublicKey)(key), w.Rest, nil
} | parseECDSA parses an ECDSA key according to RFC 5656, section 3.1. | parseECDSA | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func NewSignerFromKey(key interface{}) (Signer, error) {
switch key := key.(type) {
case crypto.Signer:
return NewSignerFromSigner(key)
case *dsa.PrivateKey:
return newDSAPrivateKey(key)
default:
return nil, fmt.Errorf("ssh: unsupported key type %T", key)
} | 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. | NewSignerFromKey | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func NewSignerFromSigner(signer crypto.Signer) (Signer, error) {
pubKey, err := NewPublicKey(signer.Public())
if err != nil {
return nil, err
}
return &wrappedSigner{signer, pubKey}, nil
} | NewSignerFromSigner takes any crypto.Signer implementation and
returns a corresponding Signer interface. This can be used, for
example, with keys kept in hardware modules. | NewSignerFromSigner | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/keys.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/keys.go | BSD-3-Clause |
func marshalTuples(tups map[string]string) []byte {
keys := make([]string, 0, len(tups))
for key := range tups {
keys = append(keys, key)
}
sort.Strings(keys)
var ret []byte
for _, key := range keys {
s := optionsTuple{Key: key}
if value := tups[key]; len(value) > 0 {
s.Value = Marshal(&optionsTupleValue{value})
}
ret = append(ret, Marshal(&s)...)
}
return ret
} | serialize a map of critical options or extensions
issue #10569 - per [PROTOCOL.certkeys] and SSH implementation,
we need two length prefixes for a non-empty string value | marshalTuples | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/certs.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/certs.go | BSD-3-Clause |
func parseTuples(in []byte) (map[string]string, error) {
tups := map[string]string{}
var lastKey string
var haveLastKey bool
for len(in) > 0 {
var key, val, extra []byte
var ok bool
if key, in, ok = parseString(in); !ok {
return nil, errShortRead
}
keyStr := string(key)
// according to [PROTOCOL.certkeys], the names must be in
// lexical order.
if haveLastKey && keyStr <= lastKey {
return nil, fmt.Errorf("ssh: certificate options are not in lexical order")
}
lastKey, haveLastKey = keyStr, true
// the next field is a data field, which if non-empty has a string embedded
if val, in, ok = parseString(in); !ok {
return nil, errShortRead
}
if len(val) > 0 {
val, extra, ok = parseString(val)
if !ok {
return nil, errShortRead
}
if len(extra) > 0 {
return nil, fmt.Errorf("ssh: unexpected trailing data after certificate option value")
}
tups[keyStr] = string(val)
} else {
tups[keyStr] = ""
}
}
return tups, nil
} | issue #10569 - per [PROTOCOL.certkeys] and SSH implementation,
we need two length prefixes for a non-empty option value | parseTuples | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/certs.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/certs.go | BSD-3-Clause |
func NewCertSigner(cert *Certificate, signer Signer) (Signer, error) {
if bytes.Compare(cert.Key.Marshal(), signer.PublicKey().Marshal()) != 0 {
return nil, errors.New("ssh: signer and cert have different public key")
}
if algorithmSigner, ok := signer.(AlgorithmSigner); ok {
return &algorithmOpenSSHCertSigner{
&openSSHCertSigner{cert, signer}, algorithmSigner}, nil
} else {
return &openSSHCertSigner{cert, signer}, nil
}
} | 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. | NewCertSigner | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/certs.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/certs.go | BSD-3-Clause |
func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey) error {
cert, ok := key.(*Certificate)
if !ok {
if c.HostKeyFallback != nil {
return c.HostKeyFallback(addr, remote, key)
}
return errors.New("ssh: non-certificate host key")
}
if cert.CertType != HostCert {
return fmt.Errorf("ssh: certificate presented as a host key has type %d", cert.CertType)
}
if !c.IsHostAuthority(cert.SignatureKey, addr) {
return fmt.Errorf("ssh: no authorities for hostname: %v", addr)
}
hostname, _, err := net.SplitHostPort(addr)
if err != nil {
return err
}
// Pass hostname only as principal for host certificates (consistent with OpenSSH)
return c.CheckCert(hostname, cert)
} | CheckHostKey checks a host key certificate. This method can be
plugged into ClientConfig.HostKeyCallback. | CheckHostKey | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/certs.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/certs.go | BSD-3-Clause |
func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permissions, error) {
cert, ok := pubKey.(*Certificate)
if !ok {
if c.UserKeyFallback != nil {
return c.UserKeyFallback(conn, pubKey)
}
return nil, errors.New("ssh: normal key pairs not accepted")
}
if cert.CertType != UserCert {
return nil, fmt.Errorf("ssh: cert has type %d", cert.CertType)
}
if !c.IsUserAuthority(cert.SignatureKey) {
return nil, fmt.Errorf("ssh: certificate signed by unrecognized authority")
}
if err := c.CheckCert(conn.User(), cert); err != nil {
return nil, err
}
return &cert.Permissions, nil
} | Authenticate checks a user certificate. Authenticate can be used as
a value for ServerConfig.PublicKeyCallback. | Authenticate | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/certs.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/certs.go | BSD-3-Clause |
func (c *CertChecker) CheckCert(principal string, cert *Certificate) error {
if c.IsRevoked != nil && c.IsRevoked(cert) {
return fmt.Errorf("ssh: certificate serial %d revoked", cert.Serial)
}
for opt := range cert.CriticalOptions {
// sourceAddressCriticalOption will be enforced by
// serverAuthenticate
if opt == sourceAddressCriticalOption {
continue
}
found := false
for _, supp := range c.SupportedCriticalOptions {
if supp == opt {
found = true
break
}
}
if !found {
return fmt.Errorf("ssh: unsupported critical option %q in certificate", opt)
}
}
if len(cert.ValidPrincipals) > 0 {
// By default, certs are valid for all users/hosts.
found := false
for _, p := range cert.ValidPrincipals {
if p == principal {
found = true
break
}
}
if !found {
return fmt.Errorf("ssh: principal %q not in the set of valid principals for given certificate: %q", principal, cert.ValidPrincipals)
}
}
clock := c.Clock
if clock == nil {
clock = time.Now
}
unixNow := clock().Unix()
if after := int64(cert.ValidAfter); after < 0 || unixNow < int64(cert.ValidAfter) {
return fmt.Errorf("ssh: cert is not yet valid")
}
if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(CertTimeInfinity) && (unixNow >= before || before < 0) {
return fmt.Errorf("ssh: cert has expired")
}
if err := cert.SignatureKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil {
return fmt.Errorf("ssh: certificate signature does not verify")
}
return nil
} | CheckCert checks CriticalOptions, ValidPrincipals, revocation, timestamp and
the signature of the certificate. | CheckCert | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/certs.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/certs.go | BSD-3-Clause |
func (c *Certificate) SignCert(rand io.Reader, authority Signer) error {
c.Nonce = make([]byte, 32)
if _, err := io.ReadFull(rand, c.Nonce); err != nil {
return err
}
c.SignatureKey = authority.PublicKey()
sig, err := authority.Sign(rand, c.bytesForSigning())
if err != nil {
return err
}
c.Signature = sig
return nil
} | SignCert sets c.SignatureKey to the authority's public key and stores a
Signature, by authority, in the certificate. | SignCert | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/certs.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/certs.go | BSD-3-Clause |
func certToPrivAlgo(algo string) string {
for privAlgo, pubAlgo := range certAlgoNames {
if pubAlgo == algo {
return privAlgo
}
}
panic("unknown cert algorithm")
} | certToPrivAlgo returns the underlying algorithm for a certificate algorithm.
Panics if a non-certificate algorithm is passed. | certToPrivAlgo | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/certs.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/certs.go | BSD-3-Clause |
func (c *Certificate) Marshal() []byte {
generic := genericCertData{
Serial: c.Serial,
CertType: c.CertType,
KeyId: c.KeyId,
ValidPrincipals: marshalStringList(c.ValidPrincipals),
ValidAfter: uint64(c.ValidAfter),
ValidBefore: uint64(c.ValidBefore),
CriticalOptions: marshalTuples(c.CriticalOptions),
Extensions: marshalTuples(c.Extensions),
Reserved: c.Reserved,
SignatureKey: c.SignatureKey.Marshal(),
}
if c.Signature != nil {
generic.Signature = Marshal(c.Signature)
}
genericBytes := Marshal(&generic)
keyBytes := c.Key.Marshal()
_, keyBytes, _ = parseString(keyBytes)
prefix := Marshal(&struct {
Name string
Nonce []byte
Key []byte `ssh:"rest"`
}{c.Type(), c.Nonce, keyBytes})
result := make([]byte, 0, len(prefix)+len(genericBytes))
result = append(result, prefix...)
result = append(result, genericBytes...)
return result
} | Marshal serializes c into OpenSSH's wire format. It is part of the
PublicKey interface. | Marshal | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/certs.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/certs.go | BSD-3-Clause |
func (c *Certificate) Type() string {
algo, ok := certAlgoNames[c.Key.Type()]
if !ok {
panic("unknown cert key type " + c.Key.Type())
}
return algo
} | Type returns the key name. It is part of the PublicKey interface. | Type | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/certs.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/certs.go | BSD-3-Clause |
func (c *Certificate) Verify(data []byte, sig *Signature) error {
return c.Key.Verify(data, sig)
} | Verify verifies a signature against the certificate's public
key. It is part of the PublicKey interface. | Verify | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/certs.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/certs.go | BSD-3-Clause |
func newBuffer() *buffer {
e := new(element)
b := &buffer{
Cond: newCond(),
head: e,
tail: e,
}
return b
} | newBuffer returns an empty buffer that is not closed. | newBuffer | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/buffer.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/buffer.go | BSD-3-Clause |
func (b *buffer) write(buf []byte) {
b.Cond.L.Lock()
e := &element{buf: buf}
b.tail.next = e
b.tail = e
b.Cond.Signal()
b.Cond.L.Unlock()
} | write makes buf available for Read to receive.
buf must not be modified after the call to write. | write | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/buffer.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/buffer.go | BSD-3-Clause |
func (b *buffer) eof() {
b.Cond.L.Lock()
b.closed = true
b.Cond.Signal()
b.Cond.L.Unlock()
} | eof closes the buffer. Reads from the buffer once all
the data has been consumed will receive io.EOF. | eof | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/buffer.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/buffer.go | BSD-3-Clause |
func (b *buffer) Read(buf []byte) (n int, err error) {
b.Cond.L.Lock()
defer b.Cond.L.Unlock()
for len(buf) > 0 {
// if there is data in b.head, copy it
if len(b.head.buf) > 0 {
r := copy(buf, b.head.buf)
buf, b.head.buf = buf[r:], b.head.buf[r:]
n += r
continue
}
// if there is a next buffer, make it the head
if len(b.head.buf) == 0 && b.head != b.tail {
b.head = b.head.next
continue
}
// if at least one byte has been copied, return
if n > 0 {
break
}
// if nothing was read, and there is nothing outstanding
// check to see if the buffer is closed.
if b.closed {
err = io.EOF
break
}
// out of buffers, wait for producer
b.Cond.Wait()
}
return
} | Read reads data from the internal buffer in buf. Reads will block
if no data is available, or until the buffer is closed. | Read | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/buffer.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/buffer.go | BSD-3-Clause |
func (c *Client) Listen(n, addr string) (net.Listener, error) {
switch n {
case "tcp", "tcp4", "tcp6":
laddr, err := net.ResolveTCPAddr(n, addr)
if err != nil {
return nil, err
}
return c.ListenTCP(laddr)
case "unix":
return c.ListenUnix(addr)
default:
return nil, fmt.Errorf("ssh: unsupported protocol: %s", n)
}
} | 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". | Listen | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func isBrokenOpenSSHVersion(versionStr string) bool {
i := strings.Index(versionStr, openSSHPrefix)
if i < 0 {
return false
}
i += len(openSSHPrefix)
j := i
for ; j < len(versionStr); j++ {
if versionStr[j] < '0' || versionStr[j] > '9' {
break
}
}
version, _ := strconv.Atoi(versionStr[i:j])
return version < 6
} | isBrokenOpenSSHVersion returns true if the given version string
specifies a version of OpenSSH that is known to have a bug in port
forwarding. | isBrokenOpenSSHVersion | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (c *Client) autoPortListenWorkaround(laddr *net.TCPAddr) (net.Listener, error) {
var sshListener net.Listener
var err error
const tries = 10
for i := 0; i < tries; i++ {
addr := *laddr
addr.Port = 1024 + portRandomizer.Intn(60000)
sshListener, err = c.ListenTCP(&addr)
if err == nil {
laddr.Port = addr.Port
return sshListener, err
}
}
return nil, fmt.Errorf("ssh: listen on random port failed after %d tries: %v", tries, err)
} | autoPortListenWorkaround simulates automatic port allocation by
trying random ports repeatedly. | autoPortListenWorkaround | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (c *Client) handleForwards() {
go c.forwards.handleChannels(c.HandleChannelOpen("forwarded-tcpip"))
go c.forwards.handleChannels(c.HandleChannelOpen("[email protected]"))
} | handleForwards starts goroutines handling forwarded connections.
It's called on first use by (*Client).ListenTCP to not launch
goroutines until needed. | handleForwards | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) {
c.handleForwardsOnce.Do(c.handleForwards)
if laddr.Port == 0 && isBrokenOpenSSHVersion(string(c.ServerVersion())) {
return c.autoPortListenWorkaround(laddr)
}
m := channelForwardMsg{
laddr.IP.String(),
uint32(laddr.Port),
}
// send message
ok, resp, err := c.SendRequest("tcpip-forward", true, Marshal(&m))
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("ssh: tcpip-forward request denied by peer")
}
// If the original port was 0, then the remote side will
// supply a real port number in the response.
if laddr.Port == 0 {
var p struct {
Port uint32
}
if err := Unmarshal(resp, &p); err != nil {
return nil, err
}
laddr.Port = int(p.Port)
}
// Register this forward, using the port number we obtained.
ch := c.forwards.add(laddr)
return &tcpListener{laddr, c, ch}, nil
} | ListenTCP requests the remote peer open a listening socket
on laddr. Incoming connections will be available by calling
Accept on the returned net.Listener. | ListenTCP | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func parseTCPAddr(addr string, port uint32) (*net.TCPAddr, error) {
if port == 0 || port > 65535 {
return nil, fmt.Errorf("ssh: port number out of range: %d", port)
}
ip := net.ParseIP(string(addr))
if ip == nil {
return nil, fmt.Errorf("ssh: cannot parse IP address %q", addr)
}
return &net.TCPAddr{IP: ip, Port: int(port)}, nil
} | parseTCPAddr parses the originating address from the remote into a *net.TCPAddr. | parseTCPAddr | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (l *forwardList) remove(addr net.Addr) {
l.Lock()
defer l.Unlock()
for i, f := range l.entries {
if addr.Network() == f.laddr.Network() && addr.String() == f.laddr.String() {
l.entries = append(l.entries[:i], l.entries[i+1:]...)
close(f.c)
return
}
}
} | remove removes the forward entry, and the channel feeding its
listener. | remove | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (l *forwardList) closeAll() {
l.Lock()
defer l.Unlock()
for _, f := range l.entries {
close(f.c)
}
l.entries = nil
} | closeAll closes and clears all forwards. | closeAll | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (l *tcpListener) Accept() (net.Conn, error) {
s, ok := <-l.in
if !ok {
return nil, io.EOF
}
ch, incoming, err := s.newCh.Accept()
if err != nil {
return nil, err
}
go DiscardRequests(incoming)
return &chanConn{
Channel: ch,
laddr: l.laddr,
raddr: s.raddr,
}, nil
} | Accept waits for and returns the next connection to the listener. | Accept | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (l *tcpListener) Close() error {
m := channelForwardMsg{
l.laddr.IP.String(),
uint32(l.laddr.Port),
}
// this also closes the listener.
l.conn.forwards.remove(l.laddr)
ok, _, err := l.conn.SendRequest("cancel-tcpip-forward", true, Marshal(&m))
if err == nil && !ok {
err = errors.New("ssh: cancel-tcpip-forward failed")
}
return err
} | Close closes the listener. | Close | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (l *tcpListener) Addr() net.Addr {
return l.laddr
} | Addr returns the listener's network address. | Addr | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (c *Client) Dial(n, addr string) (net.Conn, error) {
var ch Channel
switch n {
case "tcp", "tcp4", "tcp6":
// Parse the address into host and numeric port.
host, portString, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
port, err := strconv.ParseUint(portString, 10, 16)
if err != nil {
return nil, err
}
ch, err = c.dial(net.IPv4zero.String(), 0, host, int(port))
if err != nil {
return nil, err
}
// Use a zero address for local and remote address.
zeroAddr := &net.TCPAddr{
IP: net.IPv4zero,
Port: 0,
}
return &chanConn{
Channel: ch,
laddr: zeroAddr,
raddr: zeroAddr,
}, nil
case "unix":
var err error
ch, err = c.dialStreamLocal(addr)
if err != nil {
return nil, err
}
return &chanConn{
Channel: ch,
laddr: &net.UnixAddr{
Name: "@",
Net: "unix",
},
raddr: &net.UnixAddr{
Name: addr,
Net: "unix",
},
}, nil
default:
return nil, fmt.Errorf("ssh: unsupported protocol: %s", n)
}
} | Dial initiates a connection to the addr from the remote host.
The resulting connection has a zero LocalAddr() and RemoteAddr(). | Dial | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (c *Client) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) {
if laddr == nil {
laddr = &net.TCPAddr{
IP: net.IPv4zero,
Port: 0,
}
}
ch, err := c.dial(laddr.IP.String(), laddr.Port, raddr.IP.String(), raddr.Port)
if err != nil {
return nil, err
}
return &chanConn{
Channel: ch,
laddr: laddr,
raddr: raddr,
}, nil
} | 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. | DialTCP | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (t *chanConn) LocalAddr() net.Addr {
return t.laddr
} | LocalAddr returns the local network address. | LocalAddr | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (t *chanConn) RemoteAddr() net.Addr {
return t.raddr
} | RemoteAddr returns the remote network address. | RemoteAddr | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (t *chanConn) SetDeadline(deadline time.Time) error {
if err := t.SetReadDeadline(deadline); err != nil {
return err
}
return t.SetWriteDeadline(deadline)
} | SetDeadline sets the read and write deadlines associated
with the connection. | SetDeadline | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (t *chanConn) SetReadDeadline(deadline time.Time) error {
// for compatibility with previous version,
// the error message contains "tcpChan"
return errors.New("ssh: tcpChan: deadline not supported")
} | SetReadDeadline sets the read deadline.
A zero value for t means Read will not time out.
After the deadline, the error from Read will implement net.Error
with Timeout() == true. | SetReadDeadline | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (t *chanConn) SetWriteDeadline(deadline time.Time) error {
return errors.New("ssh: tcpChan: deadline not supported")
} | SetWriteDeadline exists to satisfy the net.Conn interface
but is not implemented by this type. It always returns an error. | SetWriteDeadline | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/tcpip.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/tcpip.go | BSD-3-Clause |
func (c *Client) ListenUnix(socketPath string) (net.Listener, error) {
c.handleForwardsOnce.Do(c.handleForwards)
m := streamLocalChannelForwardMsg{
socketPath,
}
// send message
ok, _, err := c.SendRequest("[email protected]", true, Marshal(&m))
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("ssh: [email protected] request denied by peer")
}
ch := c.forwards.add(&net.UnixAddr{Name: socketPath, Net: "unix"})
return &unixListener{socketPath, c, ch}, nil
} | ListenUnix is similar to ListenTCP but uses a Unix domain socket. | ListenUnix | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/streamlocal.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/streamlocal.go | BSD-3-Clause |
func (l *unixListener) Accept() (net.Conn, error) {
s, ok := <-l.in
if !ok {
return nil, io.EOF
}
ch, incoming, err := s.newCh.Accept()
if err != nil {
return nil, err
}
go DiscardRequests(incoming)
return &chanConn{
Channel: ch,
laddr: &net.UnixAddr{
Name: l.socketPath,
Net: "unix",
},
raddr: &net.UnixAddr{
Name: "@",
Net: "unix",
},
}, nil
} | Accept waits for and returns the next connection to the listener. | Accept | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/streamlocal.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/streamlocal.go | BSD-3-Clause |
func (l *unixListener) Close() error {
// this also closes the listener.
l.conn.forwards.remove(&net.UnixAddr{Name: l.socketPath, Net: "unix"})
m := streamLocalChannelForwardMsg{
l.socketPath,
}
ok, _, err := l.conn.SendRequest("[email protected]", true, Marshal(&m))
if err == nil && !ok {
err = errors.New("ssh: [email protected] failed")
}
return err
} | Close closes the listener. | Close | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/streamlocal.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/streamlocal.go | BSD-3-Clause |
func (l *unixListener) Addr() net.Addr {
return &net.UnixAddr{
Name: l.socketPath,
Net: "unix",
}
} | Addr returns the listener's network address. | Addr | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/streamlocal.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/streamlocal.go | BSD-3-Clause |
func (c *connection) clientAuthenticate(config *ClientConfig) error {
// initiate user auth session
if err := c.transport.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})); err != nil {
return err
}
packet, err := c.transport.readPacket()
if err != nil {
return err
}
var serviceAccept serviceAcceptMsg
if err := Unmarshal(packet, &serviceAccept); err != nil {
return err
}
// during the authentication phase the client first attempts the "none" method
// then any untried methods suggested by the server.
tried := make(map[string]bool)
var lastMethods []string
sessionID := c.transport.getSessionID()
for auth := AuthMethod(new(noneAuth)); auth != nil; {
ok, methods, err := auth.auth(sessionID, config.User, c.transport, config.Rand)
if err != nil {
return err
}
if ok == authSuccess {
// success
return nil
} else if ok == authFailure {
tried[auth.method()] = true
}
if methods == nil {
methods = lastMethods
}
lastMethods = methods
auth = nil
findNext:
for _, a := range config.Auth {
candidateMethod := a.method()
if tried[candidateMethod] {
continue
}
for _, meth := range methods {
if meth == candidateMethod {
auth = a
break findNext
}
}
}
}
return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", keys(tried))
} | clientAuthenticate authenticates with the remote server. See RFC 4252. | clientAuthenticate | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/client_auth.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/client_auth.go | BSD-3-Clause |
func Password(secret string) AuthMethod {
return passwordCallback(func() (string, error) { return secret, nil })
} | Password returns an AuthMethod using the given password. | Password | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/client_auth.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/client_auth.go | BSD-3-Clause |
func PasswordCallback(prompt func() (secret string, err error)) AuthMethod {
return passwordCallback(prompt)
} | PasswordCallback returns an AuthMethod that uses a callback for
fetching a password. | PasswordCallback | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/client_auth.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/client_auth.go | BSD-3-Clause |
func validateKey(key PublicKey, user string, c packetConn) (bool, error) {
pubKey := key.Marshal()
msg := publickeyAuthMsg{
User: user,
Service: serviceSSH,
Method: "publickey",
HasSig: false,
Algoname: key.Type(),
PubKey: pubKey,
}
if err := c.writePacket(Marshal(&msg)); err != nil {
return false, err
}
return confirmKeyAck(key, c)
} | validateKey validates the key provided is acceptable to the server. | validateKey | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/client_auth.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/client_auth.go | BSD-3-Clause |
func PublicKeys(signers ...Signer) AuthMethod {
return publicKeyCallback(func() ([]Signer, error) { return signers, nil })
} | PublicKeys returns an AuthMethod that uses the given key
pairs. | PublicKeys | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/client_auth.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/client_auth.go | BSD-3-Clause |
func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod {
return publicKeyCallback(getSigners)
} | PublicKeysCallback returns an AuthMethod that runs the given
function to obtain a list of key pairs. | PublicKeysCallback | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/client_auth.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/client_auth.go | BSD-3-Clause |
func handleAuthResponse(c packetConn) (authResult, []string, error) {
for {
packet, err := c.readPacket()
if err != nil {
return authFailure, nil, err
}
switch packet[0] {
case msgUserAuthBanner:
if err := handleBannerResponse(c, packet); err != nil {
return authFailure, nil, err
}
case msgUserAuthFailure:
var msg userAuthFailureMsg
if err := Unmarshal(packet, &msg); err != nil {
return authFailure, nil, err
}
if msg.PartialSuccess {
return authPartialSuccess, msg.Methods, nil
}
return authFailure, msg.Methods, nil
case msgUserAuthSuccess:
return authSuccess, nil, nil
default:
return authFailure, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0])
}
}
} | handleAuthResponse returns whether the preceding authentication request succeeded
along with a list of remaining authentication methods to try next and
an error if an unexpected response was received. | handleAuthResponse | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/client_auth.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/client_auth.go | BSD-3-Clause |
func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod {
return challenge
} | KeyboardInteractive returns an AuthMethod using a prompt/response
sequence controlled by the server. | KeyboardInteractive | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/client_auth.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/client_auth.go | BSD-3-Clause |
func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod {
return &retryableAuthMethod{authMethod: auth, maxTries: maxTries}
} | 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). | RetryableAuthMethod | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/client_auth.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/client_auth.go | BSD-3-Clause |
func GSSAPIWithMICAuthMethod(gssAPIClient GSSAPIClient, target string) AuthMethod {
if gssAPIClient == nil {
panic("gss-api client must be not nil with enable gssapi-with-mic")
}
return &gssAPIWithMICCallback{gssAPIClient: gssAPIClient, target: target}
} | 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. | GSSAPIWithMICAuthMethod | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/client_auth.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/client_auth.go | BSD-3-Clause |
func (c *chanList) add(ch *channel) uint32 {
c.Lock()
defer c.Unlock()
for i := range c.chans {
if c.chans[i] == nil {
c.chans[i] = ch
return uint32(i) + c.offset
}
}
c.chans = append(c.chans, ch)
return uint32(len(c.chans)-1) + c.offset
} | Assigns a channel ID to the given channel. | add | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/mux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/mux.go | BSD-3-Clause |
func (c *chanList) getChan(id uint32) *channel {
id -= c.offset
c.Lock()
defer c.Unlock()
if id < uint32(len(c.chans)) {
return c.chans[id]
}
return nil
} | getChan returns the channel for the given ID. | getChan | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/mux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/mux.go | BSD-3-Clause |
func (c *chanList) dropAll() []*channel {
c.Lock()
defer c.Unlock()
var r []*channel
for _, ch := range c.chans {
if ch == nil {
continue
}
r = append(r, ch)
}
c.chans = nil
return r
} | dropAll forgets all channels it knows, returning them in a slice. | dropAll | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/mux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/mux.go | BSD-3-Clause |
func newMux(p packetConn) *mux {
m := &mux{
conn: p,
incomingChannels: make(chan NewChannel, chanSize),
globalResponses: make(chan interface{}, 1),
incomingRequests: make(chan *Request, chanSize),
errCond: newCond(),
}
if debugMux {
m.chanList.offset = atomic.AddUint32(&globalOff, 1)
}
go m.loop()
return m
} | newMux returns a mux that runs over the given connection. | newMux | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/mux.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/mux.go | BSD-3-Clause |
func DiscardRequests(in <-chan *Request) {
for req := range in {
if req.WantReply {
req.Reply(false, nil)
}
}
} | DiscardRequests consumes and rejects all requests from the
passed-in channel. | DiscardRequests | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/connection.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/connection.go | BSD-3-Clause |
func (r *Request) Reply(ok bool, payload []byte) error {
if !r.WantReply {
return nil
}
if r.ch == nil {
return r.mux.ackRequest(ok, payload)
}
return r.ch.ackRequest(ok)
} | 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. | Reply | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/channel.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/channel.go | BSD-3-Clause |
func (r RejectionReason) String() string {
switch r {
case Prohibited:
return "administratively prohibited"
case ConnectionFailed:
return "connect failed"
case UnknownChannelType:
return "unknown channel type"
case ResourceShortage:
return "resource shortage"
}
return fmt.Sprintf("unknown reason %d", int(r))
} | String converts the rejection reason to human readable form. | String | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/channel.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/channel.go | BSD-3-Clause |
func (ch *channel) writePacket(packet []byte) error {
ch.writeMu.Lock()
if ch.sentClose {
ch.writeMu.Unlock()
return io.EOF
}
ch.sentClose = (packet[0] == msgChannelClose)
err := ch.mux.conn.writePacket(packet)
ch.writeMu.Unlock()
return err
} | writePacket sends a packet. If the packet is a channel close, it updates
sentClose. This method takes the lock c.writeMu. | writePacket | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/channel.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/channel.go | BSD-3-Clause |
func (ch *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err error) {
if ch.sentEOF {
return 0, io.EOF
}
// 1 byte message type, 4 bytes remoteId, 4 bytes data length
opCode := byte(msgChannelData)
headerLength := uint32(9)
if extendedCode > 0 {
headerLength += 4
opCode = msgChannelExtendedData
}
ch.writeMu.Lock()
packet := ch.packetPool[extendedCode]
// We don't remove the buffer from packetPool, so
// WriteExtended calls from different goroutines will be
// flagged as errors by the race detector.
ch.writeMu.Unlock()
for len(data) > 0 {
space := min(ch.maxRemotePayload, len(data))
if space, err = ch.remoteWin.reserve(space); err != nil {
return n, err
}
if want := headerLength + space; uint32(cap(packet)) < want {
packet = make([]byte, want)
} else {
packet = packet[:want]
}
todo := data[:space]
packet[0] = opCode
binary.BigEndian.PutUint32(packet[1:], ch.remoteId)
if extendedCode > 0 {
binary.BigEndian.PutUint32(packet[5:], uint32(extendedCode))
}
binary.BigEndian.PutUint32(packet[headerLength-4:], uint32(len(todo)))
copy(packet[headerLength:], todo)
if err = ch.writePacket(packet); err != nil {
return n, err
}
n += len(todo)
data = data[len(todo):]
}
ch.writeMu.Lock()
ch.packetPool[extendedCode] = packet
ch.writeMu.Unlock()
return n, err
} | WriteExtended writes data to a specific extended stream. These streams are
used, for example, for stderr. | WriteExtended | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/channel.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/channel.go | BSD-3-Clause |
func (ch *channel) responseMessageReceived() error {
if ch.direction == channelInbound {
return errors.New("ssh: channel response message received on inbound channel")
}
if ch.decided {
return errors.New("ssh: duplicate response received for channel")
}
ch.decided = true
return nil
} | responseMessageReceived is called when a success or failure message is
received on a channel to check that such a message is reasonable for the
given channel. | responseMessageReceived | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/channel.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/channel.go | BSD-3-Clause |
func (t *handshakeTransport) waitSession() error {
p, err := t.readPacket()
if err != nil {
return err
}
if p[0] != msgNewKeys {
return fmt.Errorf("ssh: first packet should be msgNewKeys")
}
return nil
} | waitSession waits for the session to be established. This should be
the first thing to call after instantiating handshakeTransport. | waitSession | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/handshake.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/handshake.go | BSD-3-Clause |
func (t *handshakeTransport) sendKexInit() error {
t.mu.Lock()
defer t.mu.Unlock()
if t.sentInitMsg != nil {
// kexInits may be sent either in response to the other side,
// or because our side wants to initiate a key change, so we
// may have already sent a kexInit. In that case, don't send a
// second kexInit.
return nil
}
msg := &kexInitMsg{
KexAlgos: t.config.KeyExchanges,
CiphersClientServer: t.config.Ciphers,
CiphersServerClient: t.config.Ciphers,
MACsClientServer: t.config.MACs,
MACsServerClient: t.config.MACs,
CompressionClientServer: supportedCompressions,
CompressionServerClient: supportedCompressions,
}
io.ReadFull(rand.Reader, msg.Cookie[:])
if len(t.hostKeys) > 0 {
for _, k := range t.hostKeys {
msg.ServerHostKeyAlgos = append(
msg.ServerHostKeyAlgos, k.PublicKey().Type())
}
} else {
msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
}
packet := Marshal(msg)
// writePacket destroys the contents, so save a copy.
packetCopy := make([]byte, len(packet))
copy(packetCopy, packet)
if err := t.pushPacket(packetCopy); err != nil {
return err
}
t.sentInitMsg = msg
t.sentInitPacket = packet
return nil
} | sendKexInit sends a key change message. | sendKexInit | go | flynn/flynn | vendor/golang.org/x/crypto/ssh/handshake.go | https://github.com/flynn/flynn/blob/master/vendor/golang.org/x/crypto/ssh/handshake.go | BSD-3-Clause |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.