// handleTypeCA is used to handle SSH logins using the "CA" key type.
177341
func (c *SSHCommand) handleTypeCA(username, ip, port string, sshArgs []string) int {
	// Read the key from disk
	publicKey, err := ioutil.ReadFile(c.flagPublicKeyPath)
	if err != nil {
		c.UI.Error(fmt.Sprintf("failed to read public key %s: %s",
			c.flagPublicKeyPath, err))
		return 1
	}

	sshClient := c.client.SSHWithMountPoint(c.flagMountPoint)

	var principals = username
	if c.flagValidPrincipals != "" {
		principals = c.flagValidPrincipals
	}

	// Attempt to sign the public key
	secret, err := sshClient.SignKey(c.flagRole, map[string]interface{}{
		// WARNING: publicKey is []byte, which is b64 encoded on JSON upload. We
		// have to convert it to a string. SV lost many hours to this...
		"public_key":       string(publicKey),
		"valid_principals": principals,
		"cert_type":        "user",

		// TODO: let the user configure these. In the interim, if users want to
		// customize these values, they can produce the key themselves.
		"extensions": map[string]string{
			"permit-X11-forwarding":   "",
			"permit-agent-forwarding": "",
			"permit-port-forwarding":  "",
			"permit-pty":              "",
			"permit-user-rc":          "",
		},
	})
	if err != nil {
		c.UI.Error(fmt.Sprintf("failed to sign public key %s: %s",
			c.flagPublicKeyPath, err))
		return 2
	}
	if secret == nil || secret.Data == nil {
		c.UI.Error("missing signed key")
		return 2
	}

	// Handle no-exec
	if c.flagNoExec {
		if c.flagField != "" {
			return PrintRawField(c.UI, secret, c.flagField)
		}
		return OutputSecret(c.UI, secret)
	}

	// Extract public key
	key, ok := secret.Data["signed_key"].(string)
	if !ok || key == "" {
		c.UI.Error("signed key is empty")
		return 2
	}

	// Capture the current value - this could be overwritten later if the user
	// enabled host key signing verification.
	userKnownHostsFile := c.flagUserKnownHostsFile
	strictHostKeyChecking := c.flagStrictHostKeyChecking

	// Handle host key signing verification. If the user specified a mount point,
	// download the public key, trust it with the given domains, and use that
	// instead of the user's regular known_hosts file.
	if c.flagHostKeyMountPoint != "" {
		secret, err := c.client.Logical().Read(c.flagHostKeyMountPoint + "/config/ca")
		if err != nil {
			c.UI.Error(fmt.Sprintf("failed to get host signing key: %s", err))
			return 2
		}
		if secret == nil || secret.Data == nil {
			c.UI.Error("missing host signing key")
			return 2
		}
		publicKey, ok := secret.Data["public_key"].(string)
		if !ok || publicKey == "" {
			c.UI.Error("host signing key is empty")
			return 2
		}

		// Write the known_hosts file
		name := fmt.Sprintf("vault_ssh_ca_known_hosts_%s_%s", username, ip)
		data := fmt.Sprintf("@cert-authority %s %s", c.flagHostKeyHostnames, publicKey)
		knownHosts, err, closer := c.writeTemporaryFile(name, []byte(data), 0644)
		defer closer()
		if err != nil {
			c.UI.Error(fmt.Sprintf("failed to write host public key: %s", err))
			return 1
		}

		// Update the variables
		userKnownHostsFile = knownHosts
		strictHostKeyChecking = "yes"
	}

	// Write the signed public key to disk
	name := fmt.Sprintf("vault_ssh_ca_%s_%s", username, ip)
	signedPublicKeyPath, err, closer := c.writeTemporaryKey(name, []byte(key))
	defer closer()
	if err != nil {
		c.UI.Error(fmt.Sprintf("failed to write signed public key: %s", err))
		return 2
	}

	args := []string{
		"-i", c.flagPrivateKeyPath,
		"-i", signedPublicKeyPath,
		"-o StrictHostKeyChecking=" + strictHostKeyChecking,
	}

	if userKnownHostsFile != "" {
		args = append(args,
			"-o UserKnownHostsFile="+userKnownHostsFile,
		)
	}

	// Add extra user defined ssh arguments
	args = append(args, sshArgs...)

	cmd := exec.Command(c.flagSSHExecutable, args...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err = cmd.Run()
	if err != nil {
		exitCode := 2

		if exitError, ok := err.(*exec.ExitError); ok {
			if exitError.Success() {
				return 0
			}
			if ws, ok := exitError.Sys().(syscall.WaitStatus); ok {
				exitCode = ws.ExitStatus()
			}
		}

		c.UI.Error(fmt.Sprintf("failed to run ssh command: %s", err))
		return exitCode
	}

	// There is no secret to revoke, since it's a certificate signing
	return 0
}
248952
func (c *Client) DelCAS(key string, cas uint64) (err error) {
	// Variants: [R] Del [Q]
	// Request : MUST key; MUST NOT value, extras
	// Response: MUST NOT key, value, extras
	m := &msg{
		header: header{
			Op:  opDelete,
			CAS: cas,
		},
		key: key,
	}

	return c.perform(m)
}
185597
func (sd *structDef) handleAdvancedType(apiDef *raml.APIDefinition) {
	if sd.T.Type == nil {
		sd.T.Type = "object"
	}

	parents, isMultipleInherit := sd.T.MultipleInheritance()
	parent, isSingleInherit := sd.T.SingleInheritance()

	switch {
	case isMultipleInherit:
		sd.addMultipleInheritance(apiDef, parents)
	case sd.T.IsUnion():
		sd.buildUnion()
	case sd.T.IsArray():
		sd.buildArray()
	case strings.ToLower(sd.T.TypeString()) == "object": // plain type
		return
	case sd.T.IsEnum():
		sd.buildEnum()
	case sd.T.IsAlias():
		sd.buildTypeAlias(apiDef)
	case isSingleInherit:
		sd.addSingleInheritance(apiDef, parent)
	}
}
814226
func handleDecodeScript(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	c := cmd.(*btcjson.DecodeScriptCmd)

	// Convert the hex script to bytes.
	hexStr := c.HexScript
	if len(hexStr)%2 != 0 {
		hexStr = "0" + hexStr
	}
	script, err := hex.DecodeString(hexStr)
	if err != nil {
		return nil, rpcDecodeHexError(hexStr)
	}

	// The disassembled string will contain [error] inline if the script
	// doesn't fully parse, so ignore the error here.
	disbuf, _ := txscript.DisasmString(script)

	// Get information about the script.
	// Ignore the error here since an error means the script couldn't parse
	// and there is no additinal information about it anyways.
	scriptClass, addrs, reqSigs, _ := txscript.ExtractPkScriptAddrs(script,
		s.cfg.ChainParams)
	addresses := make([]string, len(addrs))
	for i, addr := range addrs {
		addresses[i] = addr.EncodeAddress()
	}

	// Convert the script itself to a pay-to-script-hash address.
	p2sh, err := btcutil.NewAddressScriptHash(script, s.cfg.ChainParams)
	if err != nil {
		context := "Failed to convert script to pay-to-script-hash"
		return nil, internalRPCError(err.Error(), context)
	}

	// Generate and return the reply.
	reply := btcjson.DecodeScriptResult{
		Asm:       disbuf,
		ReqSigs:   int32(reqSigs),
		Type:      scriptClass.String(),
		Addresses: addresses,
	}
	if scriptClass != txscript.ScriptHashTy {
		reply.P2sh = p2sh.EncodeAddress()
	}
	return reply, nil
}
598587
func HandleCredentialError(err error, ctx context.ProviderCallContext) {
	common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
}
165311
func (r *RotateRequest) Types() []services.CertAuthType {
	switch r.Type {
	case "":
		return []services.CertAuthType{services.HostCA, services.UserCA}
	case services.HostCA:
		return []services.CertAuthType{services.HostCA}
	case services.UserCA:
		return []services.CertAuthType{services.UserCA}
	}
	return nil
}
382734
func (s *CA) DeleteAllCertAuthorities(caType services.CertAuthType) error {
	startKey := backend.Key(authoritiesPrefix, string(caType))
	return s.DeleteRange(context.TODO(), startKey, backend.RangeEnd(startKey))
}
1029754
func (b *SystemBackend) handleCORSUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	origins := d.Get("allowed_origins").([]string)
	headers := d.Get("allowed_headers").([]string)

	return nil, b.Core.corsConfig.Enable(ctx, origins, headers)
}
581544
func RegisterServerType(typeName string, srv ServerType) {
	if _, ok := serverTypes[typeName]; ok {
		panic("server type already registered")
	}
	serverTypes[typeName] = srv
}
1325607
func (api *SignerAPI) SignTypedData(ctx context.Context, addr common.MixedcaseAddress, typedData TypedData) (hexutil.Bytes, error) {
	domainSeparator, err := typedData.HashStruct("EIP712Domain", typedData.Domain.Map())
	if err != nil {
		return nil, err
	}
	typedDataHash, err := typedData.HashStruct(typedData.PrimaryType, typedData.Message)
	if err != nil {
		return nil, err
	}
	rawData := []byte(fmt.Sprintf("\x19\x01%s%s", string(domainSeparator), string(typedDataHash)))
	sighash := crypto.Keccak256(rawData)
	message := typedData.Format()
	req := &SignDataRequest{ContentType: DataTyped.Mime, Rawdata: rawData, Message: message, Hash: sighash}
	signature, err := api.sign(addr, req, true)
	if err != nil {
		api.UI.ShowError(err.Error())
		return nil, err
	}
	return signature, nil
}
331980
func (h *AuthHandlers) IsHostAuthority(cert ssh.PublicKey, address string) bool {
	if _, err := h.authorityForCert(services.HostCA, cert); err != nil {
		h.Entry.Debugf("Unable to find SSH host CA: %v.", err)
		return false
	}
	return true
}
33613
func readCA(params RegisterParams) (*x509.Certificate, error) {
	certBytes, err := utils.ReadPath(params.CAPath)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	cert, err := tlsca.ParseCertificatePEM(certBytes)
	if err != nil {
		return nil, trace.Wrap(err, "failed to parse certificate at %v", params.CAPath)
	}
	return cert, nil
}
282166
func (c *central) handleReadByType(b []byte) []byte {
	start, end := readHandleRange(b[:4])
	t := UUID{b[4:]}

	w := newL2capWriter(c.mtu)
	w.WriteByteFit(attOpReadByTypeRsp)
	uuidLen := -1
	for _, a := range c.attrs.Subrange(start, end) {
		if !a.typ.Equal(t) {
			continue
		}
		if (a.secure&CharRead) != 0 && c.security > securityLow {
			return attErrorRsp(attOpReadByTypeReq, start, attEcodeAuthentication)
		}
		v := a.value
		if v == nil {
			rsp := newResponseWriter(int(c.mtu - 1))
			req := &ReadRequest{
				Request: Request{Central: c},
				Cap:     int(c.mtu - 1),
				Offset:  0,
			}
			if c, ok := a.pvt.(*Characteristic); ok {
				c.rhandler.ServeRead(rsp, req)
			} else if d, ok := a.pvt.(*Descriptor); ok {
				d.rhandler.ServeRead(rsp, req)
			}
			v = rsp.bytes()
		}
		if uuidLen == -1 {
			uuidLen = len(v)
			w.WriteByteFit(byte(uuidLen) + 2)
		}
		if len(v) != uuidLen {
			break
		}
		w.Chunk()
		w.WriteUint16Fit(a.h)
		w.WriteFit(v)
		if ok := w.Commit(); !ok {
			break
		}
	}
	if uuidLen == -1 {
		return attErrorRsp(attOpReadByTypeReq, start, attEcodeAttrNotFound)
	}
	return w.Bytes()
}
824015
func HandleCredentialError(isAuthError func(error) bool, err error, ctx context.ProviderCallContext) {
	MaybeHandleCredentialError(isAuthError, err, ctx)
}
510743
func (p *Provider) handleCallback(rw http.ResponseWriter, req *http.Request, _ router.Params) error {
	// oauth handshake
	code := req.FormValue("code")
	accessToken, err := p.Config.Exchange(oauth2.NoContext, code)
	if err != nil {
		return errors.Wrap(err)
	}
	var state string
	encState := req.FormValue("state")
	if encState != "" {
		stateByte, err := base64.StdEncoding.DecodeString(encState)
		if err != nil {
			return errors.New("error decoding state: %s", err)
		}
		state = string(stateByte)
	}
	err = p.PostCallback(req, rw, accessToken, state)
	if err != nil {
		return errors.Wrap(err)
	}
	return nil
}
200912
func (t *Token) Type() string {
	if strings.EqualFold(t.TokenType, "bearer") {
		return "Bearer"
	}
	if strings.EqualFold(t.TokenType, "mac") {
		return "MAC"
	}
	if strings.EqualFold(t.TokenType, "basic") {
		return "Basic"
	}
	if t.TokenType != "" {
		return t.TokenType
	}
	return "Bearer"
}
15024
func handleAccountOrigin(h goa.Handler) goa.Handler {

	return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
		origin := req.Header.Get("Origin")
		if origin == "" {
			// Not a CORS request
			return h(ctx, rw, req)
		}
		if cors.MatchOrigin(origin, "http://swagger.goa.design") {
			ctx = goa.WithLogContext(ctx, "origin", origin)
			rw.Header().Set("Access-Control-Allow-Origin", origin)
			rw.Header().Set("Vary", "Origin")
			rw.Header().Set("Access-Control-Max-Age", "600")
			rw.Header().Set("Access-Control-Allow-Credentials", "true")
			if acrm := req.Header.Get("Access-Control-Request-Method"); acrm != "" {
				// We are handling a preflight request
				rw.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
			}
			return h(ctx, rw, req)
		}

		return h(ctx, rw, req)
	}
}