Skip to content

Commit

Permalink
Merge pull request #141 from SuperSandro2000/browser-err
Browse files Browse the repository at this point in the history
Improve overhaul error handling, Fix more lints found by golangci-lint's default config
  • Loading branch information
quexten authored Mar 21, 2024
2 parents 7b3e21b + 3323326 commit 6ac5754
Show file tree
Hide file tree
Showing 20 changed files with 223 additions and 137 deletions.
3 changes: 3 additions & 0 deletions agent/actions/send.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ func handleCreateSend(msg messages.IPCMessage, cfg *config.Config, vault *vault.

ctx := context.WithValue(context.TODO(), bitwarden.AuthToken{}, token.AccessToken)
url, err := bitwarden.CreateSend(ctx, cfg, vault, parsedMsg.Name, parsedMsg.Text)
if err != nil {
actionsLog.Warn(err.Error())
}

response, err = messages.IPCMessageFromPayload(messages.CreateSendResponse{
URL: url,
Expand Down
5 changes: 4 additions & 1 deletion agent/actions/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,17 @@ func handleAddSSH(msg messages.IPCMessage, cfg *config.Config, vault *vault.Vaul
req := messages.ParsePayload(msg).(messages.CreateSSHKeyRequest)

cipher, publicKey := ssh.NewSSHKeyCipher(req.Name, vault.Keyring)
response, err = messages.IPCMessageFromPayload(messages.ActionResponse{
_, err = messages.IPCMessageFromPayload(messages.ActionResponse{
Success: true,
})
if err != nil {
panic(err)
}

token, err := cfg.GetToken()
if err != nil {
actionsLog.Warn(err.Error())
}
ctx := context.WithValue(context.TODO(), bitwarden.AuthToken{}, token.AccessToken)
ciph, err := bitwarden.PostCipher(ctx, cipher, cfg)
if err == nil {
Expand Down
4 changes: 2 additions & 2 deletions agent/bitwarden/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,10 @@ func LoginWithMasterpassword(ctx context.Context, email string, cfg *config.Conf
return LoginResponseToken{}, crypto.MasterKey{}, "", err
}
} else if err != nil && strings.Contains(err.Error(), "Captcha required.") {
notify.Notify("Goldwarden", fmt.Sprintf("Captcha required"), "", 0, func() {})
notify.Notify("Goldwarden", "Captcha required", "", 0, func() {})
return LoginResponseToken{}, crypto.MasterKey{}, "", fmt.Errorf("captcha required, please login via the web interface")
} else if err != nil {
notify.Notify("Goldwarden", fmt.Sprintf("Could not login via password: %v", err), "", 0, func() {})
notify.Notify("Goldwarden", fmt.Sprintf("Could not login via password: %s", err.Error()), "", 0, func() {})
return LoginResponseToken{}, crypto.MasterKey{}, "", fmt.Errorf("could not login via password: %v", err)
}

Expand Down
3 changes: 1 addition & 2 deletions agent/bitwarden/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
Expand Down Expand Up @@ -105,7 +104,7 @@ func makeAuthenticatedHTTPRequest(ctx context.Context, req *http.Request, recv i
return err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
body, err := io.ReadAll(res.Body)
if err != nil {
return err
}
Expand Down
8 changes: 7 additions & 1 deletion agent/bitwarden/passwordless.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,17 @@ func CreateAuthResponse(ctx context.Context, authRequest AuthRequestData, keyrin
//}

publicKey, err := base64.StdEncoding.DecodeString(authRequest.PublicKey)
if err != nil {
return AuthRequestResponseData{}, err
}
requesterKey, err := crypto.MemoryAssymmetricEncryptionKeyFromBytes(publicKey)
if err != nil {
return AuthRequestResponseData{}, err
}

encryptedUserSymmetricKey, err := crypto.EncryptWithAsymmetric(userSymmetricKey, requesterKey)
if err != nil {
panic(err)
return AuthRequestResponseData{}, err
}
//encryptedMasterPasswordHash, err := crypto.EncryptWithAsymmetric(masterPasswordHash, requesterKey)
//if err != nil {
Expand Down
4 changes: 4 additions & 0 deletions agent/bitwarden/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ func connectToWebsocket(ctx context.Context, vault *vault.Vault, cfg *config.Con
}

token, err := cfg.GetToken()
if err != nil {
return err
}

var websocketURL = "wss://" + url.Host + url.Path + "/hub?access_token=" + token.AccessToken
c, _, err := websocket.DefaultDialer.Dial(websocketURL, nil)
if err != nil {
Expand Down
3 changes: 1 addition & 2 deletions agent/systemauth/pinentry/keybase-pinentry/pinentry.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func (pe *Pinentry) Get(arg keybase1.SecretEntryArg) (res *keybase1.SecretEntryR

func (pi *pinentryInstance) Close() {
pi.stdin.Close()
pi.cmd.Wait()
_ = pi.cmd.Wait()
}

type pinentryInstance struct {
Expand All @@ -123,7 +123,6 @@ func (pi *pinentryInstance) Set(cmd, val string, errp *error) {
if string(line) != "OK" {
*errp = fmt.Errorf("Response to " + cmd + " was " + string(line))
}
return
}

func (pi *pinentryInstance) Init() (err error) {
Expand Down
81 changes: 39 additions & 42 deletions autotype/libportalautotype.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,50 +42,47 @@ func TypeString(textToType string) {
var sessionHandle dbus.ObjectPath

for {
select {
case message := <-signals:
if state == 0 {
log.Info("Selecting Devices")
result := message.Body[1].(map[string]dbus.Variant)
resultSessionHandle := result["session_handle"]
sessionHandle = dbus.ObjectPath(resultSessionHandle.String()[1 : len(resultSessionHandle.String())-1])
res := obj.Call("org.freedesktop.portal.RemoteDesktop.SelectDevices", 0, sessionHandle, map[string]dbus.Variant{
"types": dbus.MakeVariant(uint32(1)),
})
if res.Err != nil {
log.Error("Error selecting devices: %s", res.Err.Error())
}
state = 1
} else if state == 1 {
log.Info("Starting Session")
res := obj.Call("org.freedesktop.portal.RemoteDesktop.Start", 0, sessionHandle, "", map[string]dbus.Variant{})
if res.Err != nil {
log.Error("Error starting session: %s", res.Err.Error())
}
state = 2
} else if state == 2 {
log.Info("Performing Typing")
state = 3
time.Sleep(1000 * time.Millisecond)
for _, char := range textToType {
if char == '\t' {
obj.Call("org.freedesktop.portal.RemoteDesktop.NotifyKeyboardKeycode", 0, sessionHandle, map[string]dbus.Variant{}, 15, uint32(1))
time.Sleep(autoTypeDelay)
obj.Call("org.freedesktop.portal.RemoteDesktop.NotifyKeyboardKeycode", 0, sessionHandle, map[string]dbus.Variant{}, 15, uint32(0))
time.Sleep(autoTypeDelay)
} else {
obj.Call("org.freedesktop.portal.RemoteDesktop.NotifyKeyboardKeysym", 0, sessionHandle, map[string]dbus.Variant{}, int32(char), uint32(1))
time.Sleep(autoTypeDelay)
obj.Call("org.freedesktop.portal.RemoteDesktop.NotifyKeyboardKeysym", 0, sessionHandle, map[string]dbus.Variant{}, int32(char), uint32(0))
time.Sleep(autoTypeDelay)
}
message := <-signals
switch state {
case 0:
log.Info("Selecting Devices")
result := message.Body[1].(map[string]dbus.Variant)
resultSessionHandle := result["session_handle"]
sessionHandle = dbus.ObjectPath(resultSessionHandle.String()[1 : len(resultSessionHandle.String())-1])
res := obj.Call("org.freedesktop.portal.RemoteDesktop.SelectDevices", 0, sessionHandle, map[string]dbus.Variant{
"types": dbus.MakeVariant(uint32(1)),
})
if res.Err != nil {
log.Error("Error selecting devices: %s", res.Err.Error())
}
state = 1
case 1:
log.Info("Starting Session")
res := obj.Call("org.freedesktop.portal.RemoteDesktop.Start", 0, sessionHandle, "", map[string]dbus.Variant{})
if res.Err != nil {
log.Error("Error starting session: %s", res.Err.Error())
}
state = 2
case 2:
log.Info("Performing Typing")
time.Sleep(1000 * time.Millisecond)
for _, char := range textToType {
if char == '\t' {
obj.Call("org.freedesktop.portal.RemoteDesktop.NotifyKeyboardKeycode", 0, sessionHandle, map[string]dbus.Variant{}, 15, uint32(1))
time.Sleep(autoTypeDelay)
obj.Call("org.freedesktop.portal.RemoteDesktop.NotifyKeyboardKeycode", 0, sessionHandle, map[string]dbus.Variant{}, 15, uint32(0))
time.Sleep(autoTypeDelay)
} else {
obj.Call("org.freedesktop.portal.RemoteDesktop.NotifyKeyboardKeysym", 0, sessionHandle, map[string]dbus.Variant{}, int32(char), uint32(1))
time.Sleep(autoTypeDelay)
obj.Call("org.freedesktop.portal.RemoteDesktop.NotifyKeyboardKeysym", 0, sessionHandle, map[string]dbus.Variant{}, int32(char), uint32(0))
time.Sleep(autoTypeDelay)
}
bus.Close()
return
} else {
log.Info("State 3")
return
}
bus.Close()
return
default:
return
}
}
}
41 changes: 24 additions & 17 deletions browserbiometrics/communication.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"os"
"unsafe"

Expand All @@ -25,44 +26,50 @@ func setupCommunication() {
}
}

func dataToBytes(msg SendMessage) []byte {
func dataToBytes(msg SendMessage) ([]byte, error) {
byteMsg, err := json.Marshal(msg)
if err != nil {
logging.Panicf("Unable to marshal OutgoingMessage struct to slice of bytes: " + err.Error())
return nil, fmt.Errorf("unable to marshal OutgoingMessage struct to slice of bytes: %w", err)
}
return byteMsg
return byteMsg, nil
}

func writeMessageLength(msg []byte) {
func writeMessageLength(msg []byte) error {
err := binary.Write(os.Stdout, nativeEndian, uint32(len(msg)))
if err != nil {
logging.Panicf("Unable to write message length to Stdout: " + err.Error())
return fmt.Errorf("unable to write message length to stdout: %w", err)
}
return nil
}

func readMessageLength(msg []byte) int {
var length uint32
func readMessageLength(msg []byte) (int, error) {
var length int
buf := bytes.NewBuffer(msg)
err := binary.Read(buf, nativeEndian, &length)
if err != nil {
logging.Panicf("Unable to read bytes representing message length:" + err.Error())
return 0, fmt.Errorf("Unable to read bytes representing message length: %w", err)
}
return int(length)
return length, nil
}

func send(msg SendMessage) {
byteMsg := dataToBytes(msg)
func send(msg SendMessage) error {
byteMsg, err := dataToBytes(msg)
if err != nil {
return err
}

logging.Debugf("[SENSITIVE] Sending message: " + string(byteMsg))
writeMessageLength(byteMsg)
err = writeMessageLength(byteMsg)
if err != nil {
return err
}

var msgBuf bytes.Buffer
_, err := msgBuf.Write(byteMsg)
_, err = msgBuf.Write(byteMsg)
if err != nil {
logging.Panicf(err.Error())
return err
}

_, err = msgBuf.WriteTo(os.Stdout)
if err != nil {
logging.Panicf(err.Error())
}
return err
}
24 changes: 12 additions & 12 deletions browserbiometrics/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func pkcs7Pad(b []byte, blocksize int) ([]byte, error) {
if blocksize <= 0 {
return nil, ErrInvalidBlockSize
}
if b == nil || len(b) == 0 {
if len(b) == 0 {
return nil, ErrInvalidPKCS7Data
}
n := blocksize - (len(b) % blocksize)
Expand All @@ -37,7 +37,7 @@ func pkcs7Unpad(b []byte, blocksize int) ([]byte, error) {
if blocksize <= 0 {
return nil, ErrInvalidBlockSize
}
if b == nil || len(b) == 0 {
if len(b) == 0 {
return nil, ErrInvalidPKCS7Data
}
if len(b)%blocksize != 0 {
Expand All @@ -56,30 +56,30 @@ func pkcs7Unpad(b []byte, blocksize int) ([]byte, error) {
return b[:len(b)-n], nil
}

func decryptStringSymmetric(key []byte, ivb64 string, data string) string {
func decryptStringSymmetric(key []byte, ivb64 string, data string) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
return "", err
}
iv, _ := base64.StdEncoding.DecodeString(ivb64)
ciphertext, _ := base64.StdEncoding.DecodeString(data)
bm := cipher.NewCBCDecrypter(block, iv)
bm.CryptBlocks(ciphertext, ciphertext)
ciphertext, _ = pkcs7Unpad(ciphertext, aes.BlockSize)

return string(ciphertext)
return string(ciphertext), nil
}

func encryptStringSymmetric(key []byte, data []byte) EncryptedString {
func encryptStringSymmetric(key []byte, data []byte) (EncryptedString, error) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
return EncryptedString{}, err
}
data, _ = pkcs7Pad(data, block.BlockSize())
ciphertext := make([]byte, aes.BlockSize+len(data))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
return EncryptedString{}, err
}
bm := cipher.NewCBCEncrypter(block, iv)
bm.CryptBlocks(ciphertext[aes.BlockSize:], data)
Expand All @@ -88,15 +88,15 @@ func encryptStringSymmetric(key []byte, data []byte) EncryptedString {
IV: base64.StdEncoding.EncodeToString(ciphertext[:aes.BlockSize]),
Data: base64.StdEncoding.EncodeToString(ciphertext[aes.BlockSize:]),
EncType: 0,
}
}, nil
}

func generateTransportKey() []byte {
func generateTransportKey() ([]byte, error) {
key := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
panic(err)
return nil, err
}
return key
return key, nil
}

func rsaEncrypt(keyB64 string, message []byte) (string, error) {
Expand Down
10 changes: 7 additions & 3 deletions browserbiometrics/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,17 @@ const appID = "com.quexten.bw-bio-handler"

var transportKey []byte

func Main(rtCfg *config.RuntimeConfig) {
func Main(rtCfg *config.RuntimeConfig) error {
logging.Debugf("Starting browserbiometrics")
transportKey = generateTransportKey()
var err error
transportKey, err = generateTransportKey()
if err != nil {
return err
}
logging.Debugf("Generated transport key")

setupCommunication()
readLoop(rtCfg)
return readLoop(rtCfg)
}

func DetectAndInstallBrowsers() error {
Expand Down
Loading

0 comments on commit 6ac5754

Please sign in to comment.