// socks5NegotiateAuth negotiates the authentication method and returns the
// selected method as a byte.  On negotiation failures an error is returned.
555201
func socks5NegotiateAuth(rw *bufio.ReadWriter) (method byte, err error) {
	// Validate the version.
	if err = socksReadByteVerify(rw.Reader, "version", socks5Version); err != nil {
		err = newTemporaryNetError("socks5NegotiateAuth: %s", err.Error())
		return
	}

	// Read the number of methods.
	var nmethods byte
	if nmethods, err = socksReadByte(rw.Reader); err != nil {
		err = newTemporaryNetError("socks5NegotiateAuth: Failed to read nmethods byte: %s", err.Error())
		return
	}

	// Read the methods.
	var methods []byte
	if methods, err = socksReadBytes(rw.Reader, int(nmethods)); err != nil {
		err = newTemporaryNetError("socks5NegotiateAuth: Failed to read methods bytes: %s", err.Error())
		return
	}

	// Pick the most "suitable" method.
	method = socksAuthNoAcceptableMethods
	for _, m := range methods {
		switch m {
		case socksAuthNoneRequired:
			// Pick Username/Password over None if the client happens to
			// send both.
			if method == socksAuthNoAcceptableMethods {
				method = m
			}

		case socksAuthUsernamePassword:
			method = m
		}
	}

	// Send the negotiated method.
	var msg [2]byte
	msg[0] = socks5Version
	msg[1] = method
	if _, err = rw.Writer.Write(msg[:]); err != nil {
		err = newTemporaryNetError("socks5NegotiateAuth: Failed to write negotiated method: %s", err.Error())
		return
	}

	if err = socksFlushBuffers(rw); err != nil {
		err = newTemporaryNetError("socks5NegotiateAuth: Failed to flush buffers: %s", err.Error())
		return
	}
	return
}
708461
func (s *AcceptHandshakeOutput) SetHandshake(v *Handshake) *AcceptHandshakeOutput {
	s.Handshake = v
	return s
}
1306908
func SOCKS4Handler(opts ...HandlerOption) Handler {
	h := &socks4Handler{}
	h.Init(opts...)

	return h
}
728958
func (a *Verifier) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {
	if req.TLS == nil || len(req.TLS.PeerCertificates) == 0 {
		return nil, false, nil
	}

	// Use intermediates, if provided
	optsCopy := a.opts
	if optsCopy.Intermediates == nil && len(req.TLS.PeerCertificates) > 1 {
		optsCopy.Intermediates = x509.NewCertPool()
		for _, intermediate := range req.TLS.PeerCertificates[1:] {
			optsCopy.Intermediates.AddCert(intermediate)
		}
	}

	if _, err := req.TLS.PeerCertificates[0].Verify(optsCopy); err != nil {
		return nil, false, err
	}
	if err := a.verifySubject(req.TLS.PeerCertificates[0].Subject); err != nil {
		return nil, false, err
	}
	return a.auth.AuthenticateRequest(req)
}
396655
func (s *DeclineHandshakeOutput) SetHandshake(v *Handshake) *DeclineHandshakeOutput {
	s.Handshake = v
	return s
}
427767
func (h *basicPasswordAuthHandler) AuthenticationChallenge(req *http.Request) (http.Header, error) {
	headers := http.Header{}

	if len(req.Header.Get(CSRFTokenHeader)) == 0 {
		headers.Add("Warning",
			fmt.Sprintf(
				`%s %s "A non-empty %s header is required to receive basic-auth challenges"`,
				oauthhandlers.WarningHeaderMiscCode,
				oauthhandlers.WarningHeaderOpenShiftSource,
				CSRFTokenHeader,
			),
		)
	} else {
		headers.Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, h.realm))
	}

	return headers, nil
}
130772
func AuthServerNegotiateClearOrDialog(c *Conn, method string) (string, error) {
	switch method {
	case MysqlClearPassword:
		// The password is the next packet in plain text.
		return AuthServerReadPacketString(c)

	case MysqlDialog:
		return AuthServerReadPacketString(c)

	default:
		return "", vterrors.Errorf(vtrpc.Code_INTERNAL, "unrecognized method: %v", method)
	}
}
399335
func (s *EnableAllFeaturesOutput) SetHandshake(v *Handshake) *EnableAllFeaturesOutput {
	s.Handshake = v
	return s
}
647081
func initAuthMethod() {
	var signers []ssh.Signer

	// If there's a running SSH Agent, try to use its Private keys.
	sock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
	if err == nil {
		agent := agent.NewClient(sock)
		signers, _ = agent.Signers()
	}

	// Try to read user's SSH private keys form the standard paths.
	files, _ := filepath.Glob(os.Getenv("HOME") + "/.ssh/id_*")
	for _, file := range files {
		if strings.HasSuffix(file, ".pub") {
			continue // Skip public keys.
		}
		data, err := ioutil.ReadFile(file)
		if err != nil {
			continue
		}
		signer, err := ssh.ParsePrivateKey(data)
		if err != nil {
			continue
		}
		signers = append(signers, signer)

	}
	authMethod = ssh.PublicKeys(signers...)
}
1182558
func (a *LocalKeyAgent) AuthMethods() (m []ssh.AuthMethod) {
	// combine our certificates with external SSH agent's:
	var signers []ssh.Signer
	if ourCerts, _ := a.Signers(); ourCerts != nil {
		signers = append(signers, ourCerts...)
	}
	if a.sshAgent != nil {
		if sshAgentCerts, _ := a.sshAgent.Signers(); sshAgentCerts != nil {
			signers = append(signers, sshAgentCerts...)
		}
	}
	// for every certificate create a new "auth method" and return them
	m = make([]ssh.AuthMethod, 0)
	for i := range signers {
		// filter out non-certificates (like regular public SSH keys stored in the SSH agent):
		_, ok := signers[i].PublicKey().(*ssh.Certificate)
		if ok {
			m = append(m, NewAuthMethodForCert(signers[i]))
		}
	}
	return m
}
524522
func (c *socks5BindConn) Handshake() (err error) {
	c.handshakeMux.Lock()
	defer c.handshakeMux.Unlock()

	if c.handshaked {
		return nil
	}

	c.handshaked = true

	rep, err := gosocks5.ReadReply(c.Conn)
	if err != nil {
		return fmt.Errorf("bind: read reply %v", err)
	}
	if rep.Rep != gosocks5.Succeeded {
		return fmt.Errorf("bind: peer connect failure")
	}
	c.raddr, err = net.ResolveTCPAddr("tcp", rep.Addr.String())
	return
}
403585
func ProcessChallenge(challengeMessageData []byte, user, password string) ([]byte, error) {
	if user == "" && password == "" {
		return nil, errors.New("Anonymous authentication not supported")
	}

	var cm challengeMessage
	if err := cm.UnmarshalBinary(challengeMessageData); err != nil {
		return nil, err
	}

	if cm.NegotiateFlags.Has(negotiateFlagNTLMSSPNEGOTIATELMKEY) {
		return nil, errors.New("Only NTLM v2 is supported, but server requested v1 (NTLMSSP_NEGOTIATE_LM_KEY)")
	}
	if cm.NegotiateFlags.Has(negotiateFlagNTLMSSPNEGOTIATEKEYEXCH) {
		return nil, errors.New("Key exchange requested but not supported (NTLMSSP_NEGOTIATE_KEY_EXCH)")
	}

	am := authenicateMessage{
		UserName:       user,
		TargetName:     cm.TargetName,
		NegotiateFlags: cm.NegotiateFlags,
	}

	timestamp := cm.TargetInfo[avIDMsvAvTimestamp]
	if timestamp == nil { // no time sent, take current time
		ft := uint64(time.Now().UnixNano()) / 100
		ft += 116444736000000000 // add time between unix & windows offset
		timestamp = make([]byte, 8)
		binary.LittleEndian.PutUint64(timestamp, ft)
	}

	clientChallenge := make([]byte, 8)
	rand.Reader.Read(clientChallenge)

	ntlmV2Hash := getNtlmV2Hash(password, user, cm.TargetName)

	am.NtChallengeResponse = computeNtlmV2Response(ntlmV2Hash,
		cm.ServerChallenge[:], clientChallenge, timestamp, cm.TargetInfoRaw)

	if cm.TargetInfoRaw == nil {
		am.LmChallengeResponse = computeLmV2Response(ntlmV2Hash,
			cm.ServerChallenge[:], clientChallenge)
	}

	return am.MarshalBinary()
}
620676
func (s *CancelHandshakeOutput) SetHandshake(v *Handshake) *CancelHandshakeOutput {
	s.Handshake = v
	return s
}
1156597
func SOCKS5(network, addr string, auth *Auth, forward Dialer) (Dialer, error) {
	s := &socks5{
		network: network,
		addr:    addr,
		forward: forward,
	}
	if auth != nil {
		s.user = auth.User
		s.password = auth.Password
	}

	return s, nil
}
1082103
func (sc *SignerRemote) SignProposal(chainID string, proposal *types.Proposal) error {
	err := writeMsg(sc.conn, &SignProposalRequest{Proposal: proposal})
	if err != nil {
		return err
	}

	res, err := readMsg(sc.conn)
	if err != nil {
		return err
	}
	resp, ok := res.(*SignedProposalResponse)
	if !ok {
		return ErrUnexpectedResponse
	}
	if resp.Error != nil {
		return resp.Error
	}
	*proposal = *resp.Proposal

	return nil
}
117930
func writeMethodSelection(conn net.Conn) error {
	message := []byte{socks5Version, socks5AuthNotRequired}

	n, err := conn.Write(message)
	if err != nil {
		return trace.Wrap(err)
	}
	if n != len(message) {
		return trace.BadParameter("wrote: %v wanted to write: %v", n, len(message))
	}

	return nil
}
603367
func SOCKS5Handler(opts ...HandlerOption) Handler {
	h := &socks5Handler{}
	h.Init(opts...)

	return h
}