加固管理员恢复边界并补充三库实机与安全复扫验收
This commit is contained in:
1 parent
49a584dfc8
commit
ad771b3f22
9 files changed
+277
-18
No files matched your search
@@ -9,6 +9,8 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
const systemctlPath = "/usr/bin/systemctl"
|
||||
|
||||
// AuthorizeCurrentProcess 只允许部署管理员启动正式重置流程。
|
||||
func AuthorizeCurrentProcess() error {
|
||||
if !authorizeLinuxProcess(os.Geteuid(), os.Getpid(), os.Getppid(), os.Getenv("INVOCATION_ID"), os.Getenv("SYSTEMD_EXEC_PID")) || !authorizedSystemdStartJob() {
|
||||
@@ -21,13 +23,17 @@ func AuthorizeCurrentProcess() error {
|
||||
}
|
||||
|
||||
func authorizedSystemdStartJob() bool {
|
||||
output, err := exec.Command("systemctl", "list-jobs", "--no-legend", "--plain", "--no-pager").Output()
|
||||
output, err := systemdJobCommand().Output()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return hasAuthorizedStartJob(string(output))
|
||||
}
|
||||
|
||||
func systemdJobCommand() *exec.Cmd {
|
||||
return exec.Command(systemctlPath, "list-jobs", "--no-legend", "--plain", "--no-pager")
|
||||
}
|
||||
|
||||
func hasAuthorizedStartJob(output string) bool {
|
||||
for _, line := range strings.Split(output, "\n") {
|
||||
fields := strings.Fields(line)
|
||||
@@ -63,7 +69,7 @@ func validInvocationID(value string) bool {
|
||||
|
||||
// CheckEnvironment 读取 Linux 管理程序的非敏感运行状态。
|
||||
func CheckEnvironment() EnvironmentReport {
|
||||
_, err := exec.LookPath("systemd-ask-password")
|
||||
_, err := exec.LookPath(systemdInputAgentPath)
|
||||
serviceManaged := os.Getppid() == 1 && validInvocationID(os.Getenv("INVOCATION_ID")) && authorizedSystemdStartJob()
|
||||
_, callerErr := findStartCaller()
|
||||
return EnvironmentReport{
|
||||
|
||||
@@ -5,6 +5,7 @@ package adminreset
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
@@ -47,11 +48,11 @@ func OpenInvocation(parent context.Context) (context.Context, func(), error) {
|
||||
file := os.NewFile(uintptr(fd), "smail-admin-terminal")
|
||||
var info unix.Stat_t
|
||||
err = unix.Fstat(fd, &info)
|
||||
device := uint32(caller.terminal)
|
||||
expectedDevice := unix.Mkdev((device>>8)&0xfff, (device&0xff)|((device>>12)&0xfff00))
|
||||
expectedDevice, deviceErr := terminalDevice(caller.terminal)
|
||||
// 服务不属于调用终端的会话,不能使用 TIOCGPGRP;前台关系由 /proc 校验。
|
||||
if err != nil || info.Rdev != expectedDevice || !term.IsTerminal(fd) {
|
||||
file.Close()
|
||||
if err != nil || deviceErr != nil || info.Rdev != expectedDevice || !term.IsTerminal(fd) {
|
||||
// 关闭只释放终端描述符;授权失败始终返回,不因关闭错误放行。
|
||||
_ = file.Close()
|
||||
return nil, nil, ErrUnauthorizedPeer
|
||||
}
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
@@ -78,10 +79,27 @@ func OpenInvocation(parent context.Context) (context.Context, func(), error) {
|
||||
return ctx, func() {
|
||||
cancel()
|
||||
<-done
|
||||
file.Close()
|
||||
// 终端不缓存业务写入;取消并等待监视器退出后释放描述符。
|
||||
_ = file.Close()
|
||||
}, nil
|
||||
}
|
||||
|
||||
func terminalDevice(raw int) (uint64, error) {
|
||||
if raw < math.MinInt32 || raw > math.MaxInt32 {
|
||||
return 0, ErrUnauthorizedPeer
|
||||
}
|
||||
// /proc 的 tty_nr 是有符号的 32 位编码;负值的高位仍属于合法设备号。
|
||||
encoded := int64(raw)
|
||||
if encoded < 0 {
|
||||
encoded += 1 << 32
|
||||
}
|
||||
if encoded < 0 || encoded > math.MaxUint32 {
|
||||
return 0, ErrUnauthorizedPeer
|
||||
}
|
||||
device := uint32(encoded)
|
||||
return unix.Mkdev((device>>8)&0xfff, (device&0xff)|((device>>12)&0xfff00)), nil
|
||||
}
|
||||
|
||||
func findStartCaller() (callerIdentity, error) {
|
||||
entries, err := os.ReadDir("/proc")
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//go:build linux
|
||||
|
||||
package adminreset
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func TestTerminalDeviceSignedEncodingBoundaries(t *testing.T) {
|
||||
tests := []struct {
|
||||
raw int
|
||||
major uint32
|
||||
minor uint32
|
||||
}{
|
||||
{0, 0, 0},
|
||||
{34817, 136, 1},
|
||||
{math.MaxInt32, 4095, 524287},
|
||||
{math.MinInt32, 0, 524288},
|
||||
{-1, 4095, 1048575},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(strconv.Itoa(test.raw), func(t *testing.T) {
|
||||
device, err := terminalDevice(test.raw)
|
||||
if err != nil || device != unix.Mkdev(test.major, test.minor) {
|
||||
t.Fatalf("终端设备编码错误:%x,%v", device, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
if strconv.IntSize == 64 {
|
||||
for _, raw := range []int64{int64(math.MinInt32) - 1, int64(math.MaxInt32) + 1, math.MaxInt64, math.MinInt64} {
|
||||
if _, err := terminalDevice(int(raw)); !errors.Is(err, ErrUnauthorizedPeer) {
|
||||
t.Fatalf("越界终端设备号未拒绝:%d", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalPollDescriptorRejectsTruncation(t *testing.T) {
|
||||
for _, fd := range []uintptr{0, 1, math.MaxInt32} {
|
||||
actual, err := terminalPollDescriptor(fd)
|
||||
if err != nil || uint64(actual) != uint64(fd) {
|
||||
t.Fatalf("合法描述符转换失败:%d,%v", fd, err)
|
||||
}
|
||||
}
|
||||
for _, fd := range []uintptr{math.MaxInt32 + 1, math.MaxUint32, ^uintptr(0)} {
|
||||
if _, err := terminalPollDescriptor(fd); !errors.Is(err, ErrUnauthorizedPeer) {
|
||||
t.Fatalf("越界描述符未拒绝:%d", fd)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalStreamRejectsClosedDescriptor(t *testing.T) {
|
||||
file, err := os.Open(os.DevNull)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stream := &terminalStream{ctx: context.Background(), terminal: &invocationTerminal{file: file}}
|
||||
if _, err := stream.Read(make([]byte, 1)); !errors.Is(err, ErrUnauthorizedPeer) {
|
||||
t.Fatalf("已关闭描述符未拒绝:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtectedCommandsIgnoreSearchPath(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
for _, name := range []string{"systemctl", "systemd-ask-password"} {
|
||||
if err := os.WriteFile(filepath.Join(directory, name), []byte("#!/bin/sh\nexit 91\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
t.Setenv("PATH", directory)
|
||||
for _, name := range []string{"systemctl", "systemd-ask-password"} {
|
||||
resolved, err := exec.LookPath(name)
|
||||
if err != nil || resolved != filepath.Join(directory, name) {
|
||||
t.Fatal("PATH 劫持反例未正确构造")
|
||||
}
|
||||
}
|
||||
command := systemdInputCommand(context.Background(), "--no-tty", "--echo=no", "$(id);提示")
|
||||
if command.Path != systemdInputAgentPath || command.Args[3] != "$(id);提示" {
|
||||
t.Fatal("密码代理路径或原样参数不符合约束")
|
||||
}
|
||||
if command := systemdJobCommand(); command.Path != systemctlPath || len(command.Args) != 5 {
|
||||
t.Fatal("systemctl 来源被搜索路径替换")
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
)
|
||||
|
||||
const systemdInputAgentPath = "/usr/bin/systemd-ask-password"
|
||||
|
||||
func ReadProtectedPassword() (string, error) {
|
||||
return ReadProtectedPasswordContext(context.Background())
|
||||
}
|
||||
@@ -83,7 +85,7 @@ func readSystemdInputContext(ctx context.Context, prompt, echo string, options .
|
||||
// systemd 代理把提示保存在单行配置中,用终端换行控制显示列表,避免配置被拆行。
|
||||
prompt = strings.ReplaceAll(strings.ReplaceAll(prompt, "\r\n", "\n"), "\n", "\x1bE")
|
||||
args := append([]string{"--no-tty", "--echo=" + echo}, options...)
|
||||
command := exec.CommandContext(ctx, "systemd-ask-password", append(args, prompt)...)
|
||||
command := systemdInputCommand(ctx, append(args, prompt)...)
|
||||
// 先允许代理清理请求文件,避免取消后继续弹出已经失效的输入提示。
|
||||
command.Cancel = func() error { return command.Process.Signal(syscall.SIGTERM) }
|
||||
command.WaitDelay = time.Second
|
||||
@@ -98,6 +100,11 @@ func readSystemdInputContext(ctx context.Context, prompt, echo string, options .
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func systemdInputCommand(ctx context.Context, args ...string) *exec.Cmd {
|
||||
// 管理员流程不能从调用环境的 PATH 解析高权限密码代理。
|
||||
return exec.CommandContext(ctx, systemdInputAgentPath, args...)
|
||||
}
|
||||
|
||||
func stripPasswordLineEnding(value []byte) []byte {
|
||||
if len(value) > 0 && value[len(value)-1] == '\n' {
|
||||
value = value[:len(value)-1]
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
@@ -64,12 +65,15 @@ type terminalStream struct {
|
||||
}
|
||||
|
||||
func (s *terminalStream) Read(buffer []byte) (int, error) {
|
||||
fd := int(s.terminal.file.Fd())
|
||||
fd, err := terminalPollDescriptor(s.terminal.file.Fd())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for {
|
||||
if err := s.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
fds := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
|
||||
fds := []unix.PollFd{{Fd: fd, Events: unix.POLLIN}}
|
||||
_, err := unix.Poll(fds, 100)
|
||||
if err == unix.EINTR {
|
||||
continue
|
||||
@@ -83,7 +87,7 @@ func (s *terminalStream) Read(buffer []byte) (int, error) {
|
||||
if fds[0].Revents&unix.POLLIN == 0 {
|
||||
continue
|
||||
}
|
||||
n, err := unix.Read(fd, buffer)
|
||||
n, err := unix.Read(int(fd), buffer)
|
||||
if err == unix.EAGAIN || err == unix.EINTR {
|
||||
continue
|
||||
}
|
||||
@@ -93,3 +97,10 @@ func (s *terminalStream) Read(buffer []byte) (int, error) {
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
|
||||
func terminalPollDescriptor(fd uintptr) (int32, error) {
|
||||
if fd > math.MaxInt32 {
|
||||
return 0, ErrUnauthorizedPeer
|
||||
}
|
||||
return int32(fd), nil
|
||||
}
|
||||
@@ -86,7 +86,8 @@ func validateControlSocketOwner(info os.FileInfo) error {
|
||||
|
||||
func validateControlOwner(info os.FileInfo, resource string) error {
|
||||
stat, ok := info.Sys().(*syscall.Stat_t)
|
||||
if !ok || stat.Uid != uint32(os.Geteuid()) {
|
||||
uid := os.Geteuid()
|
||||
if !ok || uid < 0 || uint64(stat.Uid) != uint64(uid) {
|
||||
return fmt.Errorf("%s owner does not match service identity", resource)
|
||||
}
|
||||
return nil
|
||||
|
||||
Reference in new issue
Block a user