Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add machinery to do client-side RDP license caching #47634

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions lib/auth/storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ package storage
import (
"context"
"encoding/json"
"strconv"
"strings"
"time"

"github.com/coreos/go-semver/semver"
"github.com/gravitational/trace"
Expand Down Expand Up @@ -233,6 +235,31 @@ func (p *ProcessStorage) WriteTeleportVersion(ctx context.Context, version *semv
return nil
}

func (p *ProcessStorage) rdpLicenseKey(majorVersion, minorVersion uint16, issuer, company, productID string) backend.Key {
return backend.NewKey("rdplicense", issuer, strconv.Itoa(int(majorVersion)), strconv.Itoa(int(minorVersion)), company, productID)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we ever going to list the licenses? If so, are we more likely to want to list them by issuer major minor company productid, or some other order?

}

// WriteRDPLicense writes an RDP license to local storage.
func (p *ProcessStorage) WriteRDPLicense(ctx context.Context, majorVersion, minorVersion uint16, issuer, company, productID string, license []byte) error {
zmb3 marked this conversation as resolved.
Show resolved Hide resolved
item := backend.Item{
Key: p.rdpLicenseKey(majorVersion, minorVersion, issuer, company, productID),
Value: license,
Expires: p.BackendStorage.Clock().Now().Add(28 * 24 * time.Hour),
}
_, err := p.stateStorage.Put(ctx, item)
return trace.Wrap(err)
}

// ReadRDPLicense reads a previously obtained license from storage.
func (p *ProcessStorage) ReadRDPLicense(ctx context.Context, majorVersion, minorVersion uint16, issuer, company, productID string) ([]byte, error) {
item, err := p.stateStorage.Get(ctx, p.rdpLicenseKey(majorVersion, minorVersion, issuer, company, productID))
if err != nil {
return nil, trace.Wrap(err)
}

return item.Value, nil
}

// ReadLocalIdentity reads, parses and returns the given pub/pri key + cert from the
// key storage (dataDir).
func ReadLocalIdentity(dataDir string, id state.IdentityID) (*state.Identity, error) {
Expand Down
2 changes: 2 additions & 0 deletions lib/auth/webauthnwin/webauthn_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ func isUVPlatformAuthenticatorAvailable() (bool, error) {

// bytesFromCBytes gets slice of bytes from C type and copies it to new slice
// so that it won't interfere when main objects is free.
//
// TODO(codingllama): can we use C.GoBytes() here instead?
func bytesFromCBytes(size uint32, p *byte) []byte {
if p == nil {
return nil
Expand Down
1 change: 1 addition & 0 deletions lib/service/desktop.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ func (process *TeleportProcess) initWindowsDesktopServiceRegistered(logger *slog

srv, err := desktop.NewWindowsService(desktop.WindowsServiceConfig{
DataDir: process.Config.DataDir,
LicenseStore: process.storage,
Logger: process.logger.With(teleport.ComponentKey, teleport.Component(teleport.ComponentWindowsDesktop, process.id)),
Clock: process.Clock,
Authorizer: authorizer,
Expand Down
94 changes: 94 additions & 0 deletions lib/srv/desktop/rdp/rdpclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -743,6 +743,62 @@ func toClient(handle C.uintptr_t) (value *Client, err error) {
return cgo.Handle(handle).Value().(*Client), nil
}

//export cgo_read_rdp_license
func cgo_read_rdp_license(handle C.uintptr_t, req *C.CGOLicenseRequest, data_out **C.uint8_t, len_out *C.size_t) C.CGOErrCode {
*data_out = nil
*len_out = 0

client, err := toClient(handle)
if err != nil {
return C.ErrCodeFailure
}

issuer := C.GoString(req.issuer)
company := C.GoString(req.company)
productID := C.GoString(req.product_id)
Comment on lines +748 to +758
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are currently recovering against panics in toClient; while that's pretty gross, should we be consistent and also check that req and the out pointers are not nil?


license, err := client.readRDPLicense(
uint16(req.major_version), uint16(req.minor_version),
issuer, company, productID)
if err != nil {
return C.ErrCodeFailure
}

// in this case, we expect the caller to use cgo_free_rdp_license
// when the data is no longer needed
*data_out = (*C.uint8_t)(C.CBytes(license))
*len_out = C.size_t(len(license))
return C.ErrCodeSuccess
}

//export cgo_free_rdp_license
func cgo_free_rdp_license(p unsafe.Pointer) {
C.free(p)
}

//export cgo_write_rdp_license
func cgo_write_rdp_license(handle C.uintptr_t, req *C.CGOLicenseRequest, data *C.uint8_t, length C.size_t) C.CGOErrCode {
client, err := toClient(handle)
if err != nil {
return C.ErrCodeFailure
}

issuer := C.GoString(req.issuer)
company := C.GoString(req.company)
productID := C.GoString(req.product_id)

licenseData := C.GoBytes(unsafe.Pointer(data), C.int(length))

err = client.writeRDPLicense(
uint16(req.major_version), uint16(req.minor_version),
issuer, company, productID, licenseData)
if err != nil {
return C.ErrCodeFailure
}

return C.ErrCodeSuccess
}

//export cgo_handle_fastpath_pdu
func cgo_handle_fastpath_pdu(handle C.uintptr_t, data *C.uint8_t, length C.uint32_t) C.CGOErrCode {
goData := asRustBackedSlice(data, int(length))
Expand All @@ -753,6 +809,44 @@ func cgo_handle_fastpath_pdu(handle C.uintptr_t, data *C.uint8_t, length C.uint3
return client.handleRDPFastPathPDU(goData)
}

func (c *Client) readRDPLicense(majorVersion, minorVersion uint16, issuer, company, productID string) ([]byte, error) {
log := c.cfg.Logger.With(
"issuer", issuer,
"company", company,
"version", fmt.Sprintf("%d.%d", majorVersion, minorVersion),
"product", productID,
)

license, err := c.cfg.LicenseStore.ReadRDPLicense(context.Background(), majorVersion, minorVersion, issuer, company, productID)
switch {
case trace.IsNotFound(err):
log.InfoContext(context.Background(), "existing RDP license not found")
case err != nil:
log.ErrorContext(context.Background(), "could not look up existing RDP license", "error", err)
case len(license) > 0:
log.InfoContext(context.Background(), "found existing RDP license")
Comment on lines +826 to +827
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what should happen in case of err == nil && len(license) == 0?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's not something I've commonly seen in Go code. It's generally safe to assume that a nil error means we're returning valid data.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So why use additional case here? can we skip it and simply log after switch?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I follow?

I want to be able to tell from the logs if:

  1. We know there wasn't an existing license.
  2. We know there was an existing license.
  3. We don't know if there was a license or not because we encountered an error.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now the switch is not exhaustive, case where err == nil and len(license) == 0 will log nothing.
So, we either don't care about the length (we assume it's >0 when err==nil) and we can skip the length check (by either returning early in case of errors above and logging happy path outside of switch or changing last case to default) or we do care and should log something different in that case

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough, we can change the last case to a default case instead.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could error upon trying to write an empty license (if that's ever plausible) and treat an empty license as a not found error, too.

For what it's worth we seem to always avoid writing items with a blank value in the backend - nothing bad should happen, but...

}

return license, trace.Wrap(err)
}

func (c *Client) writeRDPLicense(majorVersion, minorVersion uint16, issuer, company, productID string, license []byte) error {
c.cfg.Logger.InfoContext(context.Background(), "writing RDP license to storage",
"issuer", issuer,
"company", company,
"version", fmt.Sprintf("%d.%d", majorVersion, minorVersion),
"product", productID,
)
return trace.Wrap(c.cfg.LicenseStore.WriteRDPLicense(
context.Background(),
majorVersion, minorVersion,
issuer,
company,
productID,
license,
))
}

func (c *Client) handleRDPFastPathPDU(data []byte) C.CGOErrCode {
// Notify the input forwarding goroutine that we're ready for input.
// Input can only be sent after connection was established, which we infer
Expand Down
9 changes: 9 additions & 0 deletions lib/srv/desktop/rdp/rdpclient/client_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,20 @@ import (
"github.com/gravitational/teleport/lib/srv/desktop/tdp"
)

// LicenseStore implements client-side license storage for Microsoft
// Remote Desktop Services (RDS) licenses.
type LicenseStore interface {
WriteRDPLicense(ctx context.Context, majorVersion, minorVersion uint16, issuer, company, productID string, license []byte) error
ReadRDPLicense(ctx context.Context, majorVersion, minorVersion uint16, issuer, company, productID string) ([]byte, error)
}

// Config for creating a new Client.
type Config struct {
// Addr is the network address of the RDP server, in the form host:port.
Addr string

LicenseStore LicenseStore

// UserCertGenerator generates user certificates for RDP authentication.
GenerateUserCert GenerateUserCertFn
CertTTL time.Duration
Expand Down
21 changes: 21 additions & 0 deletions lib/srv/desktop/rdp/rdpclient/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,15 @@ pub unsafe extern "C" fn client_write_screen_resize(
)
}

#[repr(C)]
pub struct CGOLicenseRequest {
major_version: u16,
minor_version: u16,
issuer: *const c_char,
company: *const c_char,
product_id: *const c_char,
}

#[repr(C)]
pub struct CGOConnectParams {
ad: bool,
Expand Down Expand Up @@ -705,6 +714,18 @@ pub type CGOSharedDirectoryTruncateResponse = SharedDirectoryTruncateResponse;
// These functions are defined on the Go side.
// Look for functions with '//export funcname' comments.
extern "C" {
fn cgo_read_rdp_license(
cgo_handle: CgoHandle,
req: *mut CGOLicenseRequest,
data_out: *mut *mut u8,
len_out: *mut usize,
) -> CGOErrCode;
fn cgo_write_rdp_license(
cgo_handle: CgoHandle,
req: *mut CGOLicenseRequest,
data: *mut u8,
length: usize,
) -> CGOErrCode;
fn cgo_handle_remote_copy(cgo_handle: CgoHandle, data: *mut u8, len: u32) -> CGOErrCode;
fn cgo_handle_fastpath_pdu(cgo_handle: CgoHandle, data: *mut u8, len: u32) -> CGOErrCode;
fn cgo_handle_rdp_connection_activated(
Expand Down
8 changes: 5 additions & 3 deletions lib/srv/desktop/windows_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,9 @@ type WindowsServiceConfig struct {
// Logger is the logger for the service.
Logger *slog.Logger
// Clock provides current time.
Clock clockwork.Clock
DataDir string
Clock clockwork.Clock
DataDir string
LicenseStore rdpclient.LicenseStore
// Authorizer is used to authorize requests.
Authorizer authz.Authorizer
// LockWatcher is used to monitor for new locks.
Expand Down Expand Up @@ -906,7 +907,8 @@ func (s *WindowsService) connectRDP(ctx context.Context, log *slog.Logger, tdpCo

//nolint:staticcheck // SA4023. False positive, depends on build tags.
rdpc, err := rdpclient.New(rdpclient.Config{
Logger: log,
Logger: log,
LicenseStore: s.cfg.LicenseStore,
GenerateUserCert: func(ctx context.Context, username string, ttl time.Duration) (certDER, keyDER []byte, err error) {
return s.generateUserCert(ctx, username, ttl, desktop, createUsers, groups)
},
Expand Down
Loading