Compare commits

..

14 Commits
v1.0.0 ... main

Author SHA1 Message Date
akulij
b47de3e1b6 implement hex/raw input 2025-03-03 00:18:43 +00:00
akulij
9cde36c5c2 rename 'sum' variable that contains hashed password to more appropriate name 'secretKey' 2025-03-03 00:18:43 +00:00
akulij
181ac703ae add --input-type flag 2025-03-03 00:18:37 +00:00
akulij
b6be7799b9 README: fix wrong todo tasks formating 2025-02-28 04:21:59 +00:00
akulij
ecaa3c8a9a README: remove unnecessary decription header 2025-02-28 01:08:30 +00:00
akulij
f921077964 add option to build and run this repo using nix 2025-02-28 00:15:27 +00:00
akulij
c9cb1bb2d8 README: mark task to add sigpipe handle as done 2025-02-27 22:19:28 +00:00
akulij
5184859c54 handle sigpipe for user friendliness 2025-02-27 22:18:18 +00:00
akulij
bd018136d6 delete sigint handler since it doesn't do anything 2025-02-27 22:13:45 +00:00
akulij
d924708a1c fix: signal handler setter doesn't need to be ran asynchronously 2025-02-27 22:12:13 +00:00
akulij
5f13d1d409 change password input method
in previous method if press ctrl-c during password enter terminal echo
kept off. It was possible to fix it to set `stty echo` in sigint
handler, but this solution is more elegant
2025-02-27 22:07:41 +00:00
akulij
d5192456ce handle sigint 2025-02-27 22:07:30 +00:00
akulij
3161afeb3b README: add task to accept another input as hash 2025-02-27 21:36:40 +00:00
akulij
a873717f17 move flags parsing out of main function 2025-02-27 21:27:36 +00:00
3 changed files with 192 additions and 39 deletions

View File

@ -1,6 +1,5 @@
# Generate age keys from passphrase # Generate age keys from passphrase
## Description
This utility (age-passgen) generates secret and public keys (into stdout) from your entered passphrase or piped stdin This utility (age-passgen) generates secret and public keys (into stdout) from your entered passphrase or piped stdin
Strong password highly recomended Strong password highly recomended
@ -10,5 +9,6 @@ Exact amount of required characters can be calculated by formula: $\lceil 256 /
## TODO ## TODO
[X] piped/terminal output as raw/verbose - [X] piped/terminal output as raw/verbose
[ ] handle broken pipe signal since program will so much depend on pipes - [X] handle broken pipe signal since program will so much depend on pipes
- [ ] option to read hex number that will be used instead of hash of password (usefull if user already has sha 256 hash of smth or want to use something else as input instead)

View File

