/
ssl_permissions.go
68 lines (58 loc) · 1.72 KB
/
ssl_permissions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//go:build !windows
// +build !windows
package pq
import (
"io/fs"
"os"
"syscall"
)
const rootUserID = uint32(0)
// sslKeyPermissions checks the permissions on user-supplied ssl key files.
// The key file should have very little access.
//
// libpq does not check key file permissions on Windows.
func sslKeyPermissions(sslkey string) error {
info, err := os.Stat(sslkey)
if err != nil {
return err
}
return hasCorrectPermissions(info)
}
// hasCorrectPermissions checks the file info (and the unix-specific stat_t
// output) to verify that the permissions on the file are correct.
//
// If the file is owned by the same user the process is running as,
// the file should only have 0600 (u=rw). If the file is owned by root,
// and the group matches the group that the process is running in, the
// permissions cannot be more than 0660 (u=rw,g=rw). The file should
// never have world permissions.
//
// Returns an error when the permission check fails.
func hasCorrectPermissions(info fs.FileInfo) error {
// if file's permission matches 0600, allow access.
if info.Mode().Perm()&0177 == 0 {
return nil
}
sysInfo := info.Sys()
if sysInfo == nil {
return ErrSSLKeyUnknownOwnership
}
unixStat, ok := sysInfo.(*syscall.Stat_t)
if !ok {
return ErrSSLKeyUnknownOwnership
}
// if the file is owned by root, allow permission to be managed by
// the process group ID.
if unixStat.Uid == rootUserID {
if unixStat.Gid != uint32(os.Getgid()) {
return ErrSSLKeyNotOwnedByGroup
}
if info.Mode().Perm()&0117 != 0 {
return ErrSSLKeyHasWorldPermissions
}
// if the file group ID matches th process group ID and the
// file is not world readable, we are good to go
return nil
}
return ErrSSLKeyHasGroupPermissions
}