forked from tangled.org/core
Monorepo for Tangled — https://tangled.org
1package crypto 2 3import ( 4 "bytes" 5 "crypto/sha256" 6 "encoding/base64" 7 "fmt" 8 "strings" 9 10 "github.com/hiddeco/sshsig" 11 "golang.org/x/crypto/ssh" 12 "tangled.sh/tangled.sh/core/types" 13) 14 15func VerifySignature(pubKey, signature, payload []byte) (error, bool) { 16 pub, _, _, _, err := ssh.ParseAuthorizedKey(pubKey) 17 if err != nil { 18 return fmt.Errorf("failed to parse public key: %w", err), false 19 } 20 21 sig, err := sshsig.Unarmor(signature) 22 if err != nil { 23 return fmt.Errorf("failed to parse signature: %w", err), false 24 } 25 26 buf := bytes.NewBuffer(payload) 27 sshsig.Verify(buf, sig, pub, sshsig.HashSHA256, "git") 28 return err, err == nil 29} 30 31// VerifyCommitSignature reconstructs the payload used to sign a commit. This is 32// essentially the git cat-file output but without the gpgsig header. 33// 34// Caveats: signature verification will fail on commits with more than one parent, 35// i.e. merge commits, because types.NiceDiff doesn't carry more than one Parent field 36// and we are unable to reconstruct the payload correctly. 37// 38// Ideally this should directly operate on an *object.Commit. 39func VerifyCommitSignature(pubKey string, commit types.NiceDiff) (error, bool) { 40 signature := commit.Commit.PGPSignature 41 42 author := bytes.NewBuffer([]byte{}) 43 committer := bytes.NewBuffer([]byte{}) 44 commit.Commit.Author.Encode(author) 45 commit.Commit.Committer.Encode(committer) 46 47 payload := strings.Builder{} 48 49 fmt.Fprintf(&payload, "tree %s\n", commit.Commit.Tree) 50 fmt.Fprintf(&payload, "parent %s\n", commit.Commit.Parent) 51 fmt.Fprintf(&payload, "author %s\n", author.String()) 52 fmt.Fprintf(&payload, "committer %s\n", committer.String()) 53 if commit.Commit.ChangedId != "" { 54 fmt.Fprintf(&payload, "change-id %s\n", commit.Commit.ChangedId) 55 } 56 fmt.Fprintf(&payload, "\n%s", commit.Commit.Message) 57 58 return VerifySignature([]byte(pubKey), []byte(signature), []byte(payload.String())) 59} 60 61// SSHFingerprint computes the fingerprint of the supplied ssh pubkey. 62func SSHFingerprint(pubKey string) (string, error) { 63 pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubKey)) 64 if err != nil { 65 return "", err 66 } 67 68 hash := sha256.Sum256(pk.Marshal()) 69 return "SHA256:" + base64.StdEncoding.EncodeToString(hash[:]), nil 70}