diff options
| -rw-r--r-- | cmd/eno/cobra.go | 223 | ||||
| -rw-r--r-- | internal/config/config.go | 194 | ||||
| -rw-r--r-- | internal/config/config_file.go | 47 | ||||
| -rw-r--r-- | internal/config/config_ops.go | 163 | ||||
| -rw-r--r-- | internal/crud/cli_edit.go | 24 | ||||
| -rw-r--r-- | internal/crud/cli_new_pass.go | 161 | ||||
| -rw-r--r-- | internal/crud/cli_new_ssh.go (renamed from internal/crud/cli_new.go) | 160 | ||||
| -rw-r--r-- | internal/crypt/headers.go | 33 | ||||
| -rw-r--r-- | internal/crypt/raw_decrypt.go (renamed from internal/crypt/rawDecrypt.go) | 73 | ||||
| -rw-r--r-- | internal/crypt/raw_encrypt.go (renamed from internal/crypt/rawEncrypt.go) | 0 | ||||
| -rw-r--r-- | internal/crypt/ssh_key.go (renamed from internal/crypt/sshKey.go) | 32 | ||||
| -rw-r--r-- | internal/crypt/ssh_key_io.go | 39 | ||||
| -rw-r--r-- | internal/utils/utils.go | 24 |
13 files changed, 453 insertions, 720 deletions
diff --git a/cmd/eno/cobra.go b/cmd/eno/cobra.go index 93cba8b..7283df1 100644 --- a/cmd/eno/cobra.go +++ b/cmd/eno/cobra.go @@ -1,16 +1,10 @@ package main import ( - "fmt" "os" - "path/filepath" - "strings" "github.com/spf13/cobra" "gitlab.com/whiteboardguy/eno/internal/config" - "gitlab.com/whiteboardguy/eno/internal/crud" - "gitlab.com/whiteboardguy/eno/internal/crypt" - "gitlab.com/whiteboardguy/eno/internal/utils" ) var cobraCmd = &cobra.Command{ @@ -18,173 +12,6 @@ var cobraCmd = &cobra.Command{ Short: "file encryption tool", } -var encryptCmd = &cobra.Command{ - Use: "encrypt <file>", - Short: "encrypt a file", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - output, err := cmd.Flags().GetString("output") - if err != nil { - return fmt.Errorf("failed to get output flag: %v", err) - } - - if output == "" { - output = args[0] + ".eno" - } - - if _, err := os.Stat(output); err == nil { - ok, err := utils.AskUserYesNo("file '"+output+"' already exists. Overwrite?", false) - if err != nil { - return err - } - if !ok { - return fmt.Errorf("write aborted") - } - } - - fileBytes, err := os.ReadFile(args[0]) - if err != nil { - return fmt.Errorf("failed to read input file: %v", err) - } - crypt.TryMlock(fileBytes) - defer clear(fileBytes) - - sshFlag, err := cmd.Flags().GetBool("ssh") - if err != nil { - return fmt.Errorf("failed to get ssh flag: %v", err) - } - - if sshFlag { - if config.Conf.DefaultSSHPubPath == "" { - return fmt.Errorf("SSH not configured. Run 'eno ssh init' first") - } - defaultPubKeyBytes, err := os.ReadFile(config.Conf.DefaultSSHPubPath) - if err != nil { - return fmt.Errorf("failed to read default SSH public key: %v", err) - } - pubKeys, _, err := crud.PromptRecipientKeys(defaultPubKeyBytes) - if err != nil { - return err - } - if len(pubKeys) == 0 { - return fmt.Errorf("at least one recipient public key is required") - } - encrypted, _, err := crypt.EncryptBytesSSH(fileBytes, pubKeys) - if err != nil { - clear(fileBytes) - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - - if err := os.WriteFile(output, encrypted, 0600); err != nil { - return fmt.Errorf("failed to write output file: %v", err) - } - - return nil - } - - fmt.Printf("Enter a passphrase: ") - password, err := utils.TakeSecureUserInput() - if err != nil { - return fmt.Errorf("failed to read passphrase: %v", err) - } - crypt.TryMlock(password) - defer clear(password) - - encrypted, err := crypt.EncryptBytesPass(fileBytes, password) - if err != nil { - clear(fileBytes) - clear(password) - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - - if err := os.WriteFile(output, encrypted, 0600); err != nil { - return fmt.Errorf("failed to write output file: %v", err) - } - - return nil - }, -} - -var decryptCmd = &cobra.Command{ - Use: "decrypt <file>", - Short: "decrypt a file", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - output, err := cmd.Flags().GetString("output") - if err != nil { - return fmt.Errorf("failed to get output flag: %v", err) - } - - if output == "" { - output = strings.TrimSuffix(args[0], ".eno") - } - - if _, err := os.Stat(output); err == nil { - ok, err := utils.AskUserYesNo("file '"+output+"' already exists. Overwrite?", false) - if err != nil { - return err - } - if !ok { - return fmt.Errorf("write aborted") - } - } - - fileBytes, err := os.ReadFile(args[0]) - if err != nil { - return fmt.Errorf("failed to read input file: %v", err) - } - - authMode, err := utils.CheckFileAuthMode(args[0]) - if err != nil { - return fmt.Errorf("failed to check auth mode: %v", err) - } - - if authMode == crypt.SSH { - if config.Conf.DefaultSSHPrivPath == "" { - return fmt.Errorf("SSH not configured. Run 'eno ssh init' first") - } - plaintext, err := crypt.DecryptBytesSSH(fileBytes, config.Conf.DefaultSSHPrivPath) - if err != nil { - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - crypt.TryMlock(plaintext) - defer clear(plaintext) - - if err := os.WriteFile(output, plaintext, 0600); err != nil { - return fmt.Errorf("failed to write output file: %v", err) - } - - return nil - } - - fmt.Printf("Enter the passphrase: ") - password, err := utils.TakeSecureUserInput() - if err != nil { - return fmt.Errorf("failed to read passphrase: %v", err) - } - crypt.TryMlock(password) - defer clear(password) - - plaintext, err := crypt.DecryptBytesPass(fileBytes, password) - if err != nil { - clear(password) - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - crypt.TryMlock(plaintext) - defer clear(plaintext) - - if err := os.WriteFile(output, plaintext, 0600); err != nil { - return fmt.Errorf("failed to write output file: %v", err) - } - - return nil - }, -} - var initCmd = &cobra.Command{ Use: "init", Short: "intialize Eno config", @@ -200,56 +27,6 @@ var initCmd = &cobra.Command{ }, } -var editCmd = &cobra.Command{ - Use: "edit <note>", - Short: "edit an existing encrypted note", - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { - - target := filepath.Clean(args[0]) - - ok, err := utils.AskUserYesNo("Edit "+target+" ?", true) - if err != nil { - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - if !ok { - cmd.PrintErrln("Error: write aborted") - os.Exit(1) - } - - target = strings.TrimSuffix(target, ".eno") - target += ".eno" - - if _, err := os.Stat(target); os.IsNotExist(err) { - alt := filepath.Join(config.Conf.DataDir, target) - if _, err2 := os.Stat(alt); err2 == nil { - target = alt - } - } - - authMode, err := utils.CheckFileAuthMode(target) - if err != nil { - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - - switch authMode { - case crypt.SSH: - err = crud.EditNoteSSH(target, config.Conf.DefaultSSHPrivPath, config.Conf.EditorString) - case crypt.Pass: - err = crud.EditNotePass(target, config.Conf.EditorString) - default: - cmd.PrintErrln("Error: unknown auth mode:", authMode) - os.Exit(1) - } - if err != nil { - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - }, -} - func init() { encryptCmd.Flags().StringP("output", "o", "", "output file (required)") encryptCmd.Flags().Bool("ssh", false, "encrypt using SSH public keys (interactive)") diff --git a/internal/config/config.go b/internal/config/config.go index baf50c6..5e5fcf9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -6,7 +6,6 @@ import ( "fmt" "os" "path/filepath" - "sort" "strconv" "strings" ) @@ -167,196 +166,3 @@ func init() { configKeyField[key] = field } } - -func Set(key, value string) error { - key = strings.ToUpper(key) - field, ok := configKeyField[key] - if !ok { - return fmt.Errorf("unknown config key: %s", key) - } - - switch field { - case "PubkeyServices": - Conf.PubkeyServices = ParsePubkeyServices(value) - lines, err := readConfigLines() - if err != nil { - return err - } - return writeConfigLines(replaceOrAppend(lines, key, value)) - case "SSHInitialized": - b, err := strconv.ParseBool(value) - if err != nil { - return fmt.Errorf("SSH_INIT must be true or false: %w", err) - } - return Update(field, b) - default: - return Update(field, value) - } -} - -func Get(key string) (string, error) { - key = strings.ToUpper(key) - field, ok := configKeyField[key] - if !ok { - return "", fmt.Errorf("unknown config key: %s", key) - } - - switch field { - case "EditorString": - return Conf.EditorString, nil - case "DataDir": - return Conf.DataDir, nil - case "DefaultSSHPrivPath": - return Conf.DefaultSSHPrivPath, nil - case "DefaultSSHPubPath": - return Conf.DefaultSSHPubPath, nil - case "SSHInitialized": - return strconv.FormatBool(Conf.SSHInitialized), nil - case "PubkeyServices": - return SerializePubkeyServices(Conf.PubkeyServices), nil - default: - return "", fmt.Errorf("unknown config key: %s", key) - } -} - -func Remove(key string) error { - key = strings.ToUpper(key) - _, ok := configKeyField[key] - if !ok { - return fmt.Errorf("unknown config key: %s", key) - } - - lines, err := readConfigLines() - if err != nil { - return err - } - - filtered := make([]string, 0, len(lines)) - for _, line := range lines { - trimmed := strings.TrimSpace(line) - if trimmed == "" || strings.HasPrefix(trimmed, "#") { - filtered = append(filtered, line) - continue - } - k, _, ok := strings.Cut(trimmed, "=") - if ok && strings.TrimSpace(k) == key { - continue - } - filtered = append(filtered, line) - } - - if err := writeConfigLines(filtered); err != nil { - return err - } - return Init() -} - -func readConfigLines() ([]string, error) { - data, err := os.ReadFile(Conf.ConfPath) - if err != nil { - if errors.Is(err, os.ErrNotExist) { - return nil, nil - } - return nil, fmt.Errorf("reading config: %w", err) - } - return strings.Split(string(data), "\n"), nil -} - -func replaceOrAppend(lines []string, key, value string) []string { - newLine := fmt.Sprintf("%s=%s", key, value) - found := false - - for i, line := range lines { - trimmed := strings.TrimSpace(line) - if trimmed == "" || strings.HasPrefix(trimmed, "#") { - continue - } - k, _, ok := strings.Cut(trimmed, "=") - if ok && strings.TrimSpace(k) == key { - lines[i] = newLine - found = true - break - } - } - - if !found { - lines = append(lines, newLine) - } - return lines -} - -func writeConfigLines(lines []string) error { - content := strings.Join(lines, "\n") - return os.WriteFile(Conf.ConfPath, []byte(content), 0600) -} - -func List() []string { - keys := make([]string, 0, len(configKeyField)) - for k := range configKeyField { - keys = append(keys, k) - } - sort.Strings(keys) - - result := make([]string, 0, len(keys)) - for _, key := range keys { - val, err := Get(key) - if err != nil { - continue - } - result = append(result, fmt.Sprintf("%s=%s", key, val)) - } - return result -} - -func Update(key string, val any) error { - configKey, ok := configFieldKey[key] - if !ok { - return fmt.Errorf("unknown config field: %s", key) - } - - var valStr string - switch v := val.(type) { - case bool: - valStr = strconv.FormatBool(v) - case string: - valStr = v - default: - valStr = fmt.Sprintf("%v", v) - } - - data, err := os.ReadFile(Conf.ConfPath) - if err != nil { - return fmt.Errorf("reading config: %w", err) - } - - lines := strings.Split(string(data), "\n") - newLine := fmt.Sprintf("%s=%s", configKey, valStr) - found := false - - for i, line := range lines { - trimmed := strings.TrimSpace(line) - if trimmed == "" || strings.HasPrefix(trimmed, "#") { - continue - } - k, _, ok := strings.Cut(trimmed, "=") - if !ok { - continue - } - if strings.TrimSpace(k) == configKey { - lines[i] = newLine - found = true - break - } - } - - if !found { - lines = append(lines, newLine) - } - - err = os.WriteFile(Conf.ConfPath, []byte(strings.Join(lines, "\n")), 0600) - if err != nil { - return err - } - - return Init() -} diff --git a/internal/config/config_file.go b/internal/config/config_file.go new file mode 100644 index 0000000..31045f8 --- /dev/null +++ b/internal/config/config_file.go @@ -0,0 +1,47 @@ +package config + +import ( + "errors" + "fmt" + "os" + "strings" +) + +func readConfigLines() ([]string, error) { + data, err := os.ReadFile(Conf.ConfPath) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + return nil, fmt.Errorf("reading config: %w", err) + } + return strings.Split(string(data), "\n"), nil +} + +func replaceOrAppend(lines []string, key, value string) []string { + newLine := fmt.Sprintf("%s=%s", key, value) + found := false + + for i, line := range lines { + trimmed := strings.TrimSpace(line) + if trimmed == "" || strings.HasPrefix(trimmed, "#") { + continue + } + k, _, ok := strings.Cut(trimmed, "=") + if ok && strings.TrimSpace(k) == key { + lines[i] = newLine + found = true + break + } + } + + if !found { + lines = append(lines, newLine) + } + return lines +} + +func writeConfigLines(lines []string) error { + content := strings.Join(lines, "\n") + return os.WriteFile(Conf.ConfPath, []byte(content), 0600) +} diff --git a/internal/config/config_ops.go b/internal/config/config_ops.go new file mode 100644 index 0000000..06966f7 --- /dev/null +++ b/internal/config/config_ops.go @@ -0,0 +1,163 @@ +package config + +import ( + "fmt" + "os" + "sort" + "strconv" + "strings" +) + +func Set(key, value string) error { + key = strings.ToUpper(key) + field, ok := configKeyField[key] + if !ok { + return fmt.Errorf("unknown config key: %s", key) + } + + switch field { + case "PubkeyServices": + Conf.PubkeyServices = ParsePubkeyServices(value) + lines, err := readConfigLines() + if err != nil { + return err + } + return writeConfigLines(replaceOrAppend(lines, key, value)) + case "SSHInitialized": + b, err := strconv.ParseBool(value) + if err != nil { + return fmt.Errorf("SSH_INIT must be true or false: %w", err) + } + return Update(field, b) + default: + return Update(field, value) + } +} + +func Get(key string) (string, error) { + key = strings.ToUpper(key) + field, ok := configKeyField[key] + if !ok { + return "", fmt.Errorf("unknown config key: %s", key) + } + + switch field { + case "EditorString": + return Conf.EditorString, nil + case "DataDir": + return Conf.DataDir, nil + case "DefaultSSHPrivPath": + return Conf.DefaultSSHPrivPath, nil + case "DefaultSSHPubPath": + return Conf.DefaultSSHPubPath, nil + case "SSHInitialized": + return strconv.FormatBool(Conf.SSHInitialized), nil + case "PubkeyServices": + return SerializePubkeyServices(Conf.PubkeyServices), nil + default: + return "", fmt.Errorf("unknown config key: %s", key) + } +} + +func Remove(key string) error { + key = strings.ToUpper(key) + _, ok := configKeyField[key] + if !ok { + return fmt.Errorf("unknown config key: %s", key) + } + + lines, err := readConfigLines() + if err != nil { + return err + } + + filtered := make([]string, 0, len(lines)) + for _, line := range lines { + trimmed := strings.TrimSpace(line) + if trimmed == "" || strings.HasPrefix(trimmed, "#") { + filtered = append(filtered, line) + continue + } + k, _, ok := strings.Cut(trimmed, "=") + if ok && strings.TrimSpace(k) == key { + continue + } + filtered = append(filtered, line) + } + + if err := writeConfigLines(filtered); err != nil { + return err + } + return Init() +} + +func List() []string { + keys := make([]string, 0, len(configKeyField)) + for k := range configKeyField { + keys = append(keys, k) + } + sort.Strings(keys) + + result := make([]string, 0, len(keys)) + for _, key := range keys { + val, err := Get(key) + if err != nil { + continue + } + result = append(result, fmt.Sprintf("%s=%s", key, val)) + } + return result +} + +func Update(key string, val any) error { + configKey, ok := configFieldKey[key] + if !ok { + return fmt.Errorf("unknown config field: %s", key) + } + + var valStr string + switch v := val.(type) { + case bool: + valStr = strconv.FormatBool(v) + case string: + valStr = v + default: + valStr = fmt.Sprintf("%v", v) + } + + data, err := os.ReadFile(Conf.ConfPath) + if err != nil { + return fmt.Errorf("reading config: %w", err) + } + + lines := strings.Split(string(data), "\n") + newLine := fmt.Sprintf("%s=%s", configKey, valStr) + found := false + + for i, line := range lines { + trimmed := strings.TrimSpace(line) + if trimmed == "" || strings.HasPrefix(trimmed, "#") { + continue + } + k, _, ok := strings.Cut(trimmed, "=") + if !ok { + continue + } + if strings.TrimSpace(k) == configKey { + lines[i] = newLine + found = true + break + } + } + + if !found { + lines = append(lines, newLine) + } + + err = os.WriteFile(Conf.ConfPath, []byte(strings.Join(lines, "\n")), 0600) + if err != nil { + return err + } + + return Init() +} diff --git a/internal/crud/cli_edit.go b/internal/crud/cli_edit.go index 50bb8d2..0683439 100644 --- a/internal/crud/cli_edit.go +++ b/internal/crud/cli_edit.go @@ -3,7 +3,6 @@ package crud import ( "fmt" "os" - "strconv" "gitlab.com/whiteboardguy/eno/internal/crypt" "gitlab.com/whiteboardguy/eno/internal/editor" @@ -90,28 +89,7 @@ func EditNoteSSH(notePath, privKeyPath, editorString string) error { return err } - idx := -1 - for i, b := range ciphertext { - if b == ':' { - idx = i - break - } - } - if idx == -1 { - return fmt.Errorf("invalid file format: no header length prefix found") - } - - headerLen, err := strconv.Atoi(string(ciphertext[:idx])) - if err != nil { - return fmt.Errorf("failed to parse header length: %v", err) - } - - if headerLen < 0 || idx+1+headerLen > len(ciphertext) { - return fmt.Errorf("invalid header length %d", headerLen) - } - - headerBytes := ciphertext[idx+1 : idx+1+headerLen] - headers, err := crypt.GetFileHeaders(headerBytes) + headers, _, err := crypt.ParseFileHeaders(ciphertext) if err != nil { return fmt.Errorf("failed to read file headers: %v", err) } diff --git a/internal/crud/cli_new_pass.go b/internal/crud/cli_new_pass.go new file mode 100644 index 0000000..c18ddc6 --- /dev/null +++ b/internal/crud/cli_new_pass.go @@ -0,0 +1,161 @@ +package crud + +import ( + "bytes" + "fmt" + "os" + + "gitlab.com/whiteboardguy/eno/internal/crypt" + "gitlab.com/whiteboardguy/eno/internal/editor" + "gitlab.com/whiteboardguy/eno/internal/utils" +) + +func NewNotePass(output string) error { + fmt.Printf("Enter the passphrase: ") + password, err := utils.TakeSecureUserInput() + if err != nil { + return fmt.Errorf("failed to read passphrase: %v", err) + } + crypt.TryMlock(password) + defer clear(password) + + fmt.Printf("Confirm the passphrase: ") + passwordConfirm, err := utils.TakeSecureUserInput() + if err != nil { + return fmt.Errorf("failed to read passphrase: %v", err) + } + crypt.TryMlock(passwordConfirm) + defer clear(passwordConfirm) + + if !bytes.Equal(password, passwordConfirm) { + return fmt.Errorf("passphrases do not match") + } + + encrypted, err := crypt.EncryptBytesPass( + append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...), + password, + ) + if err != nil { + return err + } + + fmt.Println(output) + file, err := os.OpenFile(output, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) + if err != nil { + return err + } + defer file.Close() + + _, err = file.Write(encrypted) + if err != nil { + return err + } + + file.Sync() + + // utils.ClearTerm() + fmt.Println("New note saved at:", file.Name()) + + return nil +} + +func NewNotePassEdit(output, editorString string) error { + fmt.Printf("Enter the passphrase: ") + password, err := utils.TakeSecureUserInput() + if err != nil { + return fmt.Errorf("failed to read passphrase: %v", err) + } + crypt.TryMlock(password) + defer clear(password) + + fmt.Printf("Confirm the passphrase: ") + passwordConfirm, err := utils.TakeSecureUserInput() + if err != nil { + return fmt.Errorf("failed to read passphrase: %v", err) + } + crypt.TryMlock(passwordConfirm) + defer clear(passwordConfirm) + + if !bytes.Equal(password, passwordConfirm) { + return fmt.Errorf("passphrases do not match") + } + + noteInfo, err := os.Stat(output) + preExisting := err == nil + + initialContent := append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...) + encrypted, err := crypt.EncryptBytesPass(initialContent, password) + if err != nil { + return err + } + + file, err := os.OpenFile(output, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) + if err != nil { + return err + } + + _, err = file.Write(encrypted) + if err != nil { + return err + } + + file.Sync() + file.Close() + + ciphertext, err := os.ReadFile(output) + if err != nil { + return err + } + + tmpFile, err := utils.SecureTempFile() + if err != nil { + return err + } + + plaintext, err := crypt.DecryptBytesPass(ciphertext, password) + if err != nil { + return err + } + crypt.TryMlock(plaintext) + defer clear(plaintext) + + defer deferredCleanTmpFile(tmpFile, len(plaintext)) + defer os.Remove(tmpFile.Name()) + + _, err = tmpFile.Write(plaintext) + if err != nil { + return err + } + + err = editor.OpenWithEditor(tmpFile.Name(), editorString) + if err != nil { + return err + } + + newContent, err := os.ReadFile(tmpFile.Name()) + if err != nil { + return err + } + crypt.TryMlock(newContent) + defer clear(newContent) + + if err := os.WriteFile(tmpFile.Name(), make([]byte, len(newContent)), 0600); err != nil { + fmt.Fprintf(os.Stderr, "warning: failed to wipe temp file %s: %v\n", tmpFile.Name(), err) + } + + encrypted, err = crypt.EncryptBytesPass(newContent, password) + if err != nil { + return err + } + + perm := os.FileMode(0600) + if preExisting { + perm = noteInfo.Mode().Perm() + } + + err = os.WriteFile(output, encrypted, perm) + + fmt.Println("New note saved at:", output) + + return err +} diff --git a/internal/crud/cli_new.go b/internal/crud/cli_new_ssh.go index 8e56490..5479490 100644 --- a/internal/crud/cli_new.go +++ b/internal/crud/cli_new_ssh.go @@ -11,156 +11,6 @@ import ( "gitlab.com/whiteboardguy/eno/internal/utils" ) -func NewNotePass(output string) error { - fmt.Printf("Enter the passphrase: ") - password, err := utils.TakeSecureUserInput() - if err != nil { - return fmt.Errorf("failed to read passphrase: %v", err) - } - crypt.TryMlock(password) - defer clear(password) - - fmt.Printf("Confirm the passphrase: ") - passwordConfirm, err := utils.TakeSecureUserInput() - if err != nil { - return fmt.Errorf("failed to read passphrase: %v", err) - } - crypt.TryMlock(passwordConfirm) - defer clear(passwordConfirm) - - if !bytes.Equal(password, passwordConfirm) { - return fmt.Errorf("passphrases do not match") - } - - encrypted, err := crypt.EncryptBytesPass( - append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...), - password, - ) - if err != nil { - return err - } - - fmt.Println(output) - file, err := os.OpenFile(output, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) - if err != nil { - return err - } - defer file.Close() - - _, err = file.Write(encrypted) - if err != nil { - return err - } - - file.Sync() - - // utils.ClearTerm() - fmt.Println("New note saved at:", file.Name()) - - return nil -} - -func NewNotePassEdit(output, editorString string) error { - fmt.Printf("Enter the passphrase: ") - password, err := utils.TakeSecureUserInput() - if err != nil { - return fmt.Errorf("failed to read passphrase: %v", err) - } - crypt.TryMlock(password) - defer clear(password) - - fmt.Printf("Confirm the passphrase: ") - passwordConfirm, err := utils.TakeSecureUserInput() - if err != nil { - return fmt.Errorf("failed to read passphrase: %v", err) - } - crypt.TryMlock(passwordConfirm) - defer clear(passwordConfirm) - - if !bytes.Equal(password, passwordConfirm) { - return fmt.Errorf("passphrases do not match") - } - - noteInfo, err := os.Stat(output) - preExisting := err == nil - - initialContent := append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...) - encrypted, err := crypt.EncryptBytesPass(initialContent, password) - if err != nil { - return err - } - - file, err := os.OpenFile(output, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) - if err != nil { - return err - } - - _, err = file.Write(encrypted) - if err != nil { - return err - } - - file.Sync() - file.Close() - - ciphertext, err := os.ReadFile(output) - if err != nil { - return err - } - - tmpFile, err := utils.SecureTempFile() - if err != nil { - return err - } - - plaintext, err := crypt.DecryptBytesPass(ciphertext, password) - if err != nil { - return err - } - crypt.TryMlock(plaintext) - defer clear(plaintext) - - defer deferredCleanTmpFile(tmpFile, len(plaintext)) - defer os.Remove(tmpFile.Name()) - - _, err = tmpFile.Write(plaintext) - if err != nil { - return err - } - - err = editor.OpenWithEditor(tmpFile.Name(), editorString) - if err != nil { - return err - } - - newContent, err := os.ReadFile(tmpFile.Name()) - if err != nil { - return err - } - crypt.TryMlock(newContent) - defer clear(newContent) - - if err := os.WriteFile(tmpFile.Name(), make([]byte, len(newContent)), 0600); err != nil { - fmt.Fprintf(os.Stderr, "warning: failed to wipe temp file %s: %v\n", tmpFile.Name(), err) - } - - encrypted, err = crypt.EncryptBytesPass(newContent, password) - if err != nil { - return err - } - - perm := os.FileMode(0600) - if preExisting { - perm = noteInfo.Mode().Perm() - } - - err = os.WriteFile(output, encrypted, perm) - - fmt.Println("New note saved at:", output) - - return err -} - func PromptRecipientKeys(defaultPubKeyBytes []byte) ([][]byte, bool, error) { useDefault, err := utils.AskUserYesNo("Do you want to encrypt the note with your own default Public Key?", true) if err != nil { @@ -214,11 +64,11 @@ func PromptRecipientKeys(defaultPubKeyBytes []byte) ([][]byte, bool, error) { if err != nil { return nil, false, fmt.Errorf("failed to get public key from %s: %v", part, err) } - selectedKeys, err := selectServiceKeys(part, body) - if err != nil { - fmt.Printf("Warning: %s: %v\n", service, err) - continue - } + selectedKeys, err := selectServiceKeys(part, body) + if err != nil { + fmt.Printf("Warning: %s: %v\n", service, err) + continue + } for _, k := range selectedKeys { pubKeys = append(pubKeys, bytes.TrimSpace(k)) } diff --git a/internal/crypt/headers.go b/internal/crypt/headers.go index 8f9dac2..c47d39c 100644 --- a/internal/crypt/headers.go +++ b/internal/crypt/headers.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/gob" "fmt" + "strconv" ) type DataType string @@ -55,3 +56,35 @@ func FileHeadersBytes(headers FileHeaders) ([]byte, error) { return buf.Bytes(), nil } + +func ParseFileHeaders(data []byte) (FileHeaders, []byte, error) { + idx := -1 + for i, b := range data { + if b == ':' { + idx = i + break + } + } + if idx == -1 { + return FileHeaders{}, nil, fmt.Errorf("invalid file format: no header length prefix found") + } + + headerLen, err := strconv.Atoi(string(data[:idx])) + if err != nil { + return FileHeaders{}, nil, fmt.Errorf("failed to parse header length: %w", err) + } + + if headerLen <= 0 || idx+1+headerLen > len(data) { + return FileHeaders{}, nil, fmt.Errorf("invalid header length %d", headerLen) + } + + headerBytes := data[idx+1 : idx+1+headerLen] + headers, err := GetFileHeaders(headerBytes) + if err != nil { + return FileHeaders{}, nil, fmt.Errorf("failed to decode headers: %w", err) + } + + ciphertext := data[idx+1+headerLen:] + + return headers, ciphertext, nil +} diff --git a/internal/crypt/rawDecrypt.go b/internal/crypt/raw_decrypt.go index ede063c..050a4ec 100644 --- a/internal/crypt/rawDecrypt.go +++ b/internal/crypt/raw_decrypt.go @@ -2,35 +2,13 @@ package crypt import ( "fmt" - "strconv" "golang.org/x/crypto/argon2" "golang.org/x/crypto/chacha20poly1305" ) func DecryptBytesPass(inputBytes []byte, password []byte) ([]byte, error) { - idx := -1 - for i, b := range inputBytes { - if b == ':' { - idx = i - break - } - } - if idx == -1 { - return nil, fmt.Errorf("decrypt: invalid file format: no header length prefix found") - } - - headerLen, err := strconv.Atoi(string(inputBytes[:idx])) - if err != nil { - return nil, fmt.Errorf("decrypt: failed to parse header length: %w", err) - } - - if headerLen <= 0 || idx+1+headerLen > len(inputBytes) { - return nil, fmt.Errorf("decrypt: invalid header length %d", headerLen) - } - - headerBytes := inputBytes[idx+1 : idx+1+headerLen] - headers, err := GetFileHeaders(headerBytes) + headers, ciphertext, err := ParseFileHeaders(inputBytes) if err != nil { return nil, fmt.Errorf("decrypt: %w", err) } @@ -47,7 +25,6 @@ func DecryptBytesPass(inputBytes []byte, password []byte) ([]byte, error) { return nil, fmt.Errorf("decrypt: failed to create cipher: %w", err) } - ciphertext := inputBytes[idx+1+headerLen:] plaintext, err := aead.Open(nil, headers.Nonce[:], ciphertext, nil) if err != nil { return nil, fmt.Errorf("decrypt: %w", err) @@ -57,28 +34,7 @@ func DecryptBytesPass(inputBytes []byte, password []byte) ([]byte, error) { } func DecryptBytesSSH(inputBytes []byte, privKeyPath string) ([]byte, error) { - idx := -1 - for i, b := range inputBytes { - if b == ':' { - idx = i - break - } - } - if idx == -1 { - return nil, fmt.Errorf("decrypt: invalid file format: no header length prefix found") - } - - headerLen, err := strconv.Atoi(string(inputBytes[:idx])) - if err != nil { - return nil, fmt.Errorf("decrypt: failed to parse header length: %w", err) - } - - if headerLen <= 0 || idx+1+headerLen > len(inputBytes) { - return nil, fmt.Errorf("decrypt: invalid header length %d", headerLen) - } - - headerBytes := inputBytes[idx+1 : idx+1+headerLen] - headers, err := GetFileHeaders(headerBytes) + headers, ciphertext, err := ParseFileHeaders(inputBytes) if err != nil { return nil, fmt.Errorf("decrypt: %w", err) } @@ -111,7 +67,6 @@ func DecryptBytesSSH(inputBytes []byte, privKeyPath string) ([]byte, error) { return nil, fmt.Errorf("decrypt: failed to create cipher: %w", err) } - ciphertext := inputBytes[idx+1+headerLen:] plaintext, err := aead.Open(nil, headers.Nonce[:], ciphertext, nil) if err != nil { return nil, fmt.Errorf("decrypt: %w", err) @@ -121,28 +76,7 @@ func DecryptBytesSSH(inputBytes []byte, privKeyPath string) ([]byte, error) { } func DecryptBytesSSHWithKey(inputBytes []byte, noteKey []byte) ([]byte, error) { - idx := -1 - for i, b := range inputBytes { - if b == ':' { - idx = i - break - } - } - if idx == -1 { - return nil, fmt.Errorf("decrypt: invalid file format: no header length prefix found") - } - - headerLen, err := strconv.Atoi(string(inputBytes[:idx])) - if err != nil { - return nil, fmt.Errorf("decrypt: failed to parse header length: %w", err) - } - - if headerLen <= 0 || idx+1+headerLen > len(inputBytes) { - return nil, fmt.Errorf("decrypt: invalid header length %d", headerLen) - } - - headerBytes := inputBytes[idx+1 : idx+1+headerLen] - headers, err := GetFileHeaders(headerBytes) + headers, ciphertext, err := ParseFileHeaders(inputBytes) if err != nil { return nil, fmt.Errorf("decrypt: %w", err) } @@ -156,7 +90,6 @@ func DecryptBytesSSHWithKey(inputBytes []byte, noteKey []byte) ([]byte, error) { return nil, fmt.Errorf("decrypt: failed to create cipher: %w", err) } - ciphertext := inputBytes[idx+1+headerLen:] plaintext, err := aead.Open(nil, headers.Nonce[:], ciphertext, nil) if err != nil { return nil, fmt.Errorf("decrypt: %w", err) diff --git a/internal/crypt/rawEncrypt.go b/internal/crypt/raw_encrypt.go index 03f742f..03f742f 100644 --- a/internal/crypt/rawEncrypt.go +++ b/internal/crypt/raw_encrypt.go diff --git a/internal/crypt/sshKey.go b/internal/crypt/ssh_key.go index 2062ebd..a043f75 100644 --- a/internal/crypt/sshKey.go +++ b/internal/crypt/ssh_key.go @@ -10,11 +10,8 @@ import ( "crypto/sha512" "fmt" "os" - "os/signal" - "syscall" "filippo.io/edwards25519/field" - "github.com/charmbracelet/x/term" "golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/curve25519" "golang.org/x/crypto/ssh" @@ -54,35 +51,6 @@ func ed25519SeedToX25519Priv(seed []byte) []byte { return scalar } -func promptSSHKeyPassphrase(privKeyPath string) []byte { - fd := os.Stdin.Fd() - oldState, err := term.GetState(fd) - if err != nil { - fmt.Fprintf(os.Stderr, "eno: failed to get terminal state: %v\n", err) - return nil - } - - sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) - defer signal.Stop(sigCh) - - go func() { - <-sigCh - term.Restore(fd, oldState) - os.Exit(130) - }() - - fmt.Fprintf(os.Stderr, "Enter passphrase for SSH key %s: ", privKeyPath) - passphrase, err := term.ReadPassword(fd) - fmt.Fprintln(os.Stderr) - if err != nil { - fmt.Fprintf(os.Stderr, "eno: failed to read passphrase: %v\n", err) - return nil - } - - return passphrase -} - // Wraps noteKey once per PubKey. Returns WrappedKey for each. func WrapNoteKeyForRecipients(noteKey []byte, pubKeys [][]byte) ([]WrappedKey, error) { recipients := make([]WrappedKey, 0, len(pubKeys)) diff --git a/internal/crypt/ssh_key_io.go b/internal/crypt/ssh_key_io.go new file mode 100644 index 0000000..59ea448 --- /dev/null +++ b/internal/crypt/ssh_key_io.go @@ -0,0 +1,39 @@ +package crypt + +import ( + "fmt" + "os" + "os/signal" + "syscall" + + "github.com/charmbracelet/x/term" +) + +func promptSSHKeyPassphrase(privKeyPath string) []byte { + fd := os.Stdin.Fd() + oldState, err := term.GetState(fd) + if err != nil { + fmt.Fprintf(os.Stderr, "eno: failed to get terminal state: %v\n", err) + return nil + } + + sigCh := make(chan os.Signal, 1) + signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) + defer signal.Stop(sigCh) + + go func() { + <-sigCh + term.Restore(fd, oldState) + os.Exit(130) + }() + + fmt.Fprintf(os.Stderr, "Enter passphrase for SSH key %s: ", privKeyPath) + passphrase, err := term.ReadPassword(fd) + fmt.Fprintln(os.Stderr) + if err != nil { + fmt.Fprintf(os.Stderr, "eno: failed to read passphrase: %v\n", err) + return nil + } + + return passphrase +} diff --git a/internal/utils/utils.go b/internal/utils/utils.go index cea00a3..329128a 100644 --- a/internal/utils/utils.go +++ b/internal/utils/utils.go @@ -5,7 +5,6 @@ import ( "fmt" "os" "os/signal" - "strconv" "syscall" "github.com/charmbracelet/x/term" @@ -72,28 +71,7 @@ func CheckFileAuthMode(notePath string) (crypt.AuthMode, error) { return "", fmt.Errorf("failed to read file: %w", err) } - idx := -1 - for i, b := range data { - if b == ':' { - idx = i - break - } - } - if idx == -1 { - return "", fmt.Errorf("invalid file format: no header length prefix found") - } - - headerLen, err := strconv.Atoi(string(data[:idx])) - if err != nil { - return "", fmt.Errorf("failed to parse header length: %w", err) - } - - if headerLen < 0 || idx+1+headerLen > len(data) { - return "", fmt.Errorf("invalid header length %d", headerLen) - } - - headerBytes := data[idx+1 : idx+1+headerLen] - headers, err := crypt.GetFileHeaders(headerBytes) + headers, _, err := crypt.ParseFileHeaders(data) if err != nil { return "", fmt.Errorf("failed to decode headers: %w", err) } |