Merge pull request #2 from felschr/main

fix implementation & clean up
This commit is contained in:
Pablo Ovelleiro Corral 2024-03-27 18:35:56 +01:00 committed by GitHub
commit 9d5161d5e4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 87 additions and 177 deletions

View file

@ -1,11 +1,8 @@
1. I have a GPG keypair in the same format as the one provided in `test-key.asc`. It is `ed25519`.
2. That key was used to encrypt a file with [age encryption](https://github.com/FiloSottile/age) as shown below
3. I want to decrypt that file, but only have a GPG secret key, as I couldn't
find out how to derive a SSH or age key from it.
# gpg2age
**GOAL**: Derive an age key from the provided GPG key that decrypt the file as
shown below. A SSH key is also enough, since it can be used with `ssh-to-age` to
derive the age key.
Derive private ed25519 SSH key from private PGP key.
GPG itself only supports exporting _public_ SSH keys and other tools don't work for ed25519 keys.
##### Notes:
@ -13,60 +10,47 @@ derive the age key.
- Work on `gnupg` was started for this feature, but never finished see this
issue and commit: https://dev.gnupg.org/T6647
## Example
## Instructions
Example key provided in `test-key.asc` to be imported. Use `--homedir` with
`gpg` to set a temporary `.gnupg` directory
First you need to export your PGP key from GPG:
```sh
gpg --homedir ./gnupg --import test-key.asc impure ❄ ssh-to-age age
gpg: WARNING: unsafe permissions on homedir '/home/pinpox/code/github.com/pinpox/gpg2age/./gnupg'
gpg: key 76188CF30717B54E: public key "test (test) <test@test.com>" imported
gpg: key 76188CF30717B54E: secret key imported
gpg: Total number processed: 1
gpg: imported: 1
gpg: secret keys read: 1
gpg: secret keys imported: 1
gpg --homedir ./gnupg_testkey/ -K
/home/pinpox/code/github.com/pinpox/gpg2age/./gnupg_testkey/pubring.kbx
-----------------------------------------------------------------------
sec ed25519 2024-03-25 [C]
9FE4D484B69DB9F5C7AA208E76188CF30717B54E
uid [ultimate] test (test) <test@test.com>
ssb ed25519 2024-03-25 [S]
ssb cv25519 2024-03-25 [E]
ssb ed25519 2024-03-25 [A]
gpg2 --export-secret-keys --armor test@test.test >priv-gpg
```
### Get age key and encrypt test file
Then identify the public SSH key that was used to encrypt your secret.
You can search for your GitHub username in: https://fluence-dao.s3.eu-west-1.amazonaws.com/metadata.json
If you have multiple subkeys, usually it is the authenticate key highlighted with `[A]` in the output of:
```sh
gpg --homedir ./gnupg --export-ssh-key 9FE4D484B69DB9F5C7AA208E76188CF30717B54E
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICYvKXGcG4a19tTT0Rycbn+D0r/YlKltLJ9dY2gR/Fjx openpgp:0x47C9F3FF
gpg --list-secret-keys --with-keygrip
```
### Derive private SSH key
```sh
gpg --homedir ./gnupg --export-ssh-key 9FE4D484B69DB9F5C7AA208E76188CF30717B54E | ssh-to-age impure ❄ ssh-to-age
age18s8m9hvlrwvltgys4lafyyqe356ntc7e06t4kd2nccqm5amsaa2s878mju # saved as age-public-key
go run main.go
```
It'll ask you for the path to your private PGP key, followed by choosing the key/subkey and if your PGP key is encrypted it'll ask for the passphrase.
In the output, verify that the public SSH key printed matches the one in `metadata.json`.
If it matches, the last part of the output it will print the matching private SSH key.
You can save the key to a file and use how you want.
### Example: Decrypt age files
If you want to decrypt a file that was encryptd by `age` with your public SSH key, you can just use `age` as normal to decrypt the file using the SSH private key that we've got in the previous step:
```sh
age --encrypt -R age-public-key testfile.txt > testfile.txt.age
age --decrypt --identity ./ssh-secret-key --output decrypted ./testfile.txt.age
```
### Get secret age key
### Support & Donations
```sh
go run main.go impure ❄ ssh-to-age age
AGE-SECRET-KEY-165W948VSG5QEM0RPEUX8T3K4YXJT2WF83C2GXQH8Q3Q0ZHCTH44SSV0H34 # saved as age-secret-key
```
This project was built with lots of headaches by [pinpox](https://github.com/pinpox/) & [felschr](https://github.com/felschr/). If you need help, feel free to contact us.
### Try to decrypt
```sh
age --decrypt --identity age-secret-key --output decrypted testfile.txt.age impure ❄ ssh-to-age age
age: error: no identity matched any of the recipients
age: report unexpected or unhelpful errors at https://filippo.io/age/report
```
FAIL :(
And if you want to thank us, you can send us any crypto or token to our Ethereum / Polygon wallets 😊:
pinpox: `0x3d479e19ae8d1a67becdaeaf8d2d37c8e425bd03`
felschr: `0xD66753D737603E18018281E298Df86DE402d313E`

2
go.mod
View file

@ -3,9 +3,7 @@ module gpg2age
go 1.21.8
require (
github.com/Mic92/ssh-to-age v0.0.0-20240304065525-796b05d6e3b3
github.com/ProtonMail/go-crypto v1.0.0
github.com/davecgh/go-spew v1.1.1
golang.org/x/crypto v0.20.0
golang.org/x/term v0.18.0
)

4
go.sum
View file

@ -1,13 +1,9 @@
github.com/Mic92/ssh-to-age v0.0.0-20240304065525-796b05d6e3b3 h1:YT+DB0TTQ/Li1AQOAAP20k2kCT3XndzsprKgTg5GCIc=
github.com/Mic92/ssh-to-age v0.0.0-20240304065525-796b05d6e3b3/go.mod h1:M/OUOt0/3WI/tYzEYBhQNyU5OB1YStcJEkUaTDnjxJI=
github.com/ProtonMail/go-crypto v1.0.0 h1:LRuvITjQWX+WIfr930YHG2HNfjR1uOfyf5vE0kC2U78=
github.com/ProtonMail/go-crypto v1.0.0/go.mod h1:EjAoLdwvbIOoOQr3ihjnSoLZRtE8azugULFRteWMNc0=
github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
github.com/cloudflare/circl v1.3.3/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA=
github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU=
github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=

98
main.go
View file

@ -1,13 +1,11 @@
package main
import (
"crypto/sha512"
"encoding/pem"
"fmt"
"log"
"os"
"syscall"
"strings"
"encoding/pem"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/ProtonMail/go-crypto/openpgp/armor"
@ -16,18 +14,9 @@ import (
"crypto/ed25519"
"errors"
"github.com/Mic92/ssh-to-age/bech32"
"github.com/davecgh/go-spew/spew"
"golang.org/x/term"
"golang.org/x/crypto/curve25519"
"golang.org/x/crypto/ssh"
// "bytes"
// "golang.org/x/crypto/ssh"
// "golang.org/x/crypto/curve25519"
// "https://pkg.go.dev/crypto/ed25519#PrivateKey
// "crypto/ed25519"ccc1be8d-24dc-41ad-9d66-b657711419d7
"golang.org/x/term"
"reflect"
// "filippo.io/edwards25519"
)
func readEntity(keypath string) (*openpgp.Entity, error) {
@ -49,45 +38,28 @@ var (
UnsupportedKeyType = errors.New("only ed25519 keys are supported")
)
func ed25519PrivateKeyToCurve25519(pk ed25519.PrivateKey) ([]byte, error) {
h := sha512.New()
_, err := h.Write(pk.Seed())
if err != nil {
return []byte{}, err
}
out := h.Sum(nil)
return out[:curve25519.ScalarSize], nil
}
func SSHPrivateKeyToAge(bytes []byte) (*string, error) {
s, err := bech32.Encode("AGE-SECRET-KEY-", bytes)
if err != nil {
return nil, err
}
s = strings.ToUpper(s)
return &s, nil
}
func main() {
// TODO turn these into CLI inputs
// keyfile := "/home/pinpox/gnutmp/0xA5BCEFD22D30118A.priv.asc"
keyfile := "./test-key.asc"
var keyfile string
log.Println("Enter path to private PGP key (default: ./priv.asc):")
_, err := fmt.Scanf("%s", &keyfile)
if err != nil && err.Error() == "unexpected newline" {
keyfile := "./priv.asc"
} else if err != nil {
log.Fatal(err)
}
e, err := readEntity(keyfile)
if err != nil {
log.Fatal(err)
}
spew.Config.MaxDepth = 2
spew.Config.Indent = " "
log.Println("Keys:")
log.Println("[0]", e.PrimaryKey.KeyIdString()+" (primary)")
for i := 0; i < len(e.Subkeys); i++ {
log.Println(fmt.Sprintf("[%d]", i+1), e.Subkeys[i].PublicKey.KeyIdString()+" (subkey)")
}
log.Println("Please choose a key by index (default: 0):")
log.Println("Choose key by index (default: 0):")
var keyIndex int
_, err = fmt.Scanf("%d", &keyIndex)
@ -123,62 +95,22 @@ func main() {
if !ok {
log.Fatal("failed to cast")
}
// spew.Dump(castkey)
// get public key as OpenSSH key
log.Println("public key type:", reflect.TypeOf(castkey.PublicKey))
var pubkey ed25519.PublicKey = castkey.PublicKey.X
agePub, err := bech32.Encode("age", pubkey)
if err != nil {
log.Fatal(err)
}
log.Println("public age key:", string(agePub))
sshPub, err := ssh.NewPublicKey(pubkey)
if err != nil {
log.Fatal(err)
}
// log.Println("public key SSH key wire format:", sshPub.Marshal())
// log.Println("public key SHA256:", ssh.FingerprintSHA256(sshPub))
log.Println("public SSH key:", string(ssh.MarshalAuthorizedKey(sshPub)))
log.Println("public SSH key:\n" + string(ssh.MarshalAuthorizedKey(sshPub)))
// TODO: are these the correct bytes?
// var privkey ed25519.PrivateKey = castkey.D
// var privkey ed25519.PrivateKey = castkey.MarshalByteSecret()
var privkey = ed25519.NewKeyFromSeed(castkey.D)
// TODO is this right?
bytes, err := ed25519PrivateKeyToCurve25519(privkey)
privPem, err := ssh.MarshalPrivateKey(&privkey, "")
if err != nil {
log.Fatal(err)
}
// bytes = privkee
// TODO trying to get private key as age key
agekey, err := SSHPrivateKeyToAge(bytes)
if err != nil {
log.Fatal(err)
}
fmt.Println(*agekey)
// TODO trying to get private key as OpenSSH key
privPem, err := ssh.MarshalPrivateKey(privkey, "")
if err != nil {
log.Fatal(err)
}
if err := pem.Encode(os.Stdout, privPem); err != nil {
log.Fatal(err)
}
// TODO make sure public key is still the same
var priv ed25519.PrivateKey = bytes
var pubkey2 = priv.Public()
// var pubkey2 = privkey.Public()
sshPub2, err := ssh.NewPublicKey(pubkey2)
if err != nil {
log.Fatal(err)
}
log.Println("verify public SSH key:", string(ssh.MarshalAuthorizedKey(sshPub2)))
privateKeyPem := pem.EncodeToMemory(privPem)
log.Println("Private SSH key:\n" + string(privateKeyPem))
}