package libraryagent import ( "errors" "net" "os" "syscall" ) // peerAllowed enforces that the connecting process runs as the same uid as the // agent. File mode 0600 already limits connect() to that uid; the credential // check makes the boundary explicit and fails closed if the socket is ever // reached another way (bind mount into a container with a different uid). func peerAllowed(conn net.Conn, allowed map[uint32]bool) error { unixConn, ok := conn.(*net.UnixConn) if !ok { return errors.New("unsupported transport") } raw, err := unixConn.SyscallConn() if err != nil { return errors.New("peer credentials unavailable") } var credential *syscall.Ucred var controlErr error if err = raw.Control(func(fd uintptr) { credential, controlErr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED) }); err != nil { return errors.New("peer credentials unavailable") } if controlErr != nil || credential == nil { return errors.New("peer credentials unavailable") } // 默认只允许与 agent 同 uid 的连接;显式声明过的 uid(例如容器里的 // 固定运行用户)才放行。放行清单来自部署参数,不是"任何人"。 if credential.Uid != uint32(os.Geteuid()) && !allowed[credential.Uid] { return errors.New("peer uid is not allowed") } return nil }