From 6c6c4a05267e93597bb009c7d6c36383b6af7bf7 Mon Sep 17 00:00:00 2001 From: ishaan Date: Tue, 14 Jul 2026 19:26:55 +0530 Subject: ssh --- cmd/eno/cobra.go | 26 ++++- cmd/eno/cobra_new.go | 38 ++++++- cmd/eno/cobra_ssh.go | 171 ++++++++++++++++++++++++++++ cmd/eno/config.go | 38 ++++--- eno | Bin 5335157 -> 7190584 bytes internal/crud/cli_edit.go | 101 ++++++++++++++++- internal/crud/cli_new.go | 258 +++++++++++++++++++++++++++++++++++++++++-- internal/crypt/headers.go | 19 +++- internal/crypt/rawDecrypt.go | 70 +++++++++++- internal/crypt/rawEncrypt.go | 49 +++++++- internal/crypt/sshKey.go | 22 +++- internal/utils/utils.go | 37 +++++++ 12 files changed, 781 insertions(+), 48 deletions(-) create mode 100644 cmd/eno/cobra_ssh.go diff --git a/cmd/eno/cobra.go b/cmd/eno/cobra.go index 9e4d4d2..ced2bc2 100644 --- a/cmd/eno/cobra.go +++ b/cmd/eno/cobra.go @@ -56,7 +56,7 @@ var encryptCmd = &cobra.Command{ crypt.TryMlock(password) defer clear(password) - encrypted, err := crypt.EncryptRawBytes(fileBytes, password, crypt.Pass) + encrypted, err := crypt.EncryptBytesPass(fileBytes, password) if err != nil { cmd.PrintErrln("Error:", err) os.Exit(1) @@ -107,7 +107,7 @@ var decryptCmd = &cobra.Command{ crypt.TryMlock(password) defer clear(password) - plaintext, err := crypt.DecryptRawBytes(fileBytes, password) + plaintext, err := crypt.DecryptBytesPass(fileBytes, password) if err != nil { cmd.PrintErrln("Error:", err) os.Exit(1) @@ -159,7 +159,21 @@ var editCmd = &cobra.Command{ target = strings.TrimSuffix(target, ".eno") target += ".eno" - err = crud.EditNote(target, Conf.EditorString) + authMode, err := utils.CheckFileAuthMode(target) + if err != nil { + cmd.PrintErrln("Error:", err) + os.Exit(1) + } + + switch authMode { + case crypt.SSH: + err = crud.EditNoteSSH(target, Conf.DefaultSSHPrivPath, Conf.EditorString) + case crypt.Pass: + err = crud.EditNotePass(target, Conf.EditorString) + default: + cmd.PrintErrln("Error: unknown auth mode:", authMode) + os.Exit(1) + } if err != nil { cmd.PrintErrln("Error:", err) os.Exit(1) @@ -176,7 +190,9 @@ func init() { newCmd.Flags().StringP("output", "o", "", "output file") newCmd.Flags().BoolP("edit", "e", false, "edit after creation") - newCmd.Flags().BoolP("ssh", "ssh", false, "use your ssh for auth") + newCmd.Flags().Bool("ssh", false, "use your ssh for auth") + + sshCmd.AddCommand(sshInitCmd) - cobraCmd.AddCommand(encryptCmd, decryptCmd, initCmd, newCmd, editCmd) + cobraCmd.AddCommand(encryptCmd, decryptCmd, initCmd, newCmd, editCmd, sshCmd) } diff --git a/cmd/eno/cobra_new.go b/cmd/eno/cobra_new.go index 4a7caeb..d424fea 100644 --- a/cmd/eno/cobra_new.go +++ b/cmd/eno/cobra_new.go @@ -34,8 +34,6 @@ var newCmd = &cobra.Command{ os.Exit(1) } - - noteName := strings.Join(args, " ") if output == "" { if strings.ContainsRune(noteName, filepath.Separator) { @@ -57,17 +55,45 @@ var newCmd = &cobra.Command{ } } - if editFlag { - err = crud.NewNoteEdit(output, Conf.EditorString) + if sshFlag && editFlag { + pubKeyBytes, err := os.ReadFile(Conf.DefaultSSHPubPath) if err != nil { cmd.PrintErrln("Error:", err) os.Exit(1) } + + err = crud.NewNoteSSHEdit(output, pubKeyBytes, Conf.DefaultSSHPrivPath, Conf.EditorString) + if err != nil { + cmd.PrintErrln("Error:", err) + os.Exit(1) + } + return } - _ = sshFlag + if sshFlag { + pubKeyBytes, err := os.ReadFile(Conf.DefaultSSHPubPath) + if err != nil { + cmd.PrintErrln("Error:", err) + os.Exit(1) + } + + err = crud.NewNoteSSH(output, pubKeyBytes) + if err != nil { + cmd.PrintErrln("Error:", err) + os.Exit(1) + } + return + } + + if editFlag { + err = crud.NewNotePassEdit(output, Conf.EditorString) + if err != nil { + cmd.PrintErrln("Error:", err) + os.Exit(1) + } + } - err = crud.NewNote(output) + err = crud.NewNotePass(output) if err != nil { cmd.PrintErrln("Error:", err) os.Exit(1) diff --git a/cmd/eno/cobra_ssh.go b/cmd/eno/cobra_ssh.go new file mode 100644 index 0000000..58a5a44 --- /dev/null +++ b/cmd/eno/cobra_ssh.go @@ -0,0 +1,171 @@ +package main + +import ( + "bufio" + "crypto" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/spf13/cobra" + "gitlab.com/whiteboardguy/eno/internal/crypt" + "gitlab.com/whiteboardguy/eno/internal/utils" + "golang.org/x/crypto/ssh" +) + +func expandPath(path string) string { + if strings.HasPrefix(path, "~") { + home, err := os.UserHomeDir() + if err == nil { + rest := strings.TrimPrefix(path[1:], "/") + path = filepath.Join(home, rest) + } + } + return path +} + +var sshCmd = &cobra.Command{ + Use: "ssh", + Short: "ssh auth in Eno notes", + Args: cobra.MinimumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + }, +} + +var sshInitCmd = &cobra.Command{ + Use: "init", + Short: "setup ssh for Eno notes", + Args: cobra.ExactArgs(0), + Run: func(cmd *cobra.Command, args []string) { + scanner := bufio.NewScanner(os.Stdin) + + if Conf.SSHInitialized { + cmd.PrintErrln("SSH is already initialized") + ok, err := utils.AskUserYesNo("Reinitialize SSH?", false) + if err != nil { + cmd.PrintErrln(err) + os.Exit(1) + } + if !ok { + cmd.PrintErrln("SSH init aborted") + os.Exit(0) + } + } + + privateKeyPath := expandPath("~/.ssh/id_ed25519") + if _, err := os.Stat(privateKeyPath); err == nil { + ok, err := utils.AskUserYesNo("Use default SSH key at ~/.ssh/id_ed25519?", true) + if err != nil { + cmd.PrintErrln(err) + os.Exit(1) + } + if !ok { + privateKeyPath = "" + } + } else { + privateKeyPath = "" + } + + if privateKeyPath == "" { + fmt.Print("Enter path to SSH private key: ") + if !scanner.Scan() { + cmd.PrintErrln("failed to read input") + os.Exit(1) + } + privateKeyPath = expandPath(strings.TrimSpace(scanner.Text())) + } + + publicKeyPath := privateKeyPath + ".pub" + if _, err := os.Stat(publicKeyPath); os.IsNotExist(err) { + cmd.PrintErrln("public key not found at " + publicKeyPath) + fmt.Print("Enter path to SSH public key: ") + if !scanner.Scan() { + cmd.PrintErrln("failed to read input") + os.Exit(1) + } + publicKeyPath = strings.TrimSpace(scanner.Text()) + publicKeyPath = expandPath(publicKeyPath) + } + + givenPubKeyBytes, err := os.ReadFile(publicKeyPath) + if err != nil { + cmd.PrintErrln(err) + os.Exit(1) + } + + privKeyBytes, err := os.ReadFile(privateKeyPath) + if err != nil { + cmd.PrintErrln(err) + os.Exit(1) + } + crypt.TryMlock(privKeyBytes) + defer clear(privKeyBytes) + + privKey, err := ssh.ParseRawPrivateKey(privKeyBytes) + if err != nil { + if _, ok := errors.AsType[*ssh.PassphraseMissingError](err); ok { + fmt.Printf("SSH Key Locked!\n") + fmt.Printf("Enter the ssh key passphrase: ") + sshPassword, err := utils.TakeSecureUserInput() + if err != nil { + cmd.PrintErrln(err) + os.Exit(1) + } + crypt.TryMlock(sshPassword) + defer clear(sshPassword) + + privKey, err = ssh.ParseRawPrivateKeyWithPassphrase(privKeyBytes, []byte(sshPassword)) + } else { + cmd.PrintErrln(err) + os.Exit(1) + } + } + + signer, ok := privKey.(crypto.Signer) + if !ok { + cmd.PrintErrln("failed to extract public key from private key") + os.Exit(1) + } + extractedPubKeyRaw := signer.Public() + + givenPubKey, _, _, _, err := ssh.ParseAuthorizedKey(givenPubKeyBytes) + if err != nil { + cmd.PrintErrln(err) + os.Exit(1) + } + + extractedPubKey, err := ssh.NewPublicKey(extractedPubKeyRaw) + if err != nil { + cmd.PrintErrln(err) + os.Exit(1) + } + + if ssh.FingerprintSHA256(extractedPubKey) != ssh.FingerprintSHA256(givenPubKey) { + cmd.PrintErrln("public key file does not match private key") + os.Exit(1) + } + + if err := updateConfig("DefaultSSHPrivPath", privateKeyPath); err != nil { + cmd.PrintErrln(err) + os.Exit(1) + } + if err := updateConfig("DefaultSSHPubPath", publicKeyPath); err != nil { + cmd.PrintErrln(err) + os.Exit(1) + } + if err := updateConfig("SSHInitialized", true); err != nil { + cmd.PrintErrln(err) + os.Exit(1) + } + + if err := updateConfig("SSHInitialized", true); err != nil { + cmd.PrintErrln(err) + os.Exit(1) + } + + + cmd.Println("ssh initialized with public key:", publicKeyPath) + }, +} diff --git a/cmd/eno/config.go b/cmd/eno/config.go index b1bb407..3551522 100644 --- a/cmd/eno/config.go +++ b/cmd/eno/config.go @@ -14,7 +14,8 @@ type Config struct { EditorString string DataDir string ConfPath string - DefaultSSH string + DefaultSSHPrivPath string + DefaultSSHPubPath string SSHInitialized bool } var Conf Config @@ -59,7 +60,6 @@ func initConfig() error { f, err := os.Open(Conf.ConfPath) if err != nil { if errors.Is(err, os.ErrNotExist) { - fmt.Fprintf(os.Stderr, "no config — run 'eno init'\n") return nil } return fmt.Errorf("reading config: %w", err) @@ -85,14 +85,18 @@ func initConfig() error { if v := strings.TrimSpace(val); v != "" { Conf.DataDir = v } - case "DEFAULT_SSH": - if v := strings.TrimSpace(val); v != "" { - Conf.DefaultSSH = v - } case "SSH_INIT": if v, err := strconv.ParseBool(strings.TrimSpace(val)); err == nil { Conf.SSHInitialized = v } + case "DEFAULT_SSH_PRIV": + if v := strings.TrimSpace(val); v != "" { + Conf.DefaultSSHPrivPath = v + } + case "DEFAULT_SSH_PUB": + if v := strings.TrimSpace(val); v != "" { + Conf.DefaultSSHPubPath = v + } } } return scanner.Err() @@ -112,11 +116,14 @@ func handlerInit() error { defer f.Close() defaultConfLines := []string{ - fmt.Sprintf("EDITOR_STRING=%s", Conf.EditorString), - fmt.Sprintf("DATA_DIR=%s", Conf.DataDir), - fmt.Sprintf("SSH_INIT=%b", Conf.SSHInitialized), - "# Change 'DEFAULT_SSH' to a private ssh key you want to use regularly.", - "# DEFAULT_SSH=/home/user/.ssh/id_ed25519", + fmt.Sprintf("EDITOR_STRING=%s\n", Conf.EditorString), + + fmt.Sprintf("DATA_DIR=%s\n", Conf.DataDir), + + fmt.Sprintf("SSH_INIT=%t\n", Conf.SSHInitialized), + + "# Change 'DEFAULT_SSH_PRIV' to a private ssh key you want to use regularly to encrypt.", + "# Change 'DEFAULT_SSH_PUB' to a private ssh key you want to use regularly to decrypt.", } _, err = fmt.Fprintf(f, "%s\n", strings.Join(defaultConfLines, "\n")) @@ -128,10 +135,11 @@ func handlerInit() error { } var configFieldKey = map[string]string{ - "EditorString": "EDITOR_STRING", - "DataDir": "DATA_DIR", - "DefaultSSH": "DEFAULT_SSH", - "SSHInitialized": "SSH_INIT", + "EditorString": "EDITOR_STRING", + "DataDir": "DATA_DIR", + "DefaultSSHPrivPath": "DEFAULT_SSH_PRIV", + "DefaultSSHPubPath": "DEFAULT_SSH_PUB", + "SSHInitialized": "SSH_INIT", } func updateConfig(key string, val any) error { diff --git a/eno b/eno index 0e800b5..da051eb 100755 Binary files a/eno and b/eno differ diff --git a/internal/crud/cli_edit.go b/internal/crud/cli_edit.go index 5e2cb8d..0213a81 100644 --- a/internal/crud/cli_edit.go +++ b/internal/crud/cli_edit.go @@ -3,13 +3,14 @@ package crud import ( "fmt" "os" + "strconv" "gitlab.com/whiteboardguy/eno/internal/crypt" "gitlab.com/whiteboardguy/eno/internal/editor" "gitlab.com/whiteboardguy/eno/internal/utils" ) -func EditNote(notePath, editorString string) error { +func EditNotePass(notePath, editorString string) error { noteInfo, err := os.Stat(notePath) if err != nil && !os.IsNotExist(err) { return err @@ -29,7 +30,7 @@ func EditNote(notePath, editorString string) error { tmpFile, err := os.CreateTemp("", "eno-*") if err != nil { return err } - plaintext, err := crypt.DecryptRawBytes(ciphertext, password) + plaintext, err := crypt.DecryptBytesPass(ciphertext, password) if err != nil { return err } crypt.TryMlock(plaintext) defer clear(plaintext) @@ -51,13 +52,13 @@ func EditNote(notePath, editorString string) error { os.WriteFile(tmpFile.Name(), make([]byte, len(newContent)), 0600) - encrypted, err := crypt.EncryptRawBytes(newContent, password, crypt.Pass) + encrypted, err := crypt.EncryptBytesPass(newContent, password) if err != nil { return err } err = os.WriteFile(notePath, encrypted, noteInfo.Mode().Perm()) // utils.ClearTerm() - fmt.Println("Saved:", noteInfo.Name()) + fmt.Println("Saved:", notePath) return err } @@ -71,3 +72,95 @@ func deferredCleanTmpFile(tmpFile *os.File, oldContentLen int) { os.WriteFile(tmpFile.Name(), make([]byte, int(tmpFileInfo.Size())), 0600) } + +func EditNoteSSH(notePath, privKeyPath, editorString string) error { + noteInfo, err := os.Stat(notePath) + if err != nil && !os.IsNotExist(err) { + return err + } + + ciphertext, err := os.ReadFile(notePath) + if err != nil { + 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) + if err != nil { + return fmt.Errorf("failed to read file headers: %v", err) + } + + if headers.Auth != crypt.SSH { + return fmt.Errorf("note uses %s auth, not SSH", headers.Auth) + } + + pubKeys := make([][]byte, len(headers.Recipients)) + for i, recipient := range headers.Recipients { + pubKeys[i] = recipient.PubKeyBytes + } + + tmpFile, err := os.CreateTemp("", "eno-*") + if err != nil { + return err + } + + plaintext, err := crypt.DecryptBytesSSH(ciphertext, privKeyPath) + 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) + + os.WriteFile(tmpFile.Name(), make([]byte, len(newContent)), 0600) + + encrypted, err := crypt.EncryptBytesSSH(newContent, pubKeys) + if err != nil { + return err + } + + err = os.WriteFile(notePath, encrypted, noteInfo.Mode().Perm()) + + fmt.Println("Saved:", notePath) + + return err +} diff --git a/internal/crud/cli_new.go b/internal/crud/cli_new.go index 2b6e507..c8303a0 100644 --- a/internal/crud/cli_new.go +++ b/internal/crud/cli_new.go @@ -1,15 +1,18 @@ package crud import ( + "bufio" + "bytes" "fmt" "os" + "strings" "gitlab.com/whiteboardguy/eno/internal/crypt" "gitlab.com/whiteboardguy/eno/internal/editor" "gitlab.com/whiteboardguy/eno/internal/utils" ) -func NewNote(output string) error { +func NewNotePass(output string) error { fmt.Printf("Enter the passphrase: ") password, err := utils.TakeSecureUserInput() if err != nil { @@ -30,10 +33,9 @@ func NewNote(output string) error { return fmt.Errorf("passphrases do not match") } - encrypted, err := crypt.EncryptRawBytes( + encrypted, err := crypt.EncryptBytesPass( []byte(string(utils.RandomLettersNumbers(37))+"\nYou can Delete all of this ^^^"), password, - crypt.Pass, ) if err != nil { return err @@ -58,7 +60,7 @@ func NewNote(output string) error { return nil } -func NewNoteEdit(output, editorString string) error { +func NewNotePassEdit(output, editorString string) error { fmt.Printf("Enter the passphrase: ") password, err := utils.TakeSecureUserInput() if err != nil { @@ -83,7 +85,7 @@ func NewNoteEdit(output, editorString string) error { preExisting := err == nil initialContent := []byte(string(utils.RandomLettersNumbers(37)) + "\nYou can Delete all of this ^^^") - encrypted, err := crypt.EncryptRawBytes(initialContent, password, crypt.Pass) + encrypted, err := crypt.EncryptBytesPass(initialContent, password) if err != nil { return err } @@ -111,7 +113,7 @@ func NewNoteEdit(output, editorString string) error { return err } - plaintext, err := crypt.DecryptRawBytes(ciphertext, password) + plaintext, err := crypt.DecryptBytesPass(ciphertext, password) if err != nil { return err } @@ -140,7 +142,249 @@ func NewNoteEdit(output, editorString string) error { os.WriteFile(tmpFile.Name(), make([]byte, len(newContent)), 0600) - encrypted, err = crypt.EncryptRawBytes(newContent, password, crypt.Pass) + 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 NewNoteSSH(output string, defaultPubKeyBytes []byte) error { + useDefault, err := utils.AskUserYesNo("Do you want to encrypt the note with your own default Public Key?", true) + if err != nil { + return fmt.Errorf("failed to read confirmation: %v", err) + } + if !useDefault { + fmt.Println("Warning: you will not be able to open or edit this note again.") + fmt.Println(" make sure you've used the '--edit' flag.") + } + + addMore, err := utils.AskUserYesNo("Do you want to add more public keys?", false) + if err != nil { + return fmt.Errorf("failed to read confirmation: %v", err) + } + + pubKeys := [][]byte{} + + if useDefault { + pubKeys = append(pubKeys, defaultPubKeyBytes) + } + + if addMore { + for { + fmt.Print("Enter a public key, or path to a public key file (comma-separated for multiple): ") + scanner := bufio.NewScanner(os.Stdin) + scanner.Scan() + if err := scanner.Err(); err != nil { + return fmt.Errorf("failed to read public key: %v", err) + } + + input := strings.TrimSpace(scanner.Text()) + if input == "" { + continue + } + + for part := range strings.SplitSeq(input, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + + var keyBytes []byte + if strings.HasPrefix(part, "ssh-") { + keyBytes = []byte(part) + } else { + var err error + keyBytes, err = os.ReadFile(part) + if err != nil { + return fmt.Errorf("failed to read public key file %s: %v", part, err) + } + } + + pubKeys = append(pubKeys, bytes.TrimSpace(keyBytes)) + } + + more, err := utils.AskUserYesNo("Add more public keys?", false) + if err != nil { + return fmt.Errorf("failed to read confirmation: %v", err) + } + if !more { + break + } + } + } + + if len(pubKeys) == 0 { + return fmt.Errorf("at least one recipient public key is required") + } + + tmptxt := []byte(string(utils.RandomLettersNumbers(37))+"\nYou can Delete all of this ^^^") + + encrypted, err := crypt.EncryptBytesSSH(tmptxt, pubKeys) + if err != nil { + return err + } + + fmt.Println(output) + file, err := os.Create(output) + if err != nil { + return err + } + + _, err = file.Write(encrypted) + if err != nil { + return err + } + + file.Sync() + + // utils.ClearTerm() + fmt.Println("New note saved at:", file.Name()) + + return nil +} + +func NewNoteSSHEdit(output string, defaultPubKeyBytes []byte, defaultPrivKeyPath string, editorString string) error { + useDefault, err := utils.AskUserYesNo("Do you want to encrypt the note with your own default Public Key?", true) + if err != nil { + return fmt.Errorf("failed to read confirmation: %v", err) + } + if !useDefault { + fmt.Println("Warning: you will not be able to open or edit this note again.") + fmt.Println(" make sure you've used the '--edit' flag.") + } + + addMore, err := utils.AskUserYesNo("Do you want to add more public keys?", false) + if err != nil { + return fmt.Errorf("failed to read confirmation: %v", err) + } + + pubKeys := [][]byte{} + + if useDefault { + pubKeys = append(pubKeys, defaultPubKeyBytes) + } + + if addMore { + for { + fmt.Print("Enter a public key, or path to a public key file (comma-separated for multiple): ") + scanner := bufio.NewScanner(os.Stdin) + scanner.Scan() + if err := scanner.Err(); err != nil { + return fmt.Errorf("failed to read public key: %v", err) + } + + input := strings.TrimSpace(scanner.Text()) + if input == "" { + continue + } + + for part := range strings.SplitSeq(input, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + + var keyBytes []byte + if strings.HasPrefix(part, "ssh-") { + keyBytes = []byte(part) + } else { + var err error + keyBytes, err = os.ReadFile(part) + if err != nil { + return fmt.Errorf("failed to read public key file %s: %v", part, err) + } + } + + pubKeys = append(pubKeys, bytes.TrimSpace(keyBytes)) + } + + more, err := utils.AskUserYesNo("Add more public keys?", false) + if err != nil { + return fmt.Errorf("failed to read confirmation: %v", err) + } + if !more { + break + } + } + } + + if len(pubKeys) == 0 { + return fmt.Errorf("at least one recipient public key is required") + } + + noteInfo, err := os.Stat(output) + preExisting := err == nil + + initialContent := []byte(string(utils.RandomLettersNumbers(37)) + "\nYou can Delete all of this ^^^") + encrypted, err := crypt.EncryptBytesSSH(initialContent, pubKeys) + if err != nil { + return err + } + + file, err := os.Create(output) + 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 := os.CreateTemp("", "eno-*") + if err != nil { + return err + } + + plaintext, err := crypt.DecryptBytesSSH(ciphertext, defaultPrivKeyPath) + 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) + + os.WriteFile(tmpFile.Name(), make([]byte, len(newContent)), 0600) + + encrypted, err = crypt.EncryptBytesSSH(newContent, pubKeys) if err != nil { return err } diff --git a/internal/crypt/headers.go b/internal/crypt/headers.go index b5addb2..8f9dac2 100644 --- a/internal/crypt/headers.go +++ b/internal/crypt/headers.go @@ -18,15 +18,24 @@ const ( ) type FileHeaders struct { - Salt [16]byte - Nonce [12]byte - Type DataType - Auth AuthMode - Parts int + Salt [16]byte + Nonce [12]byte + Type DataType + Auth AuthMode // "Pass" or "SSH" + Parts int + Recipients []WrappedKey // TODO: Version (string) for the version of .eno file. } +type WrappedKey struct { + PKType string // "ssh-ed25519" + PubKeyBytes []byte + EphemeralPub []byte // of X25519, for ECDH on decrypt (also can replace salt) + Nonce [12]byte // for decrypting EncNoteKey + EncNoteKey []byte // encrypted note key (ciphertext + 16B tag) +} + func GetFileHeaders(b []byte) (FileHeaders, error) { dec := gob.NewDecoder(bytes.NewReader(b)) var headers FileHeaders diff --git a/internal/crypt/rawDecrypt.go b/internal/crypt/rawDecrypt.go index 28d7856..b94ea60 100644 --- a/internal/crypt/rawDecrypt.go +++ b/internal/crypt/rawDecrypt.go @@ -8,7 +8,7 @@ import ( "golang.org/x/crypto/chacha20poly1305" ) -func DecryptRawBytes(inputBytes []byte, password []byte) ([]byte, error) { +func DecryptBytesPass(inputBytes []byte, password []byte) ([]byte, error) { idx := -1 for i, b := range inputBytes { if b == ':' { @@ -35,6 +35,10 @@ func DecryptRawBytes(inputBytes []byte, password []byte) ([]byte, error) { return nil, fmt.Errorf("decrypt: %w", err) } + if headers.Auth != Pass { + return nil, fmt.Errorf("decrypt: expected password auth, got %s", headers.Auth) + } + key := argon2.IDKey(password, headers.Salt[:], 1, 2*1024*1024, 2, 32) TryMlock(key) defer clear(key) @@ -51,3 +55,67 @@ func DecryptRawBytes(inputBytes []byte, password []byte) ([]byte, error) { return plaintext, nil } + +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) + if err != nil { + return nil, fmt.Errorf("decrypt: %w", err) + } + + if headers.Auth != SSH { + return nil, fmt.Errorf("decrypt: expected SSH auth, got %s", headers.Auth) + } + + if len(headers.Recipients) == 0 { + return nil, fmt.Errorf("decrypt: no recipients found in headers") + } + + key := []byte{} + TryMlock(key) + defer clear(key) + if len(headers.Recipients) == 1 { + key, err = UnwrapNoteKey(headers.Recipients[0], privKeyPath) + if err != nil { + return nil, fmt.Errorf("decrypt: failed to unwrap note key: %w", err) + } + } else { + key, err = FindAndUnwrapNoteKey(headers.Recipients, privKeyPath) + if err != nil { + return nil, fmt.Errorf("decrypt: failed to unwrap note key: %w", err) + } + } + + aead, err := chacha20poly1305.New(key) + if err != nil { + 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) + } + + return plaintext, nil +} diff --git a/internal/crypt/rawEncrypt.go b/internal/crypt/rawEncrypt.go index 135efdf..bf4b82f 100644 --- a/internal/crypt/rawEncrypt.go +++ b/internal/crypt/rawEncrypt.go @@ -1,6 +1,7 @@ package crypt import ( + "crypto/rand" "fmt" "strconv" @@ -8,7 +9,7 @@ import ( "golang.org/x/crypto/chacha20poly1305" ) -func EncryptRawBytes(inputBytes []byte, password []byte, authMode AuthMode) ([]byte, error) { +func EncryptBytesPass(inputBytes []byte, password []byte) ([]byte, error) { salt, err := NewSalt() if err != nil { return nil, fmt.Errorf("encrypt: %w", err) @@ -19,7 +20,7 @@ func EncryptRawBytes(inputBytes []byte, password []byte, authMode AuthMode) ([]b return nil, fmt.Errorf("encrypt: %w", err) } - headers := FileHeaders{Salt: salt, Nonce: nonce, Type: File, Parts: 1, Auth: authMode} + headers := FileHeaders{Salt: salt, Nonce: nonce, Type: File, Parts: 1, Auth: Pass, Recipients: []WrappedKey{}} key := argon2.IDKey(password, headers.Salt[:], 1, 2*1024*1024, 2, 32) TryMlock(key) @@ -44,3 +45,47 @@ func EncryptRawBytes(inputBytes []byte, password []byte, authMode AuthMode) ([]b return target, nil } + +func EncryptBytesSSH(inputBytes []byte, pubKeys [][]byte) ([]byte, error) { + salt, err := NewSalt() + if err != nil { + return nil, fmt.Errorf("encrypt: %w", err) + } + + nonce, err := NewNonce() + if err != nil { + return nil, fmt.Errorf("encrypt: %w", err) + } + + key := [32]byte{} + _, err = rand.Read(key[:]) + if err != nil { + return nil, fmt.Errorf("encrypt: failed to generate key: %w", err) + } + TryMlock(key[:]) + defer clear(key[:]) + + recipients, err := WrapNoteKeyForRecipients(key[:], pubKeys) + + headers := FileHeaders{Salt: salt, Nonce: nonce, Type: File, Parts: 1, Auth: SSH, Recipients: recipients} + + aead, err := chacha20poly1305.New(key[:]) + if err != nil { + return nil, fmt.Errorf("encrypt: failed to create cipher: %w", err) + } + + encrypted := aead.Seal(nil, headers.Nonce[:], inputBytes, nil) + + headerBytes, err := FileHeadersBytes(headers) + if err != nil { + return nil, fmt.Errorf("encrypt: %w", err) + } + + lenLen := len(strconv.Itoa(len(headerBytes))) + target := make([]byte, 0, lenLen+1+len(headerBytes)+len(encrypted)) + target = fmt.Appendf(target, "%d:", len(headerBytes)) + target = append(target, headerBytes...) + target = append(target, encrypted...) + + return target, nil +} diff --git a/internal/crypt/sshKey.go b/internal/crypt/sshKey.go index 2481275..3b0b344 100644 --- a/internal/crypt/sshKey.go +++ b/internal/crypt/sshKey.go @@ -21,9 +21,17 @@ import ( var curve25519Prime, _ = new(big.Int).SetString("57896044618658097711785492504343953926634992332820282019728792003956564819949", 10) var bigOne = big.NewInt(1) -// Ed25519 pubkey -> X25519 pubkey. Both 32b +// Ed25519 pubkey -> X25519 pubkey. Both 32B func edwardsToMontgomery(edPub []byte) []byte { - y := new(big.Int).SetBytes(edPub) + edPubCopy := make([]byte, 32) + copy(edPubCopy, edPub) + edPubCopy[31] &= 0x7F + + for i, j := 0, 31; i < j; i, j = i+1, j-1 { + edPubCopy[i], edPubCopy[j] = edPubCopy[j], edPubCopy[i] + } + + y := new(big.Int).SetBytes(edPubCopy) num := new(big.Int).Add(bigOne, y) @@ -34,7 +42,15 @@ func edwardsToMontgomery(edPub []byte) []byte { u := new(big.Int).Mul(num, denom) u.Mod(u, curve25519Prime) - return u.FillBytes(make([]byte, 32)) + uBE := make([]byte, 32) + u.FillBytes(uBE) + + uLE := make([]byte, 32) + for i := 0; i < 32; i++ { + uLE[i] = uBE[31-i] + } + + return uLE } // Ed25519 seed -> X25519 private key. diff --git a/internal/utils/utils.go b/internal/utils/utils.go index a8437b9..cea00a3 100644 --- a/internal/utils/utils.go +++ b/internal/utils/utils.go @@ -5,9 +5,11 @@ import ( "fmt" "os" "os/signal" + "strconv" "syscall" "github.com/charmbracelet/x/term" + "gitlab.com/whiteboardguy/eno/internal/crypt" ) func TakeSecureUserInput() ([]byte, error) { @@ -63,3 +65,38 @@ func RandomLettersNumbers(n int) []byte { } return b } + +func CheckFileAuthMode(notePath string) (crypt.AuthMode, error) { + data, err := os.ReadFile(notePath) + if err != nil { + 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) + if err != nil { + return "", fmt.Errorf("failed to decode headers: %w", err) + } + + return headers.Auth, nil +} -- cgit v1.3