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

Use regex to extract begin and end marker #298

Merged
merged 1 commit into from
Oct 30, 2024
Merged
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
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
Loading