From 8c8efba252bdb87288968c4b97f53e9875f67e87 Mon Sep 17 00:00:00 2001 From: Kohei Morita Date: Sun, 29 Dec 2024 20:55:10 +0900 Subject: [PATCH] feat: Add ProtectOpenFile wrapping os.OpenFile --- contrib/database/sql/README.md | 2 +- contrib/os/README.md | 20 ++++++++++++++++++++ contrib/os/waf.go | 9 +++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 contrib/os/README.md diff --git a/contrib/database/sql/README.md b/contrib/database/sql/README.md index ef2c1b9..b74a194 100644 --- a/contrib/database/sql/README.md +++ b/contrib/database/sql/README.md @@ -4,7 +4,7 @@ This package provides a wrapper for [`database/sql`](https://pkg.go.dev/database # Usage -to english: When executing a statement, use the Waffle database driver instead of `database/sql`. At this time, you need to pass the Waffle's operation `context`. +When executing a statement, use the Waffle database driver instead of `database/sql`. At this time, you need to pass the Waffle's operation `context`. ```go import ( diff --git a/contrib/os/README.md b/contrib/os/README.md new file mode 100644 index 0000000..771abc6 --- /dev/null +++ b/contrib/os/README.md @@ -0,0 +1,20 @@ +# os + +This package provides a wrapper for [`os`](https://pkg.go.dev/os) protected by Waffle. +It provides functions that wrap `os.ReadFile` and `os.WriteFile` to prevent directory traversal and access to sensitive files. + +# Usage + +When accessing a file, use the Waffle's file functions instead of `os`. + +```go +import ( + waffleOs "github.com/sitebatch/waffle-go/contrib/os" +) + +// ProtectReadFile wraps os.ReadFile +data, err := waffleOs.ProtectReadFile(ctx, "") + +// ProtectOpenFile wraps os.OpenFile +f, err := waffleOs.ProtectOpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0644) +``` diff --git a/contrib/os/waf.go b/contrib/os/waf.go index 932b272..52e10c0 100644 --- a/contrib/os/waf.go +++ b/contrib/os/waf.go @@ -15,3 +15,12 @@ func ProtectReadFile(ctx context.Context, name string) ([]byte, error) { return os.ReadFile(name) } + +// ProtectOpenFile protects file opening from attacks such as directory traversal and executes os.OpenFile. +func ProtectOpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (*os.File, error) { + if err := osHandler.ProtectFileOperation(ctx, name); err != nil { + return nil, err + } + + return os.OpenFile(name, flag, perm) +}