Skip to content

Commit

Permalink
feat(vault): add new commands (#25)
Browse files Browse the repository at this point in the history
Add following new commands for subcommand `vault`:

- `encrypt-file`: Encrypt a file
- `decrypt-file`: Decrypt vault encrypted file
- `view`: View vault encrypted file

Fixes #25.
  • Loading branch information
windvalley committed Jan 19, 2022
1 parent 19d3da1 commit bead28a
Show file tree
Hide file tree
Showing 8 changed files with 439 additions and 7 deletions.
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [1.7.0]

### Added

- `gossh vault encrypt`: adding the feature of obtaining plaintext from promt.
For details at ([#24](https://github.com/windvalley/gossh/issues/24)).

- Add following new commands for subcommand `vault`,
for details at ([#25](https://github.com/windvalley/gossh/issues/25)).
- `encrypt-file`: Encrypt a file
- `decrypt-file`: Decrypt vault encrypted file
- `view`: View vault encrypted file

### Changed

- Hide following global flags for `vault`.

- `-j/--output.json`
- `-q/--output.quiet`
- `-o/--output.file`
- `-C/--output.condense`

- Optimize some flags description.

## [1.6.0]

### Changed
Expand Down
4 changes: 2 additions & 2 deletions internal/cmd/vault/decrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ import (
"github.com/windvalley/gossh/pkg/util"
)

// DecryptCmd represents the vault decrypt command
var DecryptCmd = &cobra.Command{
// decryptCmd represents the vault decrypt command
var decryptCmd = &cobra.Command{
Use: "decrypt",
Short: "Decrypt content encrypted by vault",
Long: `
Expand Down
125 changes: 125 additions & 0 deletions internal/cmd/vault/decrypt_file.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
Copyright © 2022 windvalley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package vault

import (
"bytes"
"fmt"
"io/ioutil"
"os"

"github.com/spf13/cobra"

"github.com/windvalley/gossh/internal/pkg/aes"
"github.com/windvalley/gossh/pkg/util"
)

var deOutputFile string

// decryptFileCmd represents the vault decrypt-file command
var decryptFileCmd = &cobra.Command{
Use: "decrypt-file",
Short: "Decrypt vault encrypted file",
Long: `
Decrypt vault encrypted file.`,
Example: `
# Decrypt a vault encrypted file by asking for vault password.
$ gossh vault decrypt-file /path/auth.txt
# Decrypt a vault encrypted file by vault password file.
$ gossh vault decrypt-file /path/auth.txt -V /path/vault-password-file
# Output decrypted content to another file.
$ gossh vault decrypt-file /path/auth.txt -O /path/plaintxt.txt
# Output decrypted content to screen.
$ gossh vault decrypt-file /path/auth.txt -O -`,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
util.CobraCheckErrWithHelp(cmd, "requires one arg to represent the vault encrypted file")
}

if len(args) > 1 {
util.CobraCheckErrWithHelp(cmd, "to many args, only need one")
}

if !util.FileExists(args[0]) {
util.CheckErr(fmt.Sprintf("file '%s' not found", args[0]))
}

return nil
},
Run: func(cmd *cobra.Command, args []string) {
vaultPass := GetVaultPassword()

file := args[0]

p, err := ioutil.ReadFile(file)
util.CheckErr(err)

content := string(p)

if !aes.IsAES256CipherText(content) {
util.CheckErr(fmt.Sprintf("'%s' is not vault encrypted file", file))
}

decryptContent, err := aes.AES256Decode(content, vaultPass)
if err != nil {
err = fmt.Errorf("decrypt failed: %w", err)
}
util.CheckErr(err)

var (
f *os.File
err1 error
)

if deOutputFile != "" {
if deOutputFile == "-" {
fmt.Println(decryptContent)
fmt.Printf("Decryption successful\n")
return
}
f, err1 = os.OpenFile(deOutputFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModePerm)
} else {
f, err1 = os.OpenFile(file, os.O_TRUNC|os.O_RDWR, os.ModePerm)
}
util.CheckErr(err1)

reader := bytes.NewReader([]byte(decryptContent))
_, err = reader.WriteTo(f)
util.CheckErr(err)

fmt.Printf("\nDecryption successful\n")
},
}

func init() {
decryptFileCmd.Flags().StringVarP(
&deOutputFile,
"output-file",
"O",
"",
"file that decrypted content is written to (use - for stdout)",
)
}
4 changes: 2 additions & 2 deletions internal/cmd/vault/encrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ import (
"github.com/windvalley/gossh/pkg/util"
)

// EncryptCmd represents the vault encrypt command
var EncryptCmd = &cobra.Command{
// encryptCmd represents the vault encrypt command
var encryptCmd = &cobra.Command{
Use: "encrypt",
Short: "Encrypt sensitive content",
Long: `
Expand Down
125 changes: 125 additions & 0 deletions internal/cmd/vault/encrypt_file.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
Copyright © 2022 windvalley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package vault

import (
"bytes"
"fmt"
"io/ioutil"
"os"

"github.com/spf13/cobra"

"github.com/windvalley/gossh/internal/pkg/aes"
"github.com/windvalley/gossh/pkg/util"
)

var outputFile string

// encryptFileCmd represents the vault encrypt-file command
var encryptFileCmd = &cobra.Command{
Use: "encrypt-file",
Short: "Encrypt a file",
Long: `
Encrypt a file.`,
Example: `
# Encrypt a file by asking for vault password.
$ gossh vault encrypt-file /path/auth.txt
# Encrypt a file by vault password file.
$ gossh vault encrypt-file /path/auth.txt -V /path/vault-password-file
# Output encrypted content to another file.
$ gossh vault encrypt-file /path/auth.txt -O /path/encryption.txt
# Output encrypted content to screen.
$ gossh vault encrypt-file /path/auth.txt -O -`,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
util.CobraCheckErrWithHelp(cmd, "requires one arg to represent a file to be encrypted")
}

if len(args) > 1 {
util.CobraCheckErrWithHelp(cmd, "to many args, only need one")
}

if !util.FileExists(args[0]) {
util.CheckErr(fmt.Sprintf("file '%s' not found", args[0]))
}

return nil
},
Run: func(cmd *cobra.Command, args []string) {
vaultPass := getVaultConfirmPassword()

file := args[0]

p, err := ioutil.ReadFile(file)
util.CheckErr(err)

content := string(p)

if aes.IsAES256CipherText(content) {
util.CheckErr(fmt.Sprintf("file '%s' is already encrypted", file))
}

encryptContent, err := aes.AES256Encode(content, vaultPass)
if err != nil {
err = fmt.Errorf("encrypt failed: %w", err)
}
util.CheckErr(err)

var (
f *os.File
err1 error
)

if outputFile != "" {
if outputFile == "-" {
fmt.Println(encryptContent)
fmt.Printf("\nEncryption successful\n")
return
}
f, err1 = os.OpenFile(outputFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModePerm)
} else {
f, err1 = os.OpenFile(file, os.O_TRUNC|os.O_RDWR, os.ModePerm)
}
util.CheckErr(err1)

reader := bytes.NewReader([]byte(encryptContent))
_, err = reader.WriteTo(f)
util.CheckErr(err)

fmt.Printf("\nEncryption successful\n")
},
}

func init() {
encryptFileCmd.Flags().StringVarP(
&outputFile,
"output-file",
"O",
"",
"file that encrypted content is written to (use - for stdout)",
)
}
22 changes: 19 additions & 3 deletions internal/cmd/vault/vault.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ password(vault-pass) to encrypt and decrypt the content.`,
}

func init() {
util.CobraAddSubCommandInOrder(Cmd, EncryptCmd, DecryptCmd)
util.CobraAddSubCommandInOrder(Cmd,
encryptCmd, decryptCmd, encryptFileCmd, decryptFileCmd, viewCmd)
}

// SetHelpFunc for vault command and its subcommands.
Expand All @@ -67,12 +68,27 @@ func SetHelpFunc(rootCmd *cobra.Command) {
command.Parent().HelpFunc()(command, strings)
})

EncryptCmd.SetHelpFunc(func(command *cobra.Command, strings []string) {
encryptCmd.SetHelpFunc(func(command *cobra.Command, strings []string) {
markHiddenGlobalFlagsExceptsForVault()
command.Parent().Parent().HelpFunc()(command, strings)
})

DecryptCmd.SetHelpFunc(func(command *cobra.Command, strings []string) {
decryptCmd.SetHelpFunc(func(command *cobra.Command, strings []string) {
markHiddenGlobalFlagsExceptsForVault()
command.Parent().Parent().HelpFunc()(command, strings)
})

encryptFileCmd.SetHelpFunc(func(command *cobra.Command, strings []string) {
markHiddenGlobalFlagsExceptsForVault()
command.Parent().Parent().HelpFunc()(command, strings)
})

decryptFileCmd.SetHelpFunc(func(command *cobra.Command, strings []string) {
markHiddenGlobalFlagsExceptsForVault()
command.Parent().Parent().HelpFunc()(command, strings)
})

viewCmd.SetHelpFunc(func(command *cobra.Command, strings []string) {
markHiddenGlobalFlagsExceptsForVault()
command.Parent().Parent().HelpFunc()(command, strings)
})
Expand Down
Loading

0 comments on commit bead28a

Please sign in to comment.