Skip to content

Commit

Permalink
Merge pull request #22 from thomiceli/fix/ssh-keys
Browse files Browse the repository at this point in the history
Fix SSH pubkey detection
  • Loading branch information
thomiceli committed May 1, 2023
2 parents 713b5d6 + 58d40e2 commit 0362cd8
Show file tree
Hide file tree
Showing 6 changed files with 21 additions and 28 deletions.
6 changes: 3 additions & 3 deletions internal/models/sshkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func GetSSHKeyByID(sshKeyId uint) (*SSHKey, error) {
return sshKey, err
}

func GetSSHKeyByContent(sshKeyContent string) (*SSHKey, error) {
func SSHKeyDoesExists(sshKeyContent string) (*SSHKey, error) {
sshKey := new(SSHKey)
err := db.
Where("content like ?", sshKeyContent+"%").
Expand All @@ -65,9 +65,9 @@ func (sshKey *SSHKey) Delete() error {
return db.Delete(&sshKey).Error
}

func SSHKeyLastUsedNow(sshKeyID uint) error {
func SSHKeyLastUsedNow(sshKeyContent string) error {
return db.Model(&SSHKey{}).
Where("id = ?", sshKeyID).
Where("content = ?", sshKeyContent).
Update("last_used_at", time.Now().Unix()).Error
}

Expand Down
13 changes: 6 additions & 7 deletions internal/models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,14 @@ func GetUserById(userId uint) (*User, error) {
return user, err
}

func GetUserBySSHKeyID(sshKeyId uint) (*User, error) {
user := new(User)
func SSHKeyExistsForUser(sshKey string, userId uint) (*SSHKey, error) {
key := new(SSHKey)
err := db.
Preload("SSHKeys").
Joins("join ssh_keys on users.id = ssh_keys.user_id").
Where("ssh_keys.id = ?", sshKeyId).
First(&user).Error
Where("content = ?", sshKey).
Where("user_id = ?", userId).
First(&key).Error

return user, err
return key, err
}

func GetUserByProvider(id string, provider string) (*User, error) {
Expand Down
12 changes: 3 additions & 9 deletions internal/ssh/git_ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"strings"
)

func runGitCommand(ch ssh.Channel, gitCmd string, keyID uint, ip string) error {
func runGitCommand(ch ssh.Channel, gitCmd string, key string, ip string) error {
verb, args := parseCommand(gitCmd)
if !strings.HasPrefix(verb, "git-") {
verb = ""
Expand Down Expand Up @@ -43,7 +43,7 @@ func runGitCommand(ch ssh.Channel, gitCmd string, keyID uint, ip string) error {
}

if verb == "receive-pack" || requireLogin == "1" {
user, err := models.GetUserBySSHKeyID(keyID)
pubKey, err := models.SSHKeyExistsForUser(key, gist.UserID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
log.Warn().Msg("Invalid SSH authentication attempt from " + ip)
Expand All @@ -52,15 +52,9 @@ func runGitCommand(ch ssh.Channel, gitCmd string, keyID uint, ip string) error {
errorSsh("Failed to get user by SSH key id", err)
return errors.New("internal server error")
}

if user.ID != gist.UserID {
log.Warn().Msg("Invalid SSH authentication attempt from " + ip)
return errors.New("unauthorized")
}
_ = models.SSHKeyLastUsedNow(pubKey.Content)
}

_ = models.SSHKeyLastUsedNow(keyID)

repositoryPath := git.RepositoryPath(gist.User.Username, gist.Uuid)

cmd := exec.Command("git", verb, repositoryPath)
Expand Down
13 changes: 6 additions & 7 deletions internal/ssh/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
)
Expand All @@ -24,7 +23,8 @@ func Start() {

sshConfig := &ssh.ServerConfig{
PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
pkey, err := models.GetSSHKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
strKey := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key)))
_, err := models.SSHKeyDoesExists(strKey)
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
Expand All @@ -33,7 +33,7 @@ func Start() {
log.Warn().Msg("Invalid SSH authentication attempt from " + conn.RemoteAddr().String())
return nil, errors.New("unknown public key")
}
return &ssh.Permissions{Extensions: map[string]string{"key-id": strconv.Itoa(int(pkey.ID))}}, nil
return &ssh.Permissions{Extensions: map[string]string{"key": strKey}}, nil
},
}

Expand Down Expand Up @@ -71,13 +71,12 @@ func listen(serverConfig *ssh.ServerConfig) {
}

go ssh.DiscardRequests(reqs)
keyID, _ := strconv.Atoi(sConn.Permissions.Extensions["key-id"])
go handleConnexion(channels, uint(keyID), sConn.RemoteAddr().String())
go handleConnexion(channels, sConn.Permissions.Extensions["key"], sConn.RemoteAddr().String())
}()
}
}

func handleConnexion(channels <-chan ssh.NewChannel, keyID uint, ip string) {
func handleConnexion(channels <-chan ssh.NewChannel, key string, ip string) {
for channel := range channels {
if channel.ChannelType() != "session" {
_ = channel.Reject(ssh.UnknownChannelType, "Unknown channel type")
Expand Down Expand Up @@ -109,7 +108,7 @@ func handleConnexion(channels <-chan ssh.NewChannel, keyID uint, ip string) {
payloadCmd = payloadCmd[i:]
}

if err = runGitCommand(ch, payloadCmd, keyID, ip); err != nil {
if err = runGitCommand(ch, payloadCmd, key, ip); err != nil {
_, _ = ch.Stderr().Write([]byte("Opengist: " + err.Error() + "\r\n"))
}
_, _ = ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
Expand Down
3 changes: 2 additions & 1 deletion internal/web/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,12 @@ func sshKeysProcess(ctx echo.Context) error {

key.UserID = user.ID

_, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key.Content))
pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key.Content))
if err != nil {
addFlash(ctx, "Invalid SSH key", "error")
return redirect(ctx, "/settings")
}
key.Content = strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pubKey)))

if err := key.Create(); err != nil {
return errorRes(500, "Cannot add SSH key", err)
Expand Down
2 changes: 1 addition & 1 deletion templates/pages/settings.html
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ <h2 class="text-md font-bold text-slate-300">
Add SSH Key
</h2>
<h3 class="text-sm text-gray-400 italic mb-4">
Used only to push gists using Git via SSH
Used only to pull/push gists using Git via SSH
</h3>
<form class="space-y-6" action="/settings/ssh-keys" method="post">
<div>
Expand Down

0 comments on commit 0362cd8

Please sign in to comment.