<commit_before>// Copyright (c) 2014, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tao

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/hex"
	"errors"
	"io"
	"os"
	"runtime"
	"strconv"
	"strings"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/google/go-tpm/tpm"
	"github.com/jlmucb/cloudproxy/go/tao/auth"
)

// A TPMTao implements the Tao using a hardware TPM device.
type TPMTao struct {
	// tpmfile is the file through which TPMTao communicates with the TPM. E.g.,
	// on Linux, this is usually /dev/tpm0.
	tpmfile *os.File

	// srkAuth is the authenticator for the SRK. In most simple cases, it's 20
	// bytes of zeros. That value is called the "well-known authentictor"
	srkAuth [20]byte

	// aikHandle is an integer handle for an AIK held by the TPM. This key is
	// used for creating Quote values from the TPM.
	aikHandle tpm.Handle

	// verifier is a representation of the AIK that can be used to verify Quote
	// and Quote2 attestations.
	verifier *rsa.PublicKey

	// pcrCount is the number of PCRs in the TPM. The current go-tpm
	// implementation fixes this at 24.
	pcrCount uint32
	pcrNums  []int
	pcrVals  [][]byte

	// The name of the TPMTao is tpm(...K...) with extensions that represent the
	// PCR values (and maybe someday the locality).
	name auth.Prin

	// The current TPMTao code uses only locality 0, so this value is never set.
	locality byte
}

// This is a hack, but it is vital that we call FinalizeTPMTao() if any TPMTao
// was created, even if a goroutine panics, since the TPM will hold keys in
// memory apparently permanently, across reboots. The only way to clear the keys
// appears to be to reset the TPM entirely. There does not appear to be a clean
// way to ensure the finalizer is called if a goroutine panics. As a best
// effort, the last tpmTao created will be put into this global variable, and
// panic/recover in various goroutines can call the finalizer manually. There is
// no way to systematically get all goroutines, sadly.
var lastCreatedTPMTao *TPMTao

func ReleaseTPMResources() {
	if lastCreatedTPMTao != nil {
		FinalizeTPMTao(lastCreatedTPMTao)
	}
}

func RecoverTPMResources() {
	if r := recover(); r != nil {
		ReleaseTPMResources()
		panic(r)
	}
}

