diff --git a/lib/auth/auth_with_roles.go b/lib/auth/auth_with_roles.go index e5fdaa9dab8ce..4e463f6d7b8b1 100644 --- a/lib/auth/auth_with_roles.go +++ b/lib/auth/auth_with_roles.go @@ -3021,7 +3021,7 @@ func (a *ServerWithRoles) generateUserCerts(ctx context.Context, req proto.UserC if err != nil { return nil, trace.Wrap(err) } - if err := a.verifyUserDeviceForCertIssuance(req.Usage, readOnlyAuthPref.GetDeviceTrust()); err != nil { + if err := a.verifyUserDeviceForCertIssuance(ctx, req.Usage, readOnlyAuthPref.GetDeviceTrust()); err != nil { return nil, trace.Wrap(err) } @@ -3417,14 +3417,14 @@ func (a *ServerWithRoles) GetAccessRequestAllowedPromotions(ctx context.Context, // is not paramount to the access system itself, but it stops bad attempts from // progressing further and provides better feedback than other protocol-specific // failures. -func (a *ServerWithRoles) verifyUserDeviceForCertIssuance(usage proto.UserCertsRequest_CertUsage, dt *types.DeviceTrust) error { +func (a *ServerWithRoles) verifyUserDeviceForCertIssuance(ctx context.Context, usage proto.UserCertsRequest_CertUsage, dt *types.DeviceTrust) error { // Ignore App or WindowsDeskop requests, they do not support device trust. if usage == proto.UserCertsRequest_App || usage == proto.UserCertsRequest_WindowsDesktop { return nil } identity := a.context.Identity.GetIdentity() - return trace.Wrap(dtauthz.VerifyTLSUser(dt, identity)) + return trace.Wrap(dtauthz.VerifyTLSUser(ctx, dt, identity)) } func (a *ServerWithRoles) CreateResetPasswordToken(ctx context.Context, req authclient.CreateUserTokenRequest) (types.UserToken, error) { @@ -6813,7 +6813,7 @@ func (a *ServerWithRoles) enforceGlobalModeTrustedDevice(ctx context.Context) er return trace.Wrap(err) } - err = dtauthz.VerifyTLSUser(readOnlyAuthPref.GetDeviceTrust(), a.context.Identity.GetIdentity()) + err = dtauthz.VerifyTLSUser(ctx, readOnlyAuthPref.GetDeviceTrust(), a.context.Identity.GetIdentity()) return trace.Wrap(err) } diff --git a/lib/authz/permissions.go b/lib/authz/permissions.go index 66fb0c6a86eeb..e905d6d9d479f 100644 --- a/lib/authz/permissions.go +++ b/lib/authz/permissions.go @@ -443,7 +443,7 @@ func (a *authorizer) Authorize(ctx context.Context) (authCtx *Context, err error // Device Trust: authorize device extensions. if !a.disableGlobalDeviceMode { - if err := dtauthz.VerifyTLSUser(authPref.GetDeviceTrust(), authContext.Identity.GetIdentity()); err != nil { + if err := dtauthz.VerifyTLSUser(ctx, authPref.GetDeviceTrust(), authContext.Identity.GetIdentity()); err != nil { return nil, trace.Wrap(err) } } diff --git a/lib/devicetrust/authz/authz.go b/lib/devicetrust/authz/authz.go index 3bcc0ad3bf812..5f95b8af8eace 100644 --- a/lib/devicetrust/authz/authz.go +++ b/lib/devicetrust/authz/authz.go @@ -19,8 +19,10 @@ package authz import ( + "context" + "log/slog" + "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" "golang.org/x/crypto/ssh" "github.com/gravitational/teleport" @@ -45,8 +47,8 @@ func IsTLSDeviceVerified(ext *tlsca.DeviceExtensions) bool { // VerifyTLSUser verifies if the TLS identity has the required extensions to // fulfill the device trust configuration. -func VerifyTLSUser(dt *types.DeviceTrust, identity tlsca.Identity) error { - return verifyDeviceExtensions(dt, identity.Username, IsTLSDeviceVerified(&identity.DeviceExtensions)) +func VerifyTLSUser(ctx context.Context, dt *types.DeviceTrust, identity tlsca.Identity) error { + return verifyDeviceExtensions(ctx, dt, identity.Username, IsTLSDeviceVerified(&identity.DeviceExtensions)) } // IsSSHDeviceVerified returns true if cert contains all required device @@ -83,24 +85,22 @@ func HasDeviceTrustExtensions(extensions []string) bool { // VerifySSHUser verifies if the SSH certificate has the required extensions to // fulfill the device trust configuration. -func VerifySSHUser(dt *types.DeviceTrust, cert *ssh.Certificate) error { +func VerifySSHUser(ctx context.Context, dt *types.DeviceTrust, cert *ssh.Certificate) error { if cert == nil { return trace.BadParameter("cert required") } username := cert.KeyId - return verifyDeviceExtensions(dt, username, IsSSHDeviceVerified(cert)) + return verifyDeviceExtensions(ctx, dt, username, IsSSHDeviceVerified(cert)) } -func verifyDeviceExtensions(dt *types.DeviceTrust, username string, verified bool) error { +func verifyDeviceExtensions(ctx context.Context, dt *types.DeviceTrust, username string, verified bool) error { mode := dtconfig.GetEnforcementMode(dt) switch { case mode != constants.DeviceTrustModeRequired: return nil // OK, extensions not enforced. case !verified: - log. - WithField("User", username). - Debug("Device Trust: denied access for unidentified device") + slog.DebugContext(ctx, "Device Trust: denied access for unidentified device", "user", username) return trace.Wrap(ErrTrustedDeviceRequired) default: return nil diff --git a/lib/devicetrust/authz/authz_test.go b/lib/devicetrust/authz/authz_test.go index fa5a415508581..511a6be820d70 100644 --- a/lib/devicetrust/authz/authz_test.go +++ b/lib/devicetrust/authz/authz_test.go @@ -19,6 +19,7 @@ package authz_test import ( + "context" "testing" "github.com/gravitational/trace" @@ -131,7 +132,7 @@ func testIsDeviceVerified(t *testing.T, name string, fn func(ext *tlsca.DeviceEx func TestVerifyTLSUser(t *testing.T) { runVerifyUserTest(t, "VerifyTLSUser", func(dt *types.DeviceTrust, ext *tlsca.DeviceExtensions) error { - return authz.VerifyTLSUser(dt, tlsca.Identity{ + return authz.VerifyTLSUser(context.Background(), dt, tlsca.Identity{ Username: "llama", DeviceExtensions: *ext, }) @@ -140,7 +141,7 @@ func TestVerifyTLSUser(t *testing.T) { func TestVerifySSHUser(t *testing.T) { runVerifyUserTest(t, "VerifySSHUser", func(dt *types.DeviceTrust, ext *tlsca.DeviceExtensions) error { - return authz.VerifySSHUser(dt, &ssh.Certificate{ + return authz.VerifySSHUser(context.Background(), dt, &ssh.Certificate{ KeyId: "llama", Permissions: ssh.Permissions{ Extensions: map[string]string{ diff --git a/lib/devicetrust/enroll/enroll.go b/lib/devicetrust/enroll/enroll.go index b7e8a18c662eb..bdf3cea00c1b4 100644 --- a/lib/devicetrust/enroll/enroll.go +++ b/lib/devicetrust/enroll/enroll.go @@ -22,10 +22,10 @@ import ( "context" "errors" "io" + "log/slog" "github.com/gravitational/trace" "github.com/gravitational/trace/trail" - log "github.com/sirupsen/logrus" devicepb "github.com/gravitational/teleport/api/gen/proto/go/teleport/devicetrust/v1" "github.com/gravitational/teleport/lib/devicetrust" @@ -94,8 +94,7 @@ func (c *Ceremony) RunAdmin( rewordAccessDenied := func(err error, action string) error { if trace.IsAccessDenied(trail.FromGRPC(err)) { - log.WithError(err).Debug( - "Device Trust: Redacting access denied error with user-friendly message") + slog.DebugContext(ctx, "Device Trust: Redacting access denied error with user-friendly message", "error", err) return trace.AccessDenied( "User does not have permissions to %s. Contact your cluster device administrator.", action, @@ -115,9 +114,12 @@ func (c *Ceremony) RunAdmin( for _, dev := range findResp.Devices { if dev.OsType == osType { currentDev = dev - log.Debugf( - "Device Trust: Found device %q/%v, id=%q", - currentDev.AssetTag, devicetrust.FriendlyOSType(currentDev.OsType), currentDev.Id, + slog.DebugContext(ctx, "Device Trust: Found device", + slog.Group("device", + slog.String("asset_tag", currentDev.AssetTag), + slog.String("os", devicetrust.FriendlyOSType(currentDev.OsType)), + slog.String("id", currentDev.Id), + ), ) break } @@ -148,10 +150,13 @@ func (c *Ceremony) RunAdmin( if err != nil { return currentDev, outcome, trace.Wrap(rewordAccessDenied(err, "create device enrollment tokens")) } - log.Debugf( - "Device Trust: Created enrollment token for device %q/%s", - currentDev.AssetTag, - devicetrust.FriendlyOSType(currentDev.OsType)) + slog.DebugContext(ctx, "Device Trust: Created enrollment token for device", + slog.Group("device", + slog.String("asset_tag", currentDev.AssetTag), + slog.String("os", devicetrust.FriendlyOSType(currentDev.OsType)), + slog.String("id", currentDev.Id), + ), + ) } token := currentDev.EnrollToken.GetToken() diff --git a/lib/devicetrust/errors.go b/lib/devicetrust/errors.go index 4ca5e7c41107a..b2df583f57f14 100644 --- a/lib/devicetrust/errors.go +++ b/lib/devicetrust/errors.go @@ -19,11 +19,12 @@ package devicetrust import ( + "context" "errors" "io" + "log/slog" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -48,14 +49,14 @@ func HandleUnimplemented(err error) error { const notSupportedMsg = "device trust not supported by remote cluster" if errors.Is(err, io.EOF) { - log.Debug("Device Trust: interpreting EOF as an older Teleport cluster") + slog.DebugContext(context.Background(), "Device Trust: interpreting EOF as an older Teleport cluster") return trace.NotImplemented(notSupportedMsg) } for e := err; e != nil; { switch s, ok := status.FromError(e); { case ok && s.Code() == codes.Unimplemented: - log.WithError(err).Debug("Device Trust: interpreting gRPC Unimplemented as OSS or older Enterprise cluster") + slog.DebugContext(context.Background(), "Device Trust: interpreting gRPC Unimplemented as OSS or older Enterprise cluster", "error", err) return trace.NotImplemented(notSupportedMsg) case ok: return err // Unexpected status error. diff --git a/lib/devicetrust/native/api.go b/lib/devicetrust/native/api.go index 87cab17649979..ad13f1189da54 100644 --- a/lib/devicetrust/native/api.go +++ b/lib/devicetrust/native/api.go @@ -19,12 +19,13 @@ package native import ( + "context" + "log/slog" "runtime" "sync" "time" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" @@ -88,7 +89,7 @@ func readCachedDeviceDataUnderLock(mode CollectDataMode) (cdd *devicepb.DeviceCo return nil, false } - log.Debug("Device Trust: Using in-process cached device data") + slog.DebugContext(context.Background(), "Device Trust: Using in-process cached device data") cdd = proto.Clone(cachedDeviceData.value).(*devicepb.DeviceCollectedData) cdd.CollectTime = timestamppb.Now() return cdd, true diff --git a/lib/devicetrust/native/device_darwin.go b/lib/devicetrust/native/device_darwin.go index 9167b567aec9a..b3776ccd7e221 100644 --- a/lib/devicetrust/native/device_darwin.go +++ b/lib/devicetrust/native/device_darwin.go @@ -27,11 +27,13 @@ import "C" import ( "bytes" + "context" "crypto/sha256" "crypto/x509" "errors" "fmt" "io/fs" + "log/slog" "os/exec" "os/user" "strings" @@ -40,7 +42,6 @@ import ( "github.com/google/uuid" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" "google.golang.org/protobuf/types/known/timestamppb" devicepb "github.com/gravitational/teleport/api/gen/proto/go/teleport/devicetrust/v1" @@ -139,7 +140,7 @@ func collectDeviceData(_ CollectDataMode) (*devicepb.DeviceCollectedData, error) defer wg.Done() out, err := spec.fn() if err != nil { - log.WithError(err).Warnf("Device Trust: Failed to get %v", spec.desc) + slog.WarnContext(context.Background(), "Device Trust: Failed to get device details", "details", spec.desc, "error", err) return } *spec.out = out @@ -179,7 +180,7 @@ func getJamfBinaryVersion() (string, error) { // Jamf binary may not exist. This is alright. pathErr := &fs.PathError{} if errors.As(err, &pathErr) { - log.Debugf("Device Trust: Jamf binary not found: %q", pathErr.Path) + slog.DebugContext(context.Background(), "Device Trust: Jamf binary not found", "binary_path", pathErr.Path) return "", nil } diff --git a/lib/devicetrust/native/device_linux.go b/lib/devicetrust/native/device_linux.go index 63b8363c73393..b0771c1bc72b3 100644 --- a/lib/devicetrust/native/device_linux.go +++ b/lib/devicetrust/native/device_linux.go @@ -26,6 +26,7 @@ import ( "fmt" "io" "io/fs" + "log/slog" "os" "os/exec" "os/user" @@ -34,9 +35,9 @@ import ( "github.com/google/go-attestation/attest" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" "google.golang.org/protobuf/types/known/timestamppb" + "github.com/gravitational/teleport" devicepb "github.com/gravitational/teleport/api/gen/proto/go/teleport/devicetrust/v1" "github.com/gravitational/teleport/lib/linux" ) @@ -104,9 +105,10 @@ func rewriteTPMPermissionError(err error) error { if !errors.As(err, &pathErr) || pathErr.Path != "/dev/tpmrm0" { return err } - log. - WithError(err). - Debug("TPM: Replacing TPM permission error with a more friendly one") + slog.DebugContext(context.Background(), "Replacing TPM permission error with a more friendly one", + teleport.ComponentKey, "TPM", + "error", err, + ) return errors.New("" + "Failed to open the TPM device. " + @@ -141,7 +143,10 @@ func collectDeviceData(mode CollectDataMode) (*devicepb.DeviceCollectedData, err go func() { osRelease, err := cddFuncs.parseOSRelease() if err != nil { - log.WithError(err).Debug("TPM: Failed to parse /etc/os-release file") + slog.DebugContext(context.Background(), "Failed to parse /etc/os-release file", + teleport.ComponentKey, "TPM", + "error", err, + ) // err swallowed on purpose. osRelease = &linux.OSRelease{} @@ -187,26 +192,29 @@ func collectDeviceData(mode CollectDataMode) (*devicepb.DeviceCollectedData, err } func readDMIInfoAccordingToMode(mode CollectDataMode) (*linux.DMIInfo, error) { + ctx := context.Background() + logger := slog.With(teleport.ComponentKey, "TPM") + dmiInfo, err := cddFuncs.dmiInfoFromSysfs() if err == nil { return dmiInfo, nil } - log.WithError(err).Warn("TPM: Failed to read device model and/or serial numbers") + logger.WarnContext(ctx, "Failed to read device model and/or serial numbers", "error", err) if !errors.Is(err, fs.ErrPermission) { return dmiInfo, nil // original info } switch mode { case CollectedDataNeverEscalate, CollectedDataMaybeEscalate: - log.Debug("TPM: Reading cached DMI info") + logger.DebugContext(ctx, "Reading cached DMI info") dmiCached, err := cddFuncs.readDMIInfoCached() if err == nil { return dmiCached, nil // successful cache hit } - log.WithError(err).Debug("TPM: Failed to read cached DMI info") + logger.DebugContext(ctx, "Failed to read cached DMI info", "error", err) if mode == CollectedDataNeverEscalate { return dmiInfo, nil // original info } @@ -214,7 +222,7 @@ func readDMIInfoAccordingToMode(mode CollectDataMode) (*linux.DMIInfo, error) { fallthrough case CollectedDataAlwaysEscalate: - log.Debug("TPM: Running escalated `tsh device dmi-info`") + logger.DebugContext(ctx, "Running escalated `tsh device dmi-info`") dmiInfo, err = cddFuncs.readDMIInfoEscalated() if err != nil { @@ -222,7 +230,7 @@ func readDMIInfoAccordingToMode(mode CollectDataMode) (*linux.DMIInfo, error) { } if err := cddFuncs.saveDMIInfoToCache(dmiInfo); err != nil { - log.WithError(err).Warn("TPM: Failed to write DMI cache") + logger.WarnContext(ctx, "Failed to write DMI cache", "error", err) // err swallowed on purpose. } } @@ -250,9 +258,7 @@ func readDMIInfoCached() (*linux.DMIInfo, error) { return nil, trace.Wrap(err) } if dec.More() { - log. - WithField("Path", path). - Warn("DMI cache file contains multiple JSON entries, only one expected") + slog.WarnContext(context.Background(), "DMI cache file contains multiple JSON entries, only one expected", "path", path) // Warn but keep going. } @@ -320,7 +326,7 @@ func saveDMIInfoToCache(dmiInfo *linux.DMIInfo) error { if err := f.Close(); err != nil { return trace.Wrap(err, "closing dmi.json after write") } - log.Debug("TPM: Saved DMI information to local cache") + slog.DebugContext(context.Background(), "Saved DMI information to local cache", teleport.ComponentKey, "TPM") return nil } diff --git a/lib/devicetrust/native/device_linux_test.go b/lib/devicetrust/native/device_linux_test.go index 6f1f545437ccb..7848c6a05767b 100644 --- a/lib/devicetrust/native/device_linux_test.go +++ b/lib/devicetrust/native/device_linux_test.go @@ -28,7 +28,6 @@ import ( "testing" "github.com/google/go-cmp/cmp" - log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" @@ -39,9 +38,6 @@ import ( ) func TestCollectDeviceData_linux(t *testing.T) { - // Silence logging for tests. - log.SetLevel(log.PanicLevel) - // Do not cache data during testing. skipCacheBefore := cachedDeviceData.skipCache cachedDeviceData.skipCache = true diff --git a/lib/devicetrust/native/device_windows.go b/lib/devicetrust/native/device_windows.go index b0a871c18a994..575e238af5623 100644 --- a/lib/devicetrust/native/device_windows.go +++ b/lib/devicetrust/native/device_windows.go @@ -19,17 +19,19 @@ package native import ( + "context" "encoding/base64" "errors" "fmt" + "log/slog" "os" "os/user" "strconv" "time" "github.com/google/go-attestation/attest" + "github.com/gravitational/teleport" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" "github.com/yusufpapurcu/wmi" "golang.org/x/sync/errgroup" "golang.org/x/sys/windows" @@ -166,7 +168,10 @@ func getDeviceBaseBoardSerial() (string, error) { } func collectDeviceData(_ CollectDataMode) (*devicepb.DeviceCollectedData, error) { - log.Debug("TPM: Collecting device data.") + ctx := context.Background() + logger := slog.With(teleport.ComponentKey, "TPM") + + logger.DebugContext(ctx, "Collecting device data") var g errgroup.Group const groupLimit = 4 // arbitrary @@ -188,7 +193,7 @@ func collectDeviceData(_ CollectDataMode) (*devicepb.DeviceCollectedData, error) g.Go(func() error { val, err := spec.fn() if err != nil { - log.WithError(err).Debugf("TPM: Failed to fetch %v", spec.desc) + logger.DebugContext(ctx, "Failed to fetch device details", "details", spec.desc, "error", err) return nil // Swallowed on purpose. } @@ -224,9 +229,7 @@ func collectDeviceData(_ CollectDataMode) (*devicepb.DeviceCollectedData, error) BaseBoardSerialNumber: baseBoardSerial, ReportedAssetTag: reportedAssetTag, } - log.WithField( - "device_collected_data", dcd, - ).Debug("TPM: Device data collected.") + logger.DebugContext(ctx, "Device data collected", "device_collected_data", dcd) return dcd, nil } @@ -270,7 +273,7 @@ func activateCredentialInElevatedChild( params = append(params, "--debug") } - log.Debug("Starting elevated process.") + slog.DebugContext(context.Background(), "Starting elevated process.") // https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecutew err = windowsexec.RunAsAndWait( exe, @@ -286,7 +289,7 @@ func activateCredentialInElevatedChild( // it. defer func() { if err := os.Remove(credActivationPath); err != nil { - log.WithError(err).Debug("Failed to clean up credential activation result") + slog.DebugContext(context.Background(), "Failed to clean up credential activation result", "error", err) } }() diff --git a/lib/devicetrust/native/tpm_device.go b/lib/devicetrust/native/tpm_device.go index 112647f456c90..cbfbc1b51012e 100644 --- a/lib/devicetrust/native/tpm_device.go +++ b/lib/devicetrust/native/tpm_device.go @@ -21,18 +21,20 @@ package native import ( + "context" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/base64" "fmt" + "log/slog" "math/big" "os" "github.com/google/go-attestation/attest" "github.com/gravitational/trace" - log "github.com/sirupsen/logrus" + "github.com/gravitational/teleport" devicepb "github.com/gravitational/teleport/api/gen/proto/go/teleport/devicetrust/v1" "github.com/gravitational/teleport/lib/devicetrust" ) @@ -121,6 +123,8 @@ func createAndSaveAK( } func (d *tpmDevice) enrollDeviceInit() (*devicepb.EnrollDeviceInit, error) { + ctx := context.Background() + logger := slog.With(teleport.ComponentKey, "TPM") stateDir, err := setupDeviceStateDir(userDirFunc) if err != nil { return nil, trace.Wrap(err, "setting up device state directory") @@ -134,7 +138,7 @@ func (d *tpmDevice) enrollDeviceInit() (*devicepb.EnrollDeviceInit, error) { } defer func() { if err := tpm.Close(); err != nil { - log.WithError(err).Debug("TPM: Failed to close TPM.") + logger.DebugContext(ctx, "Failed to close TPM", "error", err) } }() @@ -145,13 +149,13 @@ func (d *tpmDevice) enrollDeviceInit() (*devicepb.EnrollDeviceInit, error) { if !trace.IsNotFound(err) { return nil, trace.Wrap(err, "loading ak") } - log.Debug("TPM: No existing AK was found on disk, an AK will be created.") + logger.DebugContext(ctx, "No existing AK was found on disk, an AK will be created") ak, err = createAndSaveAK(tpm, stateDir.attestationKeyPath) if err != nil { return nil, trace.Wrap(err, "creating ak") } } else { - log.Debug("TPM: Existing AK was found on disk, it will be reused.") + logger.DebugContext(ctx, "Existing AK was found on disk, it will be reused") } defer ak.Close(tpm) @@ -245,7 +249,10 @@ func (d *tpmDevice) getDeviceCredential() (*devicepb.DeviceCredential, error) { } defer func() { if err := tpm.Close(); err != nil { - log.WithError(err).Debug("TPM: Failed to close TPM.") + slog.DebugContext(context.Background(), "Failed to close TPM", + teleport.ComponentKey, "TPM", + "error", err, + ) } }() @@ -270,6 +277,9 @@ func (d *tpmDevice) solveTPMEnrollChallenge( challenge *devicepb.TPMEnrollChallenge, debug bool, ) (*devicepb.TPMEnrollChallengeResponse, error) { + ctx := context.Background() + logger := slog.With(teleport.ComponentKey, "TPM") + stateDir, err := setupDeviceStateDir(userDirFunc) if err != nil { return nil, trace.Wrap(err, "setting up device state directory") @@ -283,7 +293,7 @@ func (d *tpmDevice) solveTPMEnrollChallenge( } defer func() { if err := tpm.Close(); err != nil { - log.WithError(err).Debug("TPM: Failed to close TPM.") + logger.DebugContext(ctx, "Failed to close TPM", "error", err) } }() @@ -302,7 +312,7 @@ func (d *tpmDevice) solveTPMEnrollChallenge( // First perform the credential activation challenge provided by the // auth server. - log.Debug("TPM: Activating credential.") + logger.DebugContext(ctx, "Activating credential") encryptedCredential := devicetrust.EncryptedCredentialFromProto( challenge.EncryptedCredential, ) @@ -318,7 +328,7 @@ func (d *tpmDevice) solveTPMEnrollChallenge( var activationSolution []byte if elevated { - log.Debug("TPM: Detected current process is elevated. Will run credential activation in current process.") + logger.DebugContext(ctx, "Detected current process is elevated. Will run credential activation in current process") // If we are running with elevated privileges, we can just complete the // credential activation here. activationSolution, err = ak.ActivateCredential( @@ -341,7 +351,7 @@ func (d *tpmDevice) solveTPMEnrollChallenge( fmt.Fprintln(os.Stderr, "Successfully completed credential activation in elevated process.") } - log.Debug("TPM: Enrollment challenge completed.") + logger.DebugContext(ctx, "Enrollment challenge completed.") return &devicepb.TPMEnrollChallengeResponse{ Solution: activationSolution, PlatformParameters: devicetrust.PlatformParametersToProto( @@ -352,7 +362,10 @@ func (d *tpmDevice) solveTPMEnrollChallenge( //nolint:unused // Used by Windows builds. func (d *tpmDevice) handleTPMActivateCredential(encryptedCredential, encryptedCredentialSecret string) error { - log.Debug("Performing credential activation.") + ctx := context.Background() + logger := slog.With(teleport.ComponentKey, "TPM") + + logger.DebugContext(ctx, "Performing credential activation") // The two input parameters are base64 encoded, so decode them. credentialBytes, err := base64.StdEncoding.DecodeString(encryptedCredential) if err != nil { @@ -376,7 +389,7 @@ func (d *tpmDevice) handleTPMActivateCredential(encryptedCredential, encryptedCr } defer func() { if err := tpm.Close(); err != nil { - log.WithError(err).Debug("TPM: Failed to close TPM.") + logger.DebugContext(ctx, "Failed to close TPM", "error", err) } }() @@ -398,7 +411,7 @@ func (d *tpmDevice) handleTPMActivateCredential(encryptedCredential, encryptedCr return trace.Wrap(err, "activating credential with challenge") } - log.Debug("Completed credential activation. Returning result to original process.") + logger.DebugContext(ctx, "Completed credential activation, returning result to original process") return trace.Wrap( os.WriteFile(stateDir.credentialActivationPath, solution, 0600), ) @@ -407,6 +420,9 @@ func (d *tpmDevice) handleTPMActivateCredential(encryptedCredential, encryptedCr func (d *tpmDevice) solveTPMAuthnDeviceChallenge( challenge *devicepb.TPMAuthenticateDeviceChallenge, ) (*devicepb.TPMAuthenticateDeviceChallengeResponse, error) { + ctx := context.Background() + logger := slog.With(teleport.ComponentKey, "TPM") + stateDir, err := setupDeviceStateDir(userDirFunc) if err != nil { return nil, trace.Wrap(err, "setting up device state directory") @@ -420,7 +436,7 @@ func (d *tpmDevice) solveTPMAuthnDeviceChallenge( } defer func() { if err := tpm.Close(); err != nil { - log.WithError(err).Debug("TPM: Failed to close TPM") + logger.DebugContext(ctx, "Failed to close TPM", "error", err) } }() @@ -437,7 +453,7 @@ func (d *tpmDevice) solveTPMAuthnDeviceChallenge( return nil, trace.Wrap(err) } - log.Debug("TPM: Authenticate device challenge completed.") + logger.DebugContext(ctx, "Authenticate device challenge completed") return &devicepb.TPMAuthenticateDeviceChallengeResponse{ PlatformParameters: devicetrust.PlatformParametersToProto( platformsParams, @@ -446,9 +462,12 @@ func (d *tpmDevice) solveTPMAuthnDeviceChallenge( } func attestPlatform(tpm *attest.TPM, ak *attest.AK, nonce []byte) (*attest.PlatformParameters, error) { + ctx := context.Background() + logger := slog.With(teleport.ComponentKey, "TPM") + config := &attest.PlatformAttestConfig{} - log.Debug("TPM: Performing platform attestation.") + logger.DebugContext(ctx, "Performing platform attestation") platformsParams, err := tpm.AttestPlatform(ak, nonce, config) if err == nil { return platformsParams, nil @@ -458,9 +477,7 @@ func attestPlatform(tpm *attest.TPM, ak *attest.AK, nonce []byte) (*attest.Platf // errors.Is(err, fs.ErrPermission), but the go-attestation version at time of // writing (v0.5.0) doesn't wrap the underlying error. // This is a common occurrence for Linux devices. - log. - WithError(err). - Debug("TPM: Platform attestation failed with permission error, attempting without event log") + logger.DebugContext(ctx, "Platform attestation failed with permission error, attempting without event log", "error", err) config.EventLog = []byte{} platformsParams, err = tpm.AttestPlatform(ak, nonce, config) return platformsParams, trace.Wrap(err, "attesting platform") diff --git a/lib/srv/session_control.go b/lib/srv/session_control.go index 748aa111062eb..536cfd8948ff2 100644 --- a/lib/srv/session_control.go +++ b/lib/srv/session_control.go @@ -236,7 +236,7 @@ func (s *SessionController) AcquireSessionContext(ctx context.Context, identity } // Device Trust: authorize device extensions. - if err := dtauthz.VerifySSHUser(authPref.GetDeviceTrust(), identity.Certificate); err != nil { + if err := dtauthz.VerifySSHUser(ctx, authPref.GetDeviceTrust(), identity.Certificate); err != nil { return ctx, trace.Wrap(err) }