// VerifyMerkleRootAndKBFS checks that the given merkle root is indeed a valid
// root of the keybase server's Merkle tree, and that the given KBFS root
// is included in that global root.
7279
func (c MerkleClient) VerifyMerkleRootAndKBFS(ctx context.Context, __arg VerifyMerkleRootAndKBFSArg) (err error) {
	err = c.Cli.Call(ctx, "keybase.1.merkle.verifyMerkleRootAndKBFS", []interface{}{__arg}, nil)
	return
}
2381
func (sc *syncContext) verifyPermittedHooks(hooks []*unstructured.Unstructured) bool {
	for _, hook := range hooks {
		gvk := hook.GroupVersionKind()
		serverRes, err := kube.ServerResourceForGroupVersionKind(sc.disco, gvk)
		if err != nil {
			sc.setOperationPhase(appv1.OperationError, fmt.Sprintf("unable to identify api resource type: %v", gvk))
			return false
		}
		if !sc.proj.IsResourcePermitted(metav1.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, serverRes.Namespaced) {
			sc.setOperationPhase(appv1.OperationFailed, fmt.Sprintf("Hook resource %s:%s is not permitted in project %s", gvk.Group, gvk.Kind, sc.proj.Name))
			return false
		}

		if serverRes.Namespaced && !sc.proj.IsDestinationPermitted(appv1.ApplicationDestination{Namespace: hook.GetNamespace(), Server: sc.server}) {
			gvk := hook.GroupVersionKind()
			sc.setResourceDetails(&appv1.ResourceResult{
				Name:      hook.GetName(),
				Group:     gvk.Group,
				Version:   gvk.Version,
				Kind:      hook.GetKind(),
				Namespace: hook.GetNamespace(),
				Message:   fmt.Sprintf("namespace %v is not permitted in project '%s'", hook.GetNamespace(), sc.proj.Name),
				Status:    appv1.ResultCodeSyncFailed,
			})
			return false
		}
	}
	return true
}
1184617
func stateHasKeySeed(m libkb.MetaContext, gen keybase1.PerTeamKeyGeneration, state *keybase1.FastTeamData) bool {
	_, foundVerified := state.Chain.PerTeamKeySeedsVerified[gen]
	if foundVerified {
		return true
	}
	_, foundUnverifiedSeed := state.PerTeamKeySeedsUnverified[gen]
	if !foundUnverifiedSeed {
		return false
	}
	_, foundPerTeamKey := state.Chain.PerTeamKeys[gen]
	if !foundPerTeamKey {
		return false
	}
	return true
}
154002
func (sp *SimpleProof) Verify(rootHash []byte, leaf []byte) error {
	leafHash := leafHash(leaf)
	if sp.Total < 0 {
		return errors.New("Proof total must be positive")
	}
	if sp.Index < 0 {
		return errors.New("Proof index cannot be negative")
	}
	if !bytes.Equal(sp.LeafHash, leafHash) {
		return cmn.NewError("invalid leaf hash: wanted %X got %X", leafHash, sp.LeafHash)
	}
	computedHash := sp.ComputeRootHash()
	if !bytes.Equal(computedHash, rootHash) {
		return cmn.NewError("invalid root hash: wanted %X got %X", rootHash, computedHash)
	}
	return nil
}
81483
func (k *KeybaseServiceBase) RootAuditError(ctx context.Context,
	arg keybase1.RootAuditErrorArg) error {
	k.log.CDebugf(ctx, "Merkle tree audit error: %v", arg.Message)
	return nil
}
1149634
func (md *RootMetadataV2) IsValidRekeyRequest(
	codec kbfscodec.Codec, prevBareMd RootMetadata,
	user keybase1.UID, _, _ ExtraMetadata) (bool, error) {
	if !md.IsWriterMetadataCopiedSet() {
		// Not a copy.
		return false, nil
	}
	prevMd, ok := prevBareMd.(*RootMetadataV2)
	if !ok {
		// Not the same type so not a copy.
		return false, nil
	}
	writerEqual, err := kbfscodec.Equal(
		codec, md.WriterMetadataV2, prevMd.WriterMetadataV2)
	if err != nil {
		return false, err
	}
	if !writerEqual {
		// Copy mismatch.
		return false, nil
	}
	writerSigInfoEqual, err := kbfscodec.Equal(codec,
		md.WriterMetadataSigInfo, prevMd.WriterMetadataSigInfo)
	if err != nil {
		return false, err
	}
	if !writerSigInfoEqual {
		// Signature/public key mismatch.
		return false, nil
	}
	onlyUserRKeysChanged, err := md.haveOnlyUserRKeysChanged(
		codec, prevMd, user)
	if err != nil {
		return false, err
	}
	if !onlyUserRKeysChanged {
		// Keys outside of this user's reader key set have changed.
		return false, nil
	}
	return true, nil
}
439365
func (ks *Keystore) DeleteTrustedKeyRoot(fingerprint string) error {
	return os.Remove(path.Join(ks.LocalRootPath, fingerprint))
}
581813
func CheckWKBID(codec kbfscodec.Codec,
	wkbID TLFWriterKeyBundleID, wkb TLFWriterKeyBundleV3) error {
	computedWKBID, err := MakeTLFWriterKeyBundleID(codec, wkb)
	if err != nil {
		return err
	}

	if wkbID != computedWKBID {
		return errors.Errorf("Expected WKB ID %s, got %s",
			wkbID, computedWKBID)
	}

	return nil
}
242028
func (c *CyclePDB) VerifyBuckets() error {
	return c.blobs.foreachView(func(tx *bolt.Tx) error {
		bucket := tx.Bucket(c.bucketTimesIn)
		if bucket == nil {
			return errorUnableToFindRootBucket
		}
		return nil
	})
}
464521
func (fbo *folderBranchOps) validateHeadLocked(
	ctx context.Context, lState *kbfssync.LockState,
	md ImmutableRootMetadata) error {
	fbo.headLock.AssertLocked(lState)

	// Validate fbo against fetched md and discard the fetched one.
	if fbo.head.TlfID() != md.TlfID() {
		fbo.log.CCriticalf(ctx, "Fake untrusted TLF encountered %v %v %v %v", fbo.head.TlfID(), md.TlfID(), fbo.head.mdID, md.mdID)
		return kbfsmd.MDTlfIDMismatch{CurrID: fbo.head.TlfID(), NextID: md.TlfID()}
	}
	fbo.headStatus = headTrusted
	return nil
}
929537
func (md *RootMetadataV2) IsValidAndSigned(
	_ context.Context, codec kbfscodec.Codec,
	_ TeamMembershipChecker, extra ExtraMetadata,
	_ kbfscrypto.VerifyingKey, _ keybase1.OfflineAvailability) error {
	// Optimization -- if the WriterMetadata signature is nil, it
	// will fail verification.
	if md.WriterMetadataSigInfo.IsNil() {
		return errors.New("Missing WriterMetadata signature")
	}

	if md.IsFinal() {
		if md.Revision < RevisionInitial+1 {
			return fmt.Errorf("Invalid final revision %d", md.Revision)
		}

		if md.Revision == (RevisionInitial + 1) {
			if md.PrevRoot != (ID{}) {
				return fmt.Errorf("Invalid PrevRoot %s for initial final revision", md.PrevRoot)
			}
		} else {
			if md.PrevRoot == (ID{}) {
				return errors.New("No PrevRoot for non-initial final revision")
			}
		}
	} else {
		if md.Revision < RevisionInitial {
			return fmt.Errorf("Invalid revision %d", md.Revision)
		}

		if md.Revision == RevisionInitial {
			if md.PrevRoot != (ID{}) {
				return fmt.Errorf("Invalid PrevRoot %s for initial revision", md.PrevRoot)
			}
		} else {
			if md.PrevRoot == (ID{}) {
				return errors.New("No PrevRoot for non-initial revision")
			}
		}
	}

	if len(md.SerializedPrivateMetadata) == 0 {
		return errors.New("No private metadata")
	}

	if (md.MergedStatus() == Merged) != (md.BID() == NullBranchID) {
		return fmt.Errorf("Branch ID %s doesn't match merged status %s",
			md.BID(), md.MergedStatus())
	}

	handle, err := md.MakeBareTlfHandle(extra)
	if err != nil {
		return err
	}

	// Make sure the last writer is valid.  TODO(KBFS-2185): for a
	// team TLF, check that the writer is part of the team.
	writer := md.LastModifyingWriter()
	if !handle.IsWriter(writer.AsUserOrTeam()) {
		return fmt.Errorf("Invalid modifying writer %s", writer)
	}

	// Make sure the last modifier is valid.
	user := md.LastModifyingUser
	if !handle.IsReader(user.AsUserOrTeam()) {
		return fmt.Errorf("Invalid modifying user %s", user)
	}

	// Verify signature. We have to re-marshal the WriterMetadata,
	// since it's embedded.
	buf, err := codec.Encode(md.WriterMetadataV2)
	if err != nil {
		return err
	}

	err = kbfscrypto.Verify(buf, md.WriterMetadataSigInfo)
	if err != nil {
		return fmt.Errorf("Could not verify writer metadata: %v", err)
	}

	return nil
}
696566
func VerifyProof(rootHash common.Hash, key []byte, proofDb ethdb.Reader) (value []byte, nodes int, err error) {
	key = keybytesToHex(key)
	wantHash := rootHash
	for i := 0; ; i++ {
		buf, _ := proofDb.Get(wantHash[:])
		if buf == nil {
			return nil, i, fmt.Errorf("proof node %d (hash %064x) missing", i, wantHash)
		}
		n, err := decodeNode(wantHash[:], buf)
		if err != nil {
			return nil, i, fmt.Errorf("bad proof node %d: %v", i, err)
		}
		keyrest, cld := get(n, key)
		switch cld := cld.(type) {
		case nil:
			// The trie doesn't contain the key.
			return nil, i, nil
		case hashNode:
			key = keyrest
			copy(wantHash[:], cld)
		case valueNode:
			return cld, i + 1, nil
		}
	}
}
874995
func (d *Driver) verifyRootPermissions() error {
	exe, err := os.Executable()
	if err != nil {
		return err
	}
	euid := syscall.Geteuid()
	log.Debugf("exe=%s uid=%d", exe, euid)
	if euid != 0 {
		return fmt.Errorf(permErr, filepath.Base(exe), exe, exe)
	}
	return nil
}
1198294
func VerifyWithJWK(buf []byte, key jwk.Key) (payload []byte, err error) {

	keyval, err := key.Materialize()
	if err != nil {
		return nil, errors.Wrap(err, `failed to materialize jwk.Key`)
	}

	payload, err = Verify(buf, jwa.SignatureAlgorithm(key.Algorithm()), keyval)
	if err != nil {
		return nil, errors.Wrap(err, "failed to verify message")
	}
	return payload, nil
}
905701
func (fbo *folderBranchOps) getMDForRekeyWriteLocked(
	ctx context.Context, lState *kbfssync.LockState) (
	rmd *RootMetadata, lastWriterVerifyingKey kbfscrypto.VerifyingKey,
	wasRekeySet bool, err error) {
	fbo.mdWriterLock.AssertLocked(lState)

	md, err := fbo.getMDForWriteOrRekeyLocked(ctx, lState, mdRekey)
	if err != nil {
		return nil, kbfscrypto.VerifyingKey{}, false, err
	}

	if md.TypeForKeying() == tlf.TeamKeying {
		return nil, kbfscrypto.VerifyingKey{}, false, nil
	}

	session, err := fbo.config.KBPKI().GetCurrentSession(ctx)
	if err != nil {
		return nil, kbfscrypto.VerifyingKey{}, false, err
	}

	handle := md.GetTlfHandle()

	// must be a reader or writer (it checks both.)
	if !handle.IsReader(session.UID) {
		return nil, kbfscrypto.VerifyingKey{}, false,
			NewRekeyPermissionError(md.GetTlfHandle(), session.Name)
	}

	newMd, err := md.MakeSuccessor(ctx, fbo.config.MetadataVersion(),
		fbo.config.Codec(),
		fbo.config.KeyManager(), fbo.config.KBPKI(), fbo.config.KBPKI(),
		fbo.config, md.mdID, handle.IsWriter(session.UID))
	if err != nil {
		return nil, kbfscrypto.VerifyingKey{}, false, err
	}

	// readers shouldn't modify writer metadata
	if !handle.IsWriter(session.UID) && !newMd.IsWriterMetadataCopiedSet() {
		return nil, kbfscrypto.VerifyingKey{}, false,
			NewRekeyPermissionError(handle, session.Name)
	}

	return newMd, md.LastModifyingWriterVerifyingKey(), md.IsRekeySet(), nil
}
889768
func (md *MDOpsStandard) convertVerifyingKeyError(ctx context.Context,
	rmds *RootMetadataSigned, handle *tlfhandle.Handle, err error) error {
	if _, ok := err.(VerifyingKeyNotFoundError); !ok {
		return err
	}

	tlf := handle.GetCanonicalPath()
	writer, nameErr := md.config.KBPKI().GetNormalizedUsername(
		ctx, rmds.MD.LastModifyingWriter().AsUserOrTeam(),
		md.config.OfflineAvailabilityForPath(tlf))
	if nameErr != nil {
		writer = kbname.NormalizedUsername("uid: " +
			rmds.MD.LastModifyingWriter().String())
	}
	md.log.CDebugf(ctx, "Unverifiable update for TLF %s: %+v",
		rmds.MD.TlfID(), err)
	return UnverifiableTlfUpdateError{tlf, writer, err}
}
338991
func readMerkleRoot(m libkb.MetaContext, link *ChainLinkUnpacked) (*keybase1.MerkleRootV2, error) {
	if link.inner == nil {
		return nil, nil
	}
	ret := link.inner.Body.MerkleRoot.ToMerkleRootV2()
	return &ret, nil
}