Fix path traversal attack in -proto-out-dir (#573)

* Fix path traversal in `-proto-out-dir`

A malicious file descriptor name (e.g. from an untrusted protoset or
server reflection) could escape the output directory through ../
sequences, writing attacker-controlled content to arbitrary paths.

Confine all writes to an `os.Root` opened on the output directory.

* assert

* refactor

---------

Co-authored-by: Scott Blum <dragonsinth@gmail.com>
This commit is contained in:
Bram
2026-07-27 15:30:28 -04:00
committed by GitHub
parent 353acfef45
commit 6be36ba632
2 changed files with 67 additions and 8 deletions
+47 -1
View File
@@ -3,9 +3,11 @@ package grpcurl
import (
"bytes"
"os"
"path/filepath"
"testing"
"github.com/golang/protobuf/proto" //lint:ignore SA1019 we have to import this because it appears in exported API
"github.com/golang/protobuf/proto"
"github.com/jhump/protoreflect/desc"
"google.golang.org/protobuf/types/descriptorpb"
)
@@ -60,3 +62,47 @@ func checkWriteProtoset(t *testing.T, descSrc DescriptorSource, protoset *descri
t.Fatalf("written protoset not equal to input:\nExpecting: %s\nActual: %s", protoset, &result)
}
}
func writeProtoFileForTest(t *testing.T, dir, fdName string) error {
t.Helper()
fd, err := desc.CreateFileDescriptor(&descriptorpb.FileDescriptorProto{
Name: proto.String(fdName),
Syntax: proto.String("proto3"),
})
if err != nil {
t.Fatalf("failed to create file descriptor: %v", err)
}
return writeProtoFiles(dir, []*desc.FileDescriptor{fd})
}
func TestWriteProtoFile_NormalPath(t *testing.T) {
dir := t.TempDir()
if err := writeProtoFileForTest(t, dir, "foo/bar.proto"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if _, err := os.Stat(filepath.Join(dir, "foo", "bar.proto")); err != nil {
t.Fatalf("expected output file not created: %v", err)
}
}
func TestWriteProtoFile_RejectsPathTraversal(t *testing.T) {
dir := t.TempDir()
if err := writeProtoFileForTest(t, dir, "../escape.proto"); err == nil {
t.Fatal("expected error for path-traversing descriptor name, got nil")
}
escapePath := filepath.Join(dir, "..", "escape.proto")
if _, err := os.Stat(escapePath); err == nil {
t.Fatalf("file was created outside output directory at %q", escapePath)
}
}
func TestWriteProtoFile_RejectsDeepPathTraversal(t *testing.T) {
dir := t.TempDir()
if err := writeProtoFileForTest(t, dir, "foo/../../../escape.proto"); err == nil {
t.Fatal("expected error for path-traversing descriptor name, got nil")
}
escapePath := filepath.Join(dir, "foo", "..", "..", "..", "escape.proto")
if _, err := os.Stat(escapePath); err == nil {
t.Fatalf("file was created outside output directory at %q", escapePath)
}
}