// Fingerprint returns a human-readable SHA-256 fingerprint for a certificate
// stored in the PEM format. The returned fingerprint matches the output of:
// openssl x509 -noout -fingerprint -sha256 -inform pem -in cert.pem
484058
func Fingerprint(certPEM string) (string, error) {
	block, _ := pem.Decode([]byte(certPEM))
	if block == nil {
		return "", errors.New("input does not contain a valid certificate in PEM format")
	}

	if _, err := x509.ParseCertificate(block.Bytes); err != nil {
		return "", errors.Annotate(err, "cannot calculate certificate fingerprint")
	}

	// fingerprint format is: XX:YY:...:ZZ
	fingerprint := make([]byte, (sha256.Size*3)-1)
	var index int
	for _, fb := range sha256.Sum256(block.Bytes) {
		if index != 0 {
			fingerprint[index] = ':'
			index++
		}

		// Encode each byte as two chars
		fingerprint[index] = hexAlphabet[(fb>>4)&0xf]
		fingerprint[index+1] = hexAlphabet[fb&0xf]
		index += 2
	}

	return string(fingerprint), nil
}
791891
func (d *Driver) setFingerprintSuccess() {
	d.fingerprintLock.Lock()
	d.fingerprintSuccess = helper.BoolToPtr(true)
	d.fingerprintLock.Unlock()
}
65120
func (d *FsDevice) fingerprint(ctx context.Context, devices chan *device.FingerprintResponse) {
	defer close(devices)

	// Create a timer that will fire immediately for the first detection
	ticker := time.NewTimer(0)

	for {
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
			ticker.Reset(d.listPeriod)
		}

		d.logger.Trace("scanning for changes")

		files, err := ioutil.ReadDir(d.deviceDir)
		if err != nil {
			d.logger.Error("failed to list device directory", "error", err)
			devices <- device.NewFingerprintError(err)
			return
		}

		detected := d.diffFiles(files)
		if len(detected) == 0 {
			continue
		}

		devices <- device.NewFingerprint(getDeviceGroup(detected))

	}
}
936202
func (a AssertionFingerprint) MatchProof(proof Proof) bool {
	v1, v2 := strings.ToLower(proof.Value), a.Value
	l1, l2 := len(v1), len(v2)
	if l2 > l1 {
		return false
	}
	// Match the suffixes of the fingerprint
	return (v1[(l1-l2):] == v2)
}
136501
func Fingerprint256(data []byte) string {
	d := sha256.New()
	_, _ = d.Write(data) // Never returns an error
	return base64.RawURLEncoding.EncodeToString(d.Sum(nil))
}
1294672
func (l *PluginLoader) fingerprintPlugin(pluginExe os.FileInfo, config *config.PluginConfig) (*pluginInfo, error) {
	info := &pluginInfo{
		exePath: filepath.Join(l.pluginDir, pluginExe.Name()),
	}

	// Build the command
	cmd := exec.Command(info.exePath)
	if config != nil {
		cmd.Args = append(cmd.Args, config.Args...)
		info.args = config.Args
		info.config = config.Config
	}

	// Launch the plugin
	client := plugin.NewClient(&plugin.ClientConfig{
		HandshakeConfig: base.Handshake,
		Plugins: map[string]plugin.Plugin{
			base.PluginTypeBase: &base.PluginBase{},
		},
		Cmd:              cmd,
		AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},
		Logger:           l.logger,
	})
	defer client.Kill()

	// Connect via RPC
	rpcClient, err := client.Client()
	if err != nil {
		return nil, err
	}

	// Request the plugin
	raw, err := rpcClient.Dispense(base.PluginTypeBase)
	if err != nil {
		return nil, err
	}

	// Cast the plugin to the base type
	bplugin := raw.(base.BasePlugin)

	// Retrieve base plugin information
	i, err := bplugin.PluginInfo()
	if err != nil {
		return nil, fmt.Errorf("failed to get plugin info for plugin %q: %v", info.exePath, err)
	}
	info.baseInfo = i

	// Parse and set the plugin version
	v, err := version.NewVersion(i.PluginVersion)
	if err != nil {
		return nil, fmt.Errorf("failed to parse plugin %q (%v) version %q: %v",
			i.Name, info.exePath, i.PluginVersion, err)
	}
	info.version = v

	// Detect the plugin API version to use
	av, err := l.selectApiVersion(i)
	if err != nil {
		return nil, fmt.Errorf("failed to validate API versions %v for plugin %s (%v): %v", i.PluginApiVersions, i.Name, info.exePath, err)
	}
	if av == "" {
		l.logger.Warn("skipping plugin because supported API versions for plugin and Nomad do not overlap", "plugin", i.Name, "path", info.exePath)
		return nil, nil
	}
	info.apiVersion = av

	// Retrieve the schema
	schema, err := bplugin.ConfigSchema()
	if err != nil {
		return nil, fmt.Errorf("failed to get plugin config schema for plugin %q: %v", info.exePath, err)
	}
	info.configSchema = schema

	return info, nil
}
1132172
func attributesFromFingerprintDeviceData(d *nvml.FingerprintDeviceData) map[string]*structs.Attribute {
	attrs := map[string]*structs.Attribute{
		DisplayStateAttr: {
			String: helper.StringToPtr(d.DisplayState),
		},
		PersistenceModeAttr: {
			String: helper.StringToPtr(d.PersistenceMode),
		},
	}

	if d.MemoryMiB != nil {
		attrs[MemoryAttr] = &structs.Attribute{
			Int:  helper.Int64ToPtr(int64(*d.MemoryMiB)),
			Unit: structs.UnitMiB,
		}
	}
	if d.PowerW != nil {
		attrs[PowerAttr] = &structs.Attribute{
			Int:  helper.Int64ToPtr(int64(*d.PowerW)),
			Unit: structs.UnitW,
		}
	}
	if d.BAR1MiB != nil {
		attrs[BAR1Attr] = &structs.Attribute{
			Int:  helper.Int64ToPtr(int64(*d.BAR1MiB)),
			Unit: structs.UnitMiB,
		}
	}
	if d.CoresClockMHz != nil {
		attrs[CoresClockAttr] = &structs.Attribute{
			Int:  helper.Int64ToPtr(int64(*d.CoresClockMHz)),
			Unit: structs.UnitMHz,
		}
	}
	if d.MemoryClockMHz != nil {
		attrs[MemoryClockAttr] = &structs.Attribute{
			Int:  helper.Int64ToPtr(int64(*d.MemoryClockMHz)),
			Unit: structs.UnitMHz,
		}
	}
	if d.PCIBandwidthMBPerS != nil {
		attrs[PCIBandwidthAttr] = &structs.Attribute{
			Int:  helper.Int64ToPtr(int64(*d.PCIBandwidthMBPerS)),
			Unit: structs.UnitMBPerS,
		}
	}

	return attrs
}
626858
func writeFingerprint(buf *bytes.Buffer, part ast.Node, braces bool) {
	switch part := part.(type) {
	case *ast.MsgNode:
		for _, part := range part.Body.Children() {
			writeFingerprint(buf, part, braces)
		}
	case *ast.RawTextNode:
		buf.Write(part.Text)
	case *ast.MsgPlaceholderNode:
		if braces {
			buf.WriteString("{" + part.Name + "}")
		} else {
			buf.WriteString(part.Name)
		}
	case *ast.MsgPluralNode:
		buf.WriteString("{" + part.VarName + ",plural,")
		for _, plCase := range part.Cases {
			buf.WriteString("=" + strconv.Itoa(plCase.Value) + "{")
			for _, child := range plCase.Body.Children() {
				writeFingerprint(buf, child, true)
			}
			buf.WriteString("}")
		}
		buf.WriteString("other{")
		for _, child := range part.Default.Children() {
			writeFingerprint(buf, child, true)
		}
		buf.WriteString("}}")
	default:
		panic(fmt.Sprintf("unrecognized type %T", part))
	}
}
54625
func CalculateCertFingerprint(pemValue string) (string, error) {
	// The _ result below is not an error but the remaining PEM bytes.
	block, _ := pem.Decode([]byte(pemValue))
	if block == nil {
		return "", fmt.Errorf("no PEM-encoded data found")
	}

	if block.Type != "CERTIFICATE" {
		return "", fmt.Errorf("first PEM-block should be CERTIFICATE type")
	}

	hash := sha1.Sum(block.Bytes)
	return HexString(hash[:]), nil
}
299919
func GenSelfTLSFiles(hostname, certPath, keyPath string) (fingerprint string, err error) {
	cert, key, err := GenSelfTLS(hostname)
	if err != nil {
		return "", err
	}
	sig, err := CertFingerprint(cert)
	if err != nil {
		return "", fmt.Errorf("could not get SHA-256 fingerprint of certificate: %v", err)
	}
	if err := wkfs.WriteFile(certPath, cert, 0666); err != nil {
		return "", fmt.Errorf("failed to write self-signed TLS cert: %v", err)
	}
	if err := wkfs.WriteFile(keyPath, key, 0600); err != nil {
		return "", fmt.Errorf("failed to write self-signed TLS key: %v", err)
	}
	return sig, nil
}
1233773
func (fm *FingerprintManager) fingerprint(name string, f fingerprint.Fingerprint) (bool, error) {
	var response fingerprint.FingerprintResponse

	fm.nodeLock.Lock()
	request := &fingerprint.FingerprintRequest{Config: fm.getConfig(), Node: fm.node}
	err := f.Fingerprint(request, &response)
	fm.nodeLock.Unlock()

	if err != nil {
		return false, err
	}

	if node := fm.updateNodeAttributes(&response); node != nil {
		fm.setNode(node)
	}

	return response.Detected, nil
}
264454
func NewEnvAWSFingerprint(logger log.Logger) Fingerprint {
	f := &EnvAWSFingerprint{
		logger:  logger.Named("env_aws"),
		timeout: AwsMetadataTimeout,
	}
	return f
}
1121256
func (a *AuthorizationUpdateRequest) GetFingerprint() string {
	if a == nil || a.Fingerprint == nil {
		return ""
	}
	return *a.Fingerprint
}
152116
func (p PublicKey) Fingerprint() string {
	h := make([]byte, 20)
	d := sha3.NewShake256()
	_, _ = d.Write([]byte{0x42})
	_ = binary.Write(d, binary.LittleEndian, p.PubKeyAlgo)
	_, _ = d.Write(p.PublicKey[:])
	_, _ = d.Read(h)
	return fmt.Sprintf("%x", h)
}
1205579
func (fm *FingerprintManager) runFingerprint(f fingerprint.Fingerprint, period time.Duration, name string) {
	fm.logger.Debug("fingerprinting periodically", "fingerprinter", name, "period", period)

	timer := time.NewTimer(period)
	defer timer.Stop()

	for {
		select {
		case <-timer.C:
			timer.Reset(period)

			_, err := fm.fingerprint(name, f)
			if err != nil {
				fm.logger.Debug("error periodic fingerprinting", "error", err, "fingerprinter", name)
				continue
			}

		case <-fm.shutdownCh:
			return
		}
	}
}
480420
func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) {
	if !pk.CanSign() {
		return errors.InvalidArgumentError("public key cannot generate signatures")
	}

	signed.Write(sig.HashSuffix)
	hashBytes := signed.Sum(nil)

	if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
		return errors.SignatureError("hash tag doesn't match")
	}

	if pk.PubKeyAlgo != sig.PubKeyAlgo {
		return errors.InvalidArgumentError("public key and signature use different algorithms")
	}

	switch pk.PubKeyAlgo {
	case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
		rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey)
		err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes)
		if err != nil {
			return errors.SignatureError("RSA verification failure")
		}
		return nil
	case PubKeyAlgoDSA:
		dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey)
		// Need to truncate hashBytes to match FIPS 186-3 section 4.6.
		subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8
		if len(hashBytes) > subgroupSize {
			hashBytes = hashBytes[:subgroupSize]
		}
		if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) {
			return errors.SignatureError("DSA verification failure")
		}
		return nil
	case PubKeyAlgoECDSA:
		ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey)
		if !ecdsa.Verify(ecdsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.ECDSASigR.bytes), new(big.Int).SetBytes(sig.ECDSASigS.bytes)) {
			return errors.SignatureError("ECDSA verification failure")
		}
		return nil
	default:
		return errors.SignatureError("Unsupported public key algorithm used in signature")
	}
	panic("unreachable")
}
1142434
func VerifySignature(pubkey, hash, signature []byte) bool {
	return secp256k1.VerifySignature(pubkey, hash, signature)
}