// NewTPMTao creates a new TPMTao and returns it under the Tao interface.
func NewTPMTao(tpmPath string, aikblob []byte, pcrNums []int) (Tao, error) {
	var err error
	tt := &TPMTao{pcrCount: 24}
	tt.tpmfile, err = os.OpenFile(tpmPath, os.O_RDWR, 0)
	if err != nil {
		return nil, err
	}

	// Make sure the TPMTao releases all its resources
	runtime.SetFinalizer(tt, FinalizeTPMTao)

	// For now, the SRK Auth value is all zero, which is the well-known value.
	// So, we don't set it here.
	// TODO(tmroeder): add support for general SRK auth values.

	// TODO(tmroeder): the current tpm implementation in go-tpm assumes 24 PCRs.
	// This is not true in general, and it should be generalized there then
	// changed here.
	tt.aikHandle, err = tpm.LoadKey2(tt.tpmfile, aikblob, tt.srkAuth[:])
	if err != nil {
		return nil, err
	}
	lastCreatedTPMTao = tt

	tt.verifier, err = tpm.UnmarshalRSAPublicKey(aikblob)
	if err != nil {
		return nil, err
	}

	// Get the pcr values for the PCR nums.
	tt.pcrNums = make([]int, len(pcrNums))
	for i, v := range pcrNums {
		tt.pcrNums[i] = v
	}

	tt.pcrVals, err = ReadPCRs(tt.tpmfile, pcrNums)
	if err != nil {
		return nil, err<commit_msg>flush all tpm keys on startup<commit_after>// Copyright (c) 2014, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tao

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/hex"
	"errors"
	"io"
	"os"
	"runtime"
	"strconv"
	"strings"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/google/go-tpm/tpm"
	"github.com/jlmucb/cloudproxy/go/tao/auth"
)

// A TPMTao implements the Tao using a hardware TPM device.
type TPMTao struct {
	// tpmfile is the file through which TPMTao communicates with the TPM. E.g.,
	// on Linux, this is usually /dev/tpm0.
	tpmfile *os.File

	// srkAuth is the authenticator for the SRK. In most simple cases, it's 20
	// bytes of zeros. That value is called the "well-known authentictor"
	srkAuth [20]byte

	// aikHandle is an integer handle for an AIK held by the TPM. This key is
	// used for creating Quote values from the TPM.
	aikHandle tpm.Handle

	// verifier is a representation of the AIK that can be used to verify Quote
	// and Quote2 attestations.
	verifier *rsa.PublicKey

	// pcrCount is the number of PCRs in the TPM. The current go-tpm
	// implementation fixes this at 24.
	pcrCount uint32
	pcrNums  []int
	pcrVals  [][]byte

	// The name of the TPMTao is tpm(...K...) with extensions that represent the
	// PCR values (and maybe someday the locality).
	name auth.Prin

	// The current TPMTao code uses only locality 0, so this value is never set.
	locality byte
}

// This is a hack, but it is vital that we call FinalizeTPMTao() if any TPMTao
// was created, even if a goroutine panics, since the TPM will hold keys in
// memory apparently permanently, across reboots. The only way to clear the keys
// appears to be to reset the TPM entirely. There does not appear to be a clean
// way to ensure the finalizer is called if a goroutine panics. As a best
// effort, the last tpmTao created will be put into this global variable, and
// panic/recover in various goroutines can call the finalizer manually. There is
// no way to systematically get all goroutines, sadly.
var lastCreatedTPMTao *TPMTao

func ReleaseTPMResources() {
	if lastCreatedTPMTao != nil {
		FinalizeTPMTao(lastCreatedTPMTao)
	}
}

func RecoverTPMResources() {
	if r := recover(); r != nil {
		ReleaseTPMResources()
		panic(r)
	}
}

// NewTPMTao creates a new TPMTao and returns it under the Tao interface.
func NewTPMTao(tpmPath string, aikblob []byte, pcrNums []int) (Tao, error) {
	var err error
	tt := &TPMTao{pcrCount: 24}
	tt.tpmfile, err = os.OpenFile(tpmPath, os.O_RDWR, 0)
	if err != nil {
		return nil, err
	}

	// Make sure the TPMTao releases all its resources
	runtime.SetFinalizer(tt, FinalizeTPMTao)

	// Flush all previously-loaded keys.
	handles, _ := tpm.GetKeys(tt.tpmfile)
	for _, h := range handles {
		h.CloseKey(tt.tpmfile)
	}

	// For now, the SRK Auth value is all zero, which is the well-known value.
	// So, we don't set it here.
	// TODO(tmroeder): add support for general SRK auth values.

	// TODO(tmroeder): the current tpm implementation in go-tpm assumes 24 PCRs.
	// This is not true in general, and it should be generalized there then
	// changed here.
	tt.aikHandle, err = tpm.LoadKey2(tt.tpmfile, aikblob, tt.srkAuth[:])
	if err != nil {
		return nil, err
	}
	lastCreatedTPMTao = tt

	tt.verifier, err = tpm.UnmarshalRSAPublicKey(aikblob)
	if err != nil {
		return nil, err
	}

	// Get the pcr values for the PCR nums.
	tt.pcrNums = make([]int, len(pcrNums))
	for i, v := range pcrNums {
		tt.pcrNums[i] = v
	}

	tt.pcrVals, err = ReadPCRs(tt.tpmfile, pcrNums)
	if err != nil {
		return nil, err
{'fraction_non_alphanumeric': 0.09564029313128804, 'fraction_numerical': 0.0069556576822754936, 'mean_word_length': 3.373709940249864, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7011808', 'n_tokens_mistral': 2828, 'n_tokens_neox': 2681, 'n_words': 1089}