Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat routing by group #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 43 additions & 6 deletions plugin/yaml/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"path/filepath"
"regexp"
"time"
"slices"
"os/user"

"github.com/patrickmn/go-cache"
"github.com/tg123/sshpiper/libplugin"
Expand All @@ -18,7 +20,8 @@ import (
)

type pipeConfigFrom struct {
Username string `yaml:"username"`
Username string `yaml:"username,omitempty"`
Groupname string `yaml:"groupname,omitempty"`
UsernameRegexMatch bool `yaml:"username_regex_match,omitempty"`
AuthorizedKeys string `yaml:"authorized_keys,omitempty"`
AuthorizedKeysData string `yaml:"authorized_keys_data,omitempty"`
Expand Down Expand Up @@ -220,20 +223,30 @@ func (p *plugin) createUpstream(conn libplugin.ConnMetadata, to pipeConfigTo, or

func (p *plugin) findAndCreateUpstream(conn libplugin.ConnMetadata, password string, publicKey []byte) (*libplugin.Upstream, error) {
user := conn.User()
userGroups, err := getUserGroups(user)

if err != nil {
return nil, err
}

config, err := p.loadConfig()

if err != nil {
return nil, err
}

for _, pipe := range config.Pipes {
for _, from := range pipe.From {
matched := from.Username == user

if from.UsernameRegexMatch {
matched, _ = regexp.MatchString(from.Username, user)
var matched bool
if from.Username != "" {
matched = from.Username == user
if from.UsernameRegexMatch {
matched, _ = regexp.MatchString(from.Username, user)
}
} else {
fromPipeGroup := from.Groupname
matched = slices.Contains(userGroups, fromPipeGroup)
}

if !matched {
continue
}
Expand Down Expand Up @@ -265,3 +278,27 @@ func (p *plugin) findAndCreateUpstream(conn libplugin.ConnMetadata, password str

return nil, fmt.Errorf("no matching pipe for username [%v] found", user)
}

func getUserGroups(userName string) ([]string, error) {
usr, err := user.Lookup(userName)
if err != nil {
return nil, err
}

groupIds, err := usr.GroupIds()
if err != nil {
return nil, err
}

var groups []string
for _, groupId := range groupIds {
grp, err := user.LookupGroupId(groupId)
if err != nil {
return nil, err
}
groups = append(groups, grp.Name)
}

return groups, nil
}