From bbeb55f5faf93659e1cfd6ab073ab3c9d126d195 Mon Sep 17 00:00:00 2001
From: Roland Shoemaker <bracewell@google.com>
Date: Fri, 5 May 2023 13:10:34 -0700
Subject: [PATCH] cmd/go: enforce flags with non-optional arguments

Enforce that linker flags which expect arguments get them, otherwise it
may be possible to smuggle unexpected flags through as the linker can
consume what looks like a flag as an argument to a preceding flag (i.e.
"-Wl,-O -Wl,-R,-bad-flag" is interpreted as "-O=-R -bad-flag"). Also be
somewhat more restrictive in the general format of some flags.

Thanks to Juho Nurminen of Mattermost for reporting this issue.

Fixes #60305
Fixes CVE-2023-29404

Change-Id: I913df78a692cee390deefc3cd7d8f5b031524fc9
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/1876275
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/501225
Run-TryBot: David Chase <drchase@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>

Upstream-Status: Backport [https://github.com/golang/go/commit/bbeb55f5faf93659e1cfd6ab073ab3c9d126d195]
CVE: CVE-2023-29404

Signed-off-by: Archana Polampalli <archana.polampalli@windriver.com>
---
 src/cmd/go/internal/work/security.go      | 6 +++---
 src/cmd/go/internal/work/security_test.go | 5 +++++
 2 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/src/cmd/go/internal/work/security.go b/src/cmd/go/internal/work/security.go
index e9b9f6c..91e6e4c 100644
--- a/src/cmd/go/internal/work/security.go
+++ b/src/cmd/go/internal/work/security.go
@@ -179,10 +179,10 @@ var validLinkerFlags = []*lazyregexp.Regexp{
	re(`-Wl,-berok`),
	re(`-Wl,-Bstatic`),
	re(`-Wl,-Bsymbolic-functions`),
-	re(`-Wl,-O([^@,\-][^,]*)?`),
+	re(`-Wl,-O[0-9]+`),
	re(`-Wl,-d[ny]`),
	re(`-Wl,--disable-new-dtags`),
-	re(`-Wl,-e[=,][a-zA-Z0-9]*`),
+	re(`-Wl,-e[=,][a-zA-Z0-9]+`),
	re(`-Wl,--enable-new-dtags`),
	re(`-Wl,--end-group`),
	re(`-Wl,--(no-)?export-dynamic`),
@@ -191,7 +191,7 @@ var validLinkerFlags = []*lazyregexp.Regexp{
	re(`-Wl,--hash-style=(sysv|gnu|both)`),
	re(`-Wl,-headerpad_max_install_names`),
	re(`-Wl,--no-undefined`),
-	re(`-Wl,-R([^@\-][^,@]*$)`),
+	re(`-Wl,-R,?([^@\-,][^,@]*$)`),
	re(`-Wl,--just-symbols[=,]([^,@\-][^,@]+)`),
	re(`-Wl,-rpath(-link)?[=,]([^,@\-][^,]+)`),
	re(`-Wl,-s`),
diff --git a/src/cmd/go/internal/work/security_test.go b/src/cmd/go/internal/work/security_test.go
index 8d4be0a..3616548 100644
--- a/src/cmd/go/internal/work/security_test.go
+++ b/src/cmd/go/internal/work/security_test.go
@@ -227,6 +227,11 @@ var badLinkerFlags = [][]string{
	{"-Wl,-R,@foo"},
	{"-Wl,--just-symbols,@foo"},
	{"../x.o"},
+	{"-Wl,-R,"},
+	{"-Wl,-O"},
+	{"-Wl,-e="},
+	{"-Wl,-e,"},
+	{"-Wl,-R,-flag"},
 }

 func TestCheckLinkerFlags(t *testing.T) {
--
2.40.0
