Chmod Rewrites File Permission Bits

Chmod changes a file's permission bits and Stat reads them back, so secret files can drop to owner-only 0600 before any data is written.

GoSecurity Boundaries

Code

snippet
package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	dir, err := os.MkdirTemp("", "chmod-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)

	path := filepath.Join(dir, "secret.env")
	if err := os.WriteFile(path, []byte("token=abc\n"), 0o644); err != nil {
		panic(err)
	}

	// Chmod rewrites the file's permission bits (POSIX semantics)
	if err := os.Chmod(path, 0o600); err != nil {
		panic(err)
	}
	info, err := os.Stat(path)
	if err != nil {
		panic(err)
	}
	fmt.Println("after chmod 600:", info.Mode().String())

	// loosen the bits again to add group read
	if err := os.Chmod(path, 0o640); err != nil {
		panic(err)
	}
	info, _ = os.Stat(path)
	fmt.Println("after chmod 640:", info.Mode().String())
}

What the demo changes

The snippet creates secret.env inside a MkdirTemp directory, then drives the permission bits through two Chmod calls. os.Chmod rewrites the file mode in place and os.Stat reads the result back, so each printed line shows the mode string the kernel accepted after the call.

The first call drops the file to 0600, owner read/write only, before any secret content would land in it. The second call reopens group read with 0640, which is why the two printed modes differ between -rw—–– and -rw-r—–.

Points to remember

  • defer os.RemoveAll cleans the temp directory, so the demo leaves nothing behind.
  • On Windows, Chmod maps only the read-only bit; the rwx rendering follows POSIX semantics.

Interactive Tools for This Topic

FAQ

Why chmod the file down to 0600 after creating it at 0644?
The demo shows the auditable sequence: create, then tighten with Chmod and confirm with a Stat readback — the two printed modes go from -rw-r--r-- to -rw------- before any secret would be written.