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.
Code
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
Unix Permissions CalculatorConvert between octal and symbolic Unix file permissions and explain read/write/execute plus setuid, setgid, and sticky bits.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.