// sweepCryptoMembers will queue "removes" for all cryptomembers with given UID.
// exceptAdminsRemovingOwners - But don't try to remove owners if we are admin.
552763
func (tx *AddMemberTx) sweepCryptoMembers(ctx context.Context, uid keybase1.UID,
	exceptAdminsRemovingOwners bool) {
	team := tx.team
	var myRole keybase1.TeamRole
	if exceptAdminsRemovingOwners {
		var err error
		myRole, err = tx.team.myRole(ctx)
		if err != nil {
			myRole = keybase1.TeamRole_NONE
		}
	}
	for chainUv := range team.chain().inner.UserLog {
		chainRole := team.chain().getUserRole(chainUv)
		if chainUv.Uid.Equal(uid) && chainRole != keybase1.TeamRole_NONE {
			if exceptAdminsRemovingOwners && myRole == keybase1.TeamRole_ADMIN && chainRole == keybase1.TeamRole_OWNER {
				// Skip if we're an admin and they're an owner.
				continue
			}
			tx.removeMember(chainUv)
		}
	}
}
934540
func tagsToMapSecretsManager(ts []*secretsmanager.Tag) map[string]string {
	result := make(map[string]string)
	for _, t := range ts {
		if !tagIgnoredSecretsManager(t) {
			result[*t.Key] = *t.Value
		}
	}

	return result
}
287762
func (m *Manager) Close() {
	m.mtx.Lock()
	defer m.mtx.Unlock()

	if m.closed {
		return
	}

	for _, manager := range m.scopedManagers {
		// Zero out the account keys (if any) of all sub key managers.
		manager.Close()
	}

	// Attempt to clear private key material from memory.
	if !m.watchingOnly && !m.locked {
		m.lock()
	}

	// Remove clear text public master and crypto keys from memory.
	m.cryptoKeyPub.Zero()
	m.masterKeyPub.Zero()

	m.closed = true
	return
}
713497
func (u *utxoNursery) sweepCribOutput(classHeight uint32, baby *babyOutput) error {
	utxnLog.Infof("Publishing CLTV-delayed HTLC output using timeout tx "+
		"(txid=%v): %v", baby.timeoutTx.TxHash(),
		newLogClosure(func() string {
			return spew.Sdump(baby.timeoutTx)
		}),
	)

	// We'll now broadcast the HTLC transaction, then wait for it to be
	// confirmed before transitioning it to kindergarten.
	err := u.cfg.PublishTransaction(baby.timeoutTx)
	if err != nil && err != lnwallet.ErrDoubleSpend {
		utxnLog.Errorf("Unable to broadcast baby tx: "+
			"%v, %v", err, spew.Sdump(baby.timeoutTx))
		return err
	}

	return u.registerTimeoutConf(baby, classHeight)
}
573460
func (tx *AddMemberTx) sweepKeybaseInvites(uid keybase1.UID) {
	team := tx.team
	allInvites := team.GetActiveAndObsoleteInvites()
	for _, invite := range allInvites {
		if inviteUv, err := invite.KeybaseUserVersion(); err == nil {
			if inviteUv.Uid.Equal(uid) && !tx.completedInvites[invite.Id] {
				tx.CancelInvite(invite.Id, uid)
			}
		}
	}
}
429562
func (b *Backend) PurgeGroupMeta(groupUUID string) error {
	conn, channel, err := b.Open(b.GetConfig().Broker, b.GetConfig().TLSConfig)
	if err != nil {
		return err
	}
	defer b.Close(channel, conn)

	b.DeleteQueue(channel, amqmChordTriggeredQueue(groupUUID))

	return b.DeleteQueue(channel, groupUUID)
}
1007750
func scrubPrivKey(cfg *config.Config) (map[string]interface{}, error) {
	cfgMap, err := config.ToMap(cfg)
	if err != nil {
		return nil, err
	}

	err = scrubValue(cfgMap, []string{config.IdentityTag, config.PrivKeyTag})
	if err != nil {
		return nil, err
	}

	return cfgMap, nil
}
1010179
func (a *AuthServer) DeleteRemoteCluster(clusterName string) error {
	// To make sure remote cluster exists - to protect against random
	// clusterName requests (e.g. when clusterName is set to local cluster name)
	_, err := a.Presence.GetRemoteCluster(clusterName)
	if err != nil {
		return trace.Wrap(err)
	}
	// delete cert authorities associated with the cluster
	err = a.DeleteCertAuthority(services.CertAuthID{
		Type:       services.HostCA,
		DomainName: clusterName,
	})
	if err != nil {
		// this method could have succeeded on the first call,
		// but then if the remote cluster resource could not be deleted
		// it would be impossible to delete the cluster after then
		if !trace.IsNotFound(err) {
			return trace.Wrap(err)
		}
	}
	// there should be no User CA in trusted clusters on the main cluster side
	// per standard automation but clean up just in case
	err = a.DeleteCertAuthority(services.CertAuthID{
		Type:       services.UserCA,
		DomainName: clusterName,
	})
	if err != nil {
		if !trace.IsNotFound(err) {
			return trace.Wrap(err)
		}
	}
	return a.Presence.DeleteRemoteCluster(clusterName)
}
876309
func PerUserKeyProof(m MetaContext,
	me *User,
	pukSigKID keybase1.KID,
	pukEncKID keybase1.KID,
	generation keybase1.PerUserKeyGeneration,
	signingKey GenericKey) (*ProofMetadataRes, error) {

	if me == nil {
		return nil, fmt.Errorf("missing user object for proof")
	}

	ret, err := ProofMetadata{
		Me:         me,
		LinkType:   LinkTypePerUserKey,
		SigningKey: signingKey,
	}.ToJSON2(m)
	if err != nil {
		return nil, err
	}

	pukSection := jsonw.NewDictionary()
	pukSection.SetKey("signing_kid", jsonw.NewString(pukSigKID.String()))
	pukSection.SetKey("encryption_kid", jsonw.NewString(pukEncKID.String()))
	pukSection.SetKey("generation", jsonw.NewInt(int(generation)))
	// The caller is responsible for overwriting reverse_sig after signing.
	pukSection.SetKey("reverse_sig", jsonw.NewNil())

	body := ret.J.AtKey("body")
	body.SetKey("per_user_key", pukSection)

	return ret, nil
}
780746
func (g *Generator) RemoveAllSeccompRules() error {
	g.initConfigLinuxSeccomp()
	return seccomp.RemoveAllSeccompRules(g.Config.Linux.Seccomp)
}
1113334
func EncryptPEMBlock(data, password []byte) (*pem.Block, error) {
	encryptedBytes, err := encryptPrivateKey(data, password)
	if err != nil {
		return nil, err
	}

	return &pem.Block{
		Type:    "ENCRYPTED PRIVATE KEY",
		Headers: map[string]string{},
		Bytes:   encryptedBytes,
	}, nil
}
318393
func (x *Index) GetDirMembers(ctx context.Context, dir blob.Ref, dest chan<- blob.Ref, limit int) (err error) {
	defer close(dest)

	sent := 0
	if x.corpus != nil {
		children, err := x.corpus.GetDirChildren(ctx, dir)
		if err != nil {
			return err
		}
		for child := range children {
			dest <- child
			sent++
			if sent == limit {
				break
			}
		}
		return nil
	}

	it := x.queryPrefix(keyStaticDirChild, dir.String())
	defer closeIterator(it, &err)
	for it.Next() {
		keyPart := strings.Split(it.Key(), "|")
		if len(keyPart) != 3 {
			return fmt.Errorf("index: bogus key keyStaticDirChild = %q", it.Key())
		}

		child, ok := blob.Parse(keyPart[2])
		if !ok {
			continue
		}
		dest <- child
		sent++
		if sent == limit {
			break
		}
	}
	return nil
}
1269558
func (s *SecretService) DeleteSecret(ctx context.Context, orgID influxdb.ID, keys ...string) error {
	if err := authorizeWriteSecret(ctx, orgID); err != nil {
		return err
	}

	err := s.s.DeleteSecret(ctx, orgID, keys...)
	if err != nil {
		return err
	}

	return nil
}
644946
func DecryptPEMBlock(block *pem.Block, password []byte) ([]byte, error) {
	der := block.Bytes

	var privKey encryptedPrivateKeyInfo
	if _, err := asn1.Unmarshal(der, &privKey); err != nil {
		return nil, errors.New("pkcs8: only PKCS #5 v2.0 supported")
	}

	if !privKey.EncryptionAlgorithm.IDPBES2.Equal(oidPBES2) {
		return nil, errors.New("pkcs8: only PBES2 supported")
	}

	if !privKey.EncryptionAlgorithm.PBES2Params.KeyDerivationFunc.IDPBKDF2.Equal(oidPKCS5PBKDF2) {
		return nil, errors.New("pkcs8: only PBKDF2 supported")
	}

	encParam := privKey.EncryptionAlgorithm.PBES2Params.EncryptionScheme
	kdfParam := privKey.EncryptionAlgorithm.PBES2Params.KeyDerivationFunc.PBKDF2Params

	switch {
	case encParam.EncryAlgo.Equal(oidAES256CBC):
		iv := encParam.IV
		salt := kdfParam.Salt
		iter := kdfParam.IterationCount

		encryptedKey := privKey.EncryptedData
		symkey := pbkdf2.Key(password, salt, iter, 32, sha1.New)
		block, err := aes.NewCipher(symkey)
		if err != nil {
			return nil, err
		}
		mode := cipher.NewCBCDecrypter(block, iv)
		mode.CryptBlocks(encryptedKey, encryptedKey)

		if _, err := derhelpers.ParsePrivateKeyDER(encryptedKey); err != nil {
			return nil, errors.New("pkcs8: incorrect password")
		}

		// Remove padding from key as it might be used to encode to memory as pem
		keyLen := len(encryptedKey)
		padLen := int(encryptedKey[keyLen-1])
		if padLen > keyLen || padLen > aes.BlockSize {
			return nil, errors.New("pkcs8: invalid padding size")
		}
		encryptedKey = encryptedKey[:keyLen-padLen]

		return encryptedKey, nil
	default:
		return nil, errors.New("pkcs8: only AES-256-CBC supported")
	}
}
770907
func (s *State) MemberRemove(member *Member) error {
	if s == nil {
		return ErrNilState
	}

	guild, err := s.Guild(member.GuildID)
	if err != nil {
		return err
	}

	s.Lock()
	defer s.Unlock()

	members, ok := s.memberMap[member.GuildID]
	if !ok {
		return ErrStateNotFound
	}

	_, ok = members[member.User.ID]
	if !ok {
		return ErrStateNotFound
	}
	delete(members, member.User.ID)

	for i, m := range guild.Members {
		if m.User.ID == member.User.ID {
			guild.Members = append(guild.Members[:i], guild.Members[i+1:]...)
			return nil
		}
	}

	return ErrStateNotFound
}
462757
func (u *utils) EncryptPEMBlock(data, password []byte) (*pem.Block, error) {
	if IsPKCS8(data) {
		return pkcs8.EncryptPEMBlock(data, password)
	} else if u.fips {
		return nil, ErrFIPSUnsupportedKeyFormat
	}

	cipherType := x509.PEMCipherAES256
	return x509.EncryptPEMBlock(cryptorand.Reader,
		"EC PRIVATE KEY",
		data,
		password,
		cipherType)
}
799564
func (pm *PolicyMap) DeleteEntry(entry *PolicyEntryDump) error {
	return pm.Map.Delete(&entry.Key)
}