@ -1,14 +1,18 @@
package main package main
import ( import (
"encoding/hex"
"errors" "errors"
"flag" "flag"
"fmt" "fmt"
"io" "io"
"log" "log"
"os" "os"
"os/signal"
"slices" "slices"
"strconv" "strconv"
"strings"
"syscall"
"time" "time"
"unsafe" "unsafe"
@ -31,6 +35,7 @@ Options:
-o, --output OUTPUT Write the result to the file at path OUTPUT. -o, --output OUTPUT Write the result to the file at path OUTPUT.
--raw-output Print stripped keys (without additional text or comments) --raw-output Print stripped keys (without additional text or comments)
--entropy-level VALUE Manages required strenght of password (more info down below) --entropy-level VALUE Manages required strenght of password (more info down below)
--input-type TYPE Type of input from stdin. Can be 'password' (default), 'hash', 'raw'
Mostly similar to age-keygen Mostly similar to age-keygen
Required password strenght can be changes via --entropy-level flag. Possible values Required password strenght can be changes via --entropy-level flag. Possible values
@ -44,39 +49,49 @@ Each word or number is mapped following this list:
- stupid - no limit - stupid - no limit
` `
func main() { type InputType int
log.SetFlags(0)
flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", usage) }
var ( const (
rawOutput bool InputPassword InputType = iota
outputFile string InputHash
entropyLevel string InputRaw
) )
flag.BoolVar(&rawOutput, "raw-output", false, "Print stripped keys (without additional text or comments)") type Flags struct {
flag.StringVar(&outputFile, "o", "", "Write the result to the file at path OUTPUT") RawOutput bool
flag.StringVar(&outputFile, "output", "", "Write the result to the file at path OUTPUT") OutputFile string
flag.StringVar(&entropyLevel, "entropy-level", "medium", "Manages required strenght of password. Read more in --help") EntropyLevel int
flag.Parse() InputType InputType
eLevel, err := parseEntropyLevel(entropyLevel)
if err != nil {
errorf("error while parsing --entropy-level argument: %s\n", err)
} }
passbytes, err := getPasswordBytes() func main() {
setSystemSignalHandlers()
flags, err := parseFlags()
if err != nil {
errorf("error while parsing arguments: %s\n", err)
}
var secretKey [curve25519.ScalarSize]byte
if flags.InputType == InputPassword {
secretKey, err = getInputPassword(flags.EntropyLevel)
if err != nil { if err != nil {
errorf("Failed to get password, error: %s\n", err) errorf("Failed to get password, error: %s\n", err)
} }
valid := isEntropyValid(passbytes, eLevel) } else if flags.InputType == InputHash {
if !valid { secretKey, err = getInputHash()
errorf("You should choose stroger password!!! (or change entropy level, read more with --help)\n") if err != nil {
errorf("Failed to read hash, error: %s\n", err)
}
} else if flags.InputType == InputRaw {
secretKey, err = getInputRaw()
if err != nil {
errorf("Failed to read raw data, error: %s\n", err)
}
} else {
errorf("No such input type implemented!!!")
} }
sum := sha256.Sum256(passbytes) k, err := newX25519IdentityFromScalar(secretKey[:])
k, err := newX25519IdentityFromScalar(sum[:])
if err != nil { if err != nil {
errorf("internal error: %v", err) errorf("internal error: %v", err)
} }
@ -84,8 +99,8 @@ func main() {
// if user is not seeing private keyfile, which also contains public key, // if user is not seeing private keyfile, which also contains public key,
// also duplicate public key it to stderr, // also duplicate public key it to stderr,
// but if user sees public key via stdout, no need for duplication // but if user sees public key via stdout, no need for duplication
if outputFile != "" { if flags.OutputFile != "" {
if !rawOutput { if !flags.RawOutput {
fmt.Printf("Public key: %s\n", k.Recipient()) fmt.Printf("Public key: %s\n", k.Recipient())
} else { } else {
fmt.Printf("%s", k.Recipient()) fmt.Printf("%s", k.Recipient())
@ -93,19 +108,136 @@ func main() {
} }
output := os.Stdout output := os.Stdout
if outputFile != "" { if flags.OutputFile != "" {
output, err = os.Create(outputFile) output, err = os.Create(flags.OutputFile)
if err != nil { if err != nil {
errorf("failed to create output file, error: %s", err) errorf("failed to create output file, error: %s", err)
} }
} }
err = writeSecretKey(output, k, !rawOutput) err = writeSecretKey(output, k, !flags.RawOutput)
if err != nil { if err != nil {
fmt.Printf("Failed to write secret key to file, error: %s\n", err) fmt.Printf("Failed to write secret key to file, error: %s\n", err)
} }
} }
func getInputPassword(entropyLevel int) ([curve25519.ScalarSize]byte, error) {
passbytes, err := getPasswordBytes()
if err != nil {
return [curve25519.ScalarSize]byte{}, err
}
valid := isEntropyValid(passbytes, entropyLevel)
if !valid {
return [curve25519.ScalarSize]byte{}, errors.New("You should choose stroger password!!! (or change entropy level, read more with --help)\n")
}
return sha256.Sum256(passbytes), nil
}
func getInputHash() ([curve25519.ScalarSize]byte, error) {
hashStringBytes, err := getPasswordBytes()
if err != nil {
return [curve25519.ScalarSize]byte{}, err
}
hashString := strings.TrimSpace(string(hashStringBytes))
passbytes, err := hex.DecodeString(hashString)
if err != nil {
fmt.Printf("HEXSTR:%s|\n", hashString)
return [curve25519.ScalarSize]byte{}, errors.New(fmt.Sprintf("Unable to decode hash, error: %s\n", err))
}
if len(passbytes) != curve25519.ScalarSize {
return [curve25519.ScalarSize]byte{}, errors.New(fmt.Sprintf("Wrong input lenght of sha256 hash! (may be it is not a hash at all) Expected %d bytes, got: %d\n", curve25519.ScalarSize, len(passbytes)))
}
// making `possibly` stack allocated out of the one in heap
var key [curve25519.ScalarSize]byte
copy(key[:], passbytes)
return key, nil
}
func getInputRaw() ([curve25519.ScalarSize]byte, error) {
passbytes, err := getPasswordBytes()
if err != nil {
return [curve25519.ScalarSize]byte{}, err
}
if len(passbytes) != curve25519.ScalarSize {
return [curve25519.ScalarSize]byte{}, errors.New(fmt.Sprintf("Wrong amount of entered data! Expected %d bytes, got: %d\n", curve25519.ScalarSize, len(passbytes)))
}
// making `possibly` stack allocated out of the one in heap
var key [curve25519.ScalarSize]byte
copy(key[:], passbytes)
return key, nil
}
func setSystemSignalHandlers() {
go handleSigpipe()
}
func handleSigpipe() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGPIPE)
<-c
errorf("Recieved SIGPIPE. Check if your programs that give input or recieve input do not stops before this one")
os.Exit(1)
}
func parseFlags() (*Flags, error) {
log.SetFlags(0)
flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", usage) }
var (
rawOutput bool
outputFile string
entropyLevel string
inputType string
)
flag.BoolVar(&rawOutput, "raw-output", false, "Print stripped keys (without additional text or comments)")
flag.StringVar(&outputFile, "o", "", "Write the result to the file at path OUTPUT")
flag.StringVar(&outputFile, "output", "", "Write the result to the file at path OUTPUT")
flag.StringVar(&entropyLevel, "entropy-level", "medium", "Manages required strenght of password. Read more in --help")
flag.StringVar(&inputType, "input-type", "password", "Type of input from stdin. Can be 'password' (default), 'hash', 'raw'")
flag.Parse()
eLevel, err := parseEntropyLevel(entropyLevel)
if err != nil {
return nil, err
}
iType, err := parseInputType(inputType)
if err != nil {
return nil, err
}
return &Flags{
RawOutput: rawOutput,
OutputFile: outputFile,
EntropyLevel: eLevel,
InputType: iType,
}, nil
}
func parseInputType(inputType string) (InputType, error) {
m := map[string]InputType{
"password": InputPassword,
"hash": InputHash,
"raw": InputRaw,
}
iType, ok := m[inputType]
if !ok {
return InputPassword, errors.New("wrong input type")
}
return iType, nil
}
func parseEntropyLevel(entropyLevel string) (int, error) { func parseEntropyLevel(entropyLevel string) (int, error) {
if i, err := strconv.Atoi(entropyLevel); err == nil { if i, err := strconv.Atoi(entropyLevel); err == nil {
if i == 0 { if i == 0 {
@ -134,10 +266,17 @@ func isEntropyValid(passbytes []byte, entropyLevel int) bool {
func getPasswordBytes() ([]byte, error) { func getPasswordBytes() ([]byte, error) {
if term.IsTerminal(int(os.Stdin.Fd())) { if term.IsTerminal(int(os.Stdin.Fd())) {
fmt.Fprintf(os.Stderr, "Enter password: ") oldState, err := term.MakeRaw(0)
passbytes, err := term.ReadPassword(int(os.Stdin.Fd())) defer term.Restore(0, oldState)
fmt.Println()
return passbytes, err screen := struct {
io.Reader
io.Writer
}{os.Stdin, os.Stdout}
t := term.NewTerminal(screen, "")
pass, err := t.ReadPassword("Enter pass: ")
return []byte(pass), err
} else { } else {
return io.ReadAll(os.Stdin) return io.ReadAll(os.Stdin)
} }

View File

@ -8,6 +8,20 @@
let pkgs = nixpkgs.legacyPackages.${system}; in let pkgs = nixpkgs.legacyPackages.${system}; in
{ {
devShells.default = import ./shell.nix { inherit pkgs; }; devShells.default = import ./shell.nix { inherit pkgs; };
packages.default = pkgs.buildGoModule {
pname = "age-passgen";
version = "unversioned";
src = ./.;
vendorHash = "sha256-Y6R8c9PzRq0tJ0b06f0LuFfrdFvxQ7h/86a6gg6UOro=";
};
apps.default = {
type = "app";
program = "${self.packages.${system}.default}/bin/age-passgen";
};
} }
); );
} }