Skip to content

Commit

Permalink
Merge pull request #298 from soraxas/feat/use-ssh-key-standard
Browse files Browse the repository at this point in the history
Use regex to extract begin and end marker
  • Loading branch information
quexten authored Oct 30, 2024
2 parents b62ffb2 + 4b0b906 commit 51940fa
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions cli/agent/vault/vault.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package vault
import (
"errors"
"strings"
"fmt"
"regexp"
"sync"

"github.com/quexten/goldwarden/cli/agent/bitwarden/crypto"
Expand Down Expand Up @@ -174,6 +176,26 @@ type SSHKey struct {
PublicKey string
}

func extractKeyMarker(text, pattern string) (string, string, error) {
re := regexp.MustCompile(pattern)
match := re.FindStringIndex(text)

if match != nil {
// Extract the matched text
extracted := re.FindString(text[match[0]:match[1]])
if match[0] == 0 {
// begin marker
return extracted, text[match[1]:], nil
} else if match[1] == len(strings.TrimRight(text, "\n\r ")) {
// end marker
return extracted, text[:match[0]], nil
}
return "", text, fmt.Errorf("Token found is neither at the beginning nor end: pattern: %s. match idx: %s", pattern, match)
}

return "", text, fmt.Errorf("No match found in pattern %s", pattern)
}

func (vault *Vault) GetSSHKeys() []SSHKey {
vault.lockMutex()
defer vault.unlockMutex()
Expand Down Expand Up @@ -211,11 +233,19 @@ func (vault *Vault) GetSSHKeys() []SSHKey {
}
}

privateKey = strings.Replace(privateKey, "-----BEGIN OPENSSH PRIVATE KEY-----", "", 1)
privateKey = strings.Replace(privateKey, "-----END OPENSSH PRIVATE KEY-----", "", 1)
beginMarker, privateKey, err := extractKeyMarker(privateKey, `-----\w*BEGIN [a-zA-Z ]+\w*-----`)
if err != nil {
vaultLog.Error("Failed for note %s: %s", vault.secureNotes[id].Name, err.Error())
continue
}
endMarker, privateKey, err := extractKeyMarker(privateKey, `-----\w*END [a-zA-Z ]+\w*-----`)
if err != nil {
vaultLog.Error("Failed for note %s: %s", vault.secureNotes[id].Name, err.Error())
continue
}

pkParts := strings.Join(strings.Split(privateKey, " "), "\n")
privateKeyString := "-----BEGIN OPENSSH PRIVATE KEY-----" + pkParts + "-----END OPENSSH PRIVATE KEY-----"
privateKeyString := beginMarker + pkParts + endMarker

decryptedTitle, err := crypto.DecryptWith(vault.secureNotes[id].Name, key)
if err != nil {
Expand Down

0 comments on commit 51940fa

Please sign in to comment.