From 8ef2e3c1538b5b9d847d5e17f7741e42f24a67ea Mon Sep 17 00:00:00 2001
From: Bolke de Bruin <bolke@xs4all.nl>
Date: Thu, 11 Aug 2022 13:24:12 +0200
Subject: [PATCH] Correct handshake response

---
 cmd/rdpgw/protocol/protocol_test.go | 54 ++++++++++++++++++++++++++++-
 cmd/rdpgw/protocol/server.go        |  2 +-
 2 files changed, 54 insertions(+), 2 deletions(-)

diff --git a/cmd/rdpgw/protocol/protocol_test.go b/cmd/rdpgw/protocol/protocol_test.go
index 6d74ae6..a57213a 100644
--- a/cmd/rdpgw/protocol/protocol_test.go
+++ b/cmd/rdpgw/protocol/protocol_test.go
@@ -66,7 +66,7 @@ func TestHandshake(t *testing.T) {
 		t.Fatalf("handshakeRequest failed got ext auth %d, expected %d", extAuth, extAuth|HTTP_EXTENDED_AUTH_PAA)
 	}
 
-	data = h.handshakeResponse(0x0, 0x0, 0, ERROR_SUCCESS)
+	data = h.handshakeResponse(0x0, 0x0, HTTP_EXTENDED_AUTH_PAA, ERROR_SUCCESS)
 	_, _, pkt, err = verifyPacketHeader(data, PKT_TYPE_HANDSHAKE_RESPONSE, HandshakeResponseLen)
 	if err != nil {
 		t.Fatalf("verifyHeader failed: %s", err)
@@ -79,6 +79,58 @@ func TestHandshake(t *testing.T) {
 	}
 }
 
+func capsHelper(h Server) uint16 {
+	var caps uint16
+	if h.TokenAuth {
+		caps = caps | HTTP_EXTENDED_AUTH_PAA
+	}
+	if h.SmartCardAuth {
+		caps = caps | HTTP_EXTENDED_AUTH_SC
+	}
+	return caps
+}
+
+func TestMatchAuth(t *testing.T) {
+	s := &SessionInfo{}
+	hc := &ServerConf{
+		TokenAuth: false,
+		SmartCardAuth: false,
+	}
+
+	h:= NewServer(s, hc)
+
+	in := uint16(0)
+	caps, err := h.matchAuth(in)
+	if err != nil {
+		t.Fatalf("in caps: %x <= server caps %x, but %s", in, capsHelper(*h), err)
+	}
+	if caps > in {
+		t.Fatalf("returned server caps %x > client cpas %x", capsHelper(*h), in)
+	}
+
+	in = HTTP_EXTENDED_AUTH_PAA
+	caps, err = h.matchAuth(in)
+	if err == nil {
+		t.Fatalf("server cannot satisfy client caps %x but error is nil (server caps %x)", in, caps)
+	} else {
+		t.Logf("(SUCCESS) server cannot satisfy client caps : %s", err)
+	}
+
+	h.SmartCardAuth = true
+	caps, err = h.matchAuth(in)
+	if err == nil {
+		t.Fatalf("server cannot satisfy client caps %x but error is nil (server caps %x)", in, caps)
+	} else {
+		t.Logf("(SUCCESS) server cannot satisfy client caps : %s", err)
+	}
+
+	h.TokenAuth = true
+	caps, err = h.matchAuth(in)
+	if err != nil {
+		t.Fatalf("server caps %x (orig: %x) should match client request %x, %s", caps, capsHelper(*h), in, err)
+	}
+}
+
 func TestTunnelCreation(t *testing.T) {
 	client := ClientConfig{
 		PAAToken: "abab",
diff --git a/cmd/rdpgw/protocol/server.go b/cmd/rdpgw/protocol/server.go
index 64bca2f..a85a088 100644
--- a/cmd/rdpgw/protocol/server.go
+++ b/cmd/rdpgw/protocol/server.go
@@ -232,7 +232,7 @@ func (s *Server) matchAuth(extAuth uint16) (caps uint16, err error) {
 		caps = caps | HTTP_EXTENDED_AUTH_PAA
 	}
 
-	if caps & extAuth == 0 {
+	if caps & extAuth == 0 && extAuth > 0 {
 		return 0, fmt.Errorf("%x has no matching capability configured (%x). Did you configure caps? ", extAuth, caps)
 	}
 
-- 
GitLab