Add test to ensure signature is added

This commit is contained in:
Andrew Heberle 2025-08-31 15:53:53 +08:00
parent b291ad1f82
commit d056cffe65
7 changed files with 193 additions and 16 deletions

View File

@ -3,17 +3,18 @@ package protocol
import (
"context"
"errors"
"github.com/bolkedebruin/rdpgw/cmd/rdpgw/identity"
"github.com/bolkedebruin/rdpgw/cmd/rdpgw/transport"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/patrickmn/go-cache"
"log"
"net"
"net/http"
"reflect"
"syscall"
"time"
"github.com/bolkedebruin/rdpgw/cmd/rdpgw/identity"
"github.com/bolkedebruin/rdpgw/cmd/rdpgw/transport"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/patrickmn/go-cache"
)
const (
@ -140,7 +141,7 @@ func (g *Gateway) setSendReceiveBuffers(conn net.Conn) error {
if !ptrSysFd.IsValid() {
return errors.New("cannot find Sysfd field")
}
fd := int(ptrSysFd.Int())
fd := int64ToFd(ptrSysFd.Int())
if g.ReceiveBuf > 0 {
err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, g.ReceiveBuf)

View File

@ -0,0 +1,6 @@
package protocol
// the fd arg to syscall.SetsockoptInt on Linix is of type int
func int64ToFd(n int64) int {
return int(n)
}

View File

@ -0,0 +1,10 @@
package protocol
import (
"syscall"
)
// the fd arg to syscall.SetsockoptInt on Windows is of type syscall.Handle
func int64ToFd(n int64) syscall.Handle {
return syscall.Handle(n)
}

View File

@ -4,12 +4,13 @@ import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"net/http"
"time"
"github.com/bolkedebruin/rdpgw/cmd/rdpgw/identity"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/patrickmn/go-cache"
"golang.org/x/oauth2"
"net/http"
"time"
)
const (
@ -91,7 +92,7 @@ func (h *OIDC) HandleCallback(w http.ResponseWriter, r *http.Request) {
id.SetAuthTime(time.Now())
id.SetAttribute(identity.AttrAccessToken, oauth2Token.AccessToken)
if err = SaveSessionIdentity(r, w, id); err != nil {
if err := SaveSessionIdentity(r, w, id); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}

View File

@ -79,7 +79,7 @@ func (c *Config) NewHandler() *Handler {
// set up RDP signer if config values are set
if c.RdpSigningCert != "" && c.RdpSigningKey != "" {
signer, err := rdpsign.NewSigner(c.RdpSigningCert, c.RdpSigningKey)
signer, err := rdpsign.New(c.RdpSigningCert, c.RdpSigningKey)
if err != nil {
log.Fatal("Could not set up RDP signer", err)
}
@ -178,7 +178,7 @@ func (h *Handler) HandleDownload(w http.ResponseWriter, r *http.Request) {
render := user
if opts.UsernameTemplate != "" {
render = fmt.Sprintf(h.rdpOpts.UsernameTemplate)
render = fmt.Sprint(h.rdpOpts.UsernameTemplate)
render = strings.Replace(render, "{{ username }}", user, 1)
if h.rdpOpts.UsernameTemplate == render {
log.Printf("Invalid username template. %s == %s", h.rdpOpts.UsernameTemplate, user)
@ -252,7 +252,7 @@ func (h *Handler) HandleDownload(w http.ResponseWriter, r *http.Request) {
rdpContent := d.String()
// sign rdp content
signedContent, err := h.rdpSigner.SignRdp(rdpContent)
signedContent, err := h.rdpSigner.Sign(rdpContent)
if err != nil {
log.Printf("Could not sign RDP file due to %s", err)
http.Error(w, errors.New("could not sign RDP file").Error(), http.StatusInternalServerError)

View File

@ -2,15 +2,25 @@ package web
import (
"context"
"github.com/bolkedebruin/rdpgw/cmd/rdpgw/identity"
"github.com/bolkedebruin/rdpgw/cmd/rdpgw/rdp"
"github.com/bolkedebruin/rdpgw/cmd/rdpgw/security"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
"github.com/andrewheberle/rdpsign"
"github.com/bolkedebruin/rdpgw/cmd/rdpgw/identity"
"github.com/bolkedebruin/rdpgw/cmd/rdpgw/rdp"
"github.com/bolkedebruin/rdpgw/cmd/rdpgw/security"
"github.com/spf13/afero"
)
const (
@ -172,6 +182,89 @@ func TestHandler_HandleDownload(t *testing.T) {
}
func TestHandler_HandleSignedDownload(t *testing.T) {
req, err := http.NewRequest("GET", "/connect", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
id := identity.NewUser()
id.SetUserName(testuser)
id.SetAuthenticated(true)
req = identity.AddToRequestCtx(id, req)
ctx := req.Context()
u, _ := url.Parse(gateway)
c := Config{
HostSelection: "roundrobin",
Hosts: hosts,
PAATokenGenerator: paaTokenMock,
GatewayAddress: u,
RdpOpts: RdpOpts{SplitUserDomain: true},
}
h := c.NewHandler()
// set up rdp signer
fs := afero.NewMemMapFs()
if err := genKeypair(fs); err != nil {
t.Errorf("could not generate key pair for testing: %s", err)
}
signer, err := rdpsign.New("test.crt", "test.key", rdpsign.WithFs(fs))
if err != nil {
t.Errorf("could not create *rdpsign.Signer for testing: %s", err)
}
h.rdpSigner = signer
hh := http.HandlerFunc(h.HandleDownload)
hh.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
if ctype := rr.Header().Get("Content-Type"); ctype != "application/x-rdp" {
t.Errorf("content type header does not match: got %v want %v",
ctype, "application/json")
}
if cdisp := rr.Header().Get("Content-Disposition"); cdisp == "" {
t.Errorf("content disposition is nil")
}
data := rdpToMap(strings.Split(rr.Body.String(), rdp.CRLF))
if data["username"] != testuser {
t.Errorf("username key in rdp does not match: got %v want %v", data["username"], testuser)
}
if data["gatewayhostname"] != u.Host {
t.Errorf("gatewayhostname key in rdp does not match: got %v want %v", data["gatewayhostname"], u.Host)
}
if token, _ := paaTokenMock(ctx, testuser, data["full address"]); token != data["gatewayaccesstoken"] {
t.Errorf("gatewayaccesstoken key in rdp does not match username_full address: got %v want %v",
data["gatewayaccesstoken"], token)
}
if !contains(data["full address"], hosts) {
t.Errorf("full address key in rdp is not in allowed hosts list: go %v want in %v",
data["full address"], hosts)
}
signscopeWant := "GatewayHostname,Full Address,GatewayCredentialsSource,GatewayProfileUsageMethod,GatewayUsageMethod,Alternate Full Address"
if data["signscope"] != signscopeWant {
t.Errorf("signscope key in rdp does not match: got %v want %v", data["signscope"], signscopeWant)
}
if _, found := data["signature"]; !found {
t.Errorf("no signature found in rdp")
}
}
func TestHandler_HandleDownloadWithRdpTemplate(t *testing.T) {
f, err := os.CreateTemp("", "rdp")
if err != nil {
@ -233,3 +326,68 @@ func rdpToMap(rdp []string) map[string]string {
return ret
}
func genKeypair(fs afero.Fs) error {
// generate private key
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
// convert to DER
der, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return err
}
// encode DER private key as PEM
if err := func() error {
f, err := fs.Create("test.key")
if err != nil {
return err
}
defer f.Close()
return pem.Encode(f, &pem.Block{
Type: "PRIVATE KEY",
Bytes: der,
})
}(); err != nil {
return err
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"Example Organization"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Minute * 10),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
if err != nil {
return err
}
// encode cert as PEM
if err := func() error {
f, err := fs.Create("test.crt")
if err != nil {
return err
}
defer f.Close()
return pem.Encode(f, &pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes,
})
}(); err != nil {
return err
}
return nil
}

3
go.mod
View File

@ -3,7 +3,7 @@ module github.com/bolkedebruin/rdpgw
go 1.24.2
require (
github.com/andrewheberle/rdpsign v1.0.0
github.com/andrewheberle/rdpsign v1.1.0
github.com/bolkedebruin/gokrb5/v8 v8.5.0
github.com/coreos/go-oidc/v3 v3.9.0
github.com/fatih/structs v1.1.0
@ -24,6 +24,7 @@ require (
github.com/msteinert/pam/v2 v2.0.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/prometheus/client_golang v1.19.0
github.com/spf13/afero v1.14.0
github.com/stretchr/testify v1.10.0
github.com/thought-machine/go-flags v1.6.3
golang.org/x/crypto v0.36.0