Skip to content

Instantly share code, notes, and snippets.

@nobiit
Created November 24, 2024 05:33
Show Gist options
  • Select an option

  • Save nobiit/0cc8a9e3d00fa14bf2949150dd3d460c to your computer and use it in GitHub Desktop.

Select an option

Save nobiit/0cc8a9e3d00fa14bf2949150dd3d460c to your computer and use it in GitHub Desktop.
package keyring
import (
"errors"
"fmt"
"go.nobidev.com/ssh-agent/pkg/schema"
"golang.org/x/crypto/ssh/agent"
"net"
)
func ParseKey(key agent.AddedKey) (*schema.Key, error) {
if key.PrivateKey == nil {
return nil, errors.New("invalid .PrivateKey")
}
if key.Certificate != nil {
return nil, errors.New("invalid .Certificate")
}
if key.LifetimeSecs > 0 {
return nil, errors.New("invalid .LifetimeSecs")
}
if key.ConfirmBeforeUse {
return nil, errors.New("invalid .ConfirmBeforeUse")
}
if key.ConstraintExtensions != nil {
return nil, errors.New("invalid .ConstraintExtensions")
}
k, err := schema.NewPrivateKey(key.PrivateKey)
if err != nil {
return nil, err
}
k.Comment = key.Comment
return k, nil
}
func ToKey(k schema.Key) (agent.AddedKey, error) {
key := agent.AddedKey{
Comment: k.Comment,
}
var err error
key.PrivateKey, err = k.GetPrivateKey()
if err != nil {
return key, err
}
return key, nil
}
func getClientInfo(c net.Conn) (any, error) {
switch v := c.(type) {
case *net.UnixConn:
return getClientUnixInfo(v)
default:
return nil, fmt.Errorf("unsupported connection: %v", c)
}
}
//go:build darwin
package keyring
import (
"errors"
"github.com/shirou/gopsutil/v4/process"
"golang.org/x/sys/unix"
"net"
"os/user"
"strconv"
)
func getClientUnixInfo(c *net.UnixConn) (*ClientInfo, error) {
rc, err := c.SyscallConn()
if err != nil {
return nil, err
}
var (
xucred *unix.Xucred
pid int
err2, err3 error
)
err = rc.Control(func(fd uintptr) {
xucred, err2 = unix.GetsockoptXucred(
int(fd),
unix.SOL_LOCAL,
unix.LOCAL_PEERCRED,
)
pid, err3 = unix.GetsockoptInt(
int(fd),
unix.SOL_LOCAL,
unix.LOCAL_PEERPID,
)
})
err = errors.Join(err, err2, err3)
if err != nil {
return nil, err
}
r := new(ClientInfo)
p, err := process.NewProcess(int32(pid))
if err != nil {
return r, err
}
r.Process = p
u, err := user.LookupId(strconv.Itoa(int(xucred.Uid)))
if err != nil {
return r, err
}
r.User = u
for _, gid := range xucred.Groups[:xucred.Ngroups] {
g, err := user.LookupGroupId(strconv.Itoa(int(gid)))
if err != nil {
return r, err
}
r.Groups = append(r.Groups, g)
}
return r, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment