Debian Codegraph @

lib/crypto/gpg/gpgbin/gpgbin.go

raw
1 package gpgbin
2
3 import (
4 "bufio"
5 "bytes"
6 "fmt"
7 "io"
8 "os/exec"
9 "strconv"
10 "strings"
11
12 "git.sr.ht/~rjarry/aerc/lib/log"
13 "git.sr.ht/~rjarry/aerc/lib/pinentry"
14 "git.sr.ht/~rjarry/aerc/models"
15 )
16
17 // gpg represents a gpg command with buffers attached to stdout and stderr
18 type gpg struct {
19 cmd *exec.Cmd
20 stdout bytes.Buffer
21 stderr bytes.Buffer
22 }
23
24 // newGpg creates a new gpg command with buffers attached
25 func newGpg(stdin io.Reader, args []string) *gpg {
26 g := new(gpg)
27 g.cmd = exec.Command("gpg", "--status-fd", "2", "--log-file", "/dev/null", "--batch")
28 g.cmd.Args = append(g.cmd.Args, args...)
29 g.cmd.Stdin = stdin
30 g.cmd.Stdout = &g.stdout
31 g.cmd.Stderr = &g.stderr
32
33 pinentry.SetCmdEnv(g.cmd)
34
35 return g
36 }
37
38 // fields returns the field name from --status-fd output. See:
39 // https://github.com/gpg/gnupg/blob/master/doc/DETAILS
40 func field(s string) string {
41 tokens := strings.SplitN(s, " ", 3)
42 if tokens[0] == "[GNUPG:]" {
43 return tokens[1]
44 }
45 return ""
46 }
47
48 // getIdentity returns the identity of the given key
49 func getIdentity(key uint64) string {
50 fpr := fmt.Sprintf("%X", key)
51 cmd := exec.Command("gpg", "--with-colons", "--batch", "--list-keys", fpr)
52
53 var outbuf strings.Builder
54 cmd.Stdout = &outbuf
55 err := cmd.Run()
56 if err != nil {
57 log.Errorf("gpg: failed to get identity: %v", err)
58 return ""
59 }
60 out := strings.Split(outbuf.String(), "\n")
61 for _, line := range out {
62 if strings.HasPrefix(line, "uid") {
63 flds := strings.Split(line, ":")
64 return flds[9]
65 }
66 }
67 return ""
68 }
69
70 // getKeyId returns the 16 digit key id, if key exists
71 func getKeyId(s string, private bool) string {
72 cmd := exec.Command("gpg", "--with-colons", "--batch")
73 listArg := "--list-keys"
74 if private {
75 listArg = "--list-secret-keys"
76 }
77 cmd.Args = append(cmd.Args, listArg, s)
78
79 var outbuf strings.Builder
80 cmd.Stdout = &outbuf
81 err := cmd.Run()
82 if err != nil {
83 log.Errorf("gpg: failed to get key ID: %v", err)
84 return ""
85 }
86 out := strings.Split(outbuf.String(), "\n")
87 for _, line := range out {
88 if strings.HasPrefix(line, "fpr") {
89 flds := strings.Split(line, ":")
90 id := flds[9]
91 return id[len(id)-16:]
92 }
93 }
94 return ""
95 }
96
97 // longKeyToUint64 returns a uint64 version of the given key
98 func longKeyToUint64(key string) (uint64, error) {
99 fpr := string(key[len(key)-16:])
100 fprUint64, err := strconv.ParseUint(fpr, 16, 64)
101 if err != nil {
102 return 0, err
103 }
104 return fprUint64, nil
105 }
106
107 // parse parses the output of gpg --status-fd
108 func parseStatusFd(r io.Reader, md *models.MessageDetails) error {
109 var err error
110 scanner := bufio.NewScanner(r)
111 for scanner.Scan() {
112 line := scanner.Text()
113 if field(line) == "PLAINTEXT_LENGTH" {
114 continue
115 }
116 log.Tracef(line)
117
118 switch field(line) {
119 case "ENC_TO":
120 md.IsEncrypted = true
121 case "DECRYPTION_KEY":
122 md.DecryptedWithKeyId, err = parseDecryptionKey(line)
123 md.DecryptedWith = getIdentity(md.DecryptedWithKeyId)
124 if err != nil {
125 return err
126 }
127 case "DECRYPTION_FAILED":
128 return EncryptionFailed
129 case "NEWSIG":
130 md.IsSigned = true
131 case "GOODSIG":
132 t := strings.SplitN(line, " ", 4)
133 md.SignedByKeyId, err = longKeyToUint64(t[2])
134 if err != nil {
135 return err
136 }
137 md.SignedBy = t[3]
138 case "BADSIG":
139 t := strings.SplitN(line, " ", 4)
140 md.SignedByKeyId, err = longKeyToUint64(t[2])
141 if err != nil {
142 return err
143 }
144 md.SignatureError = "gpg: invalid signature"
145 md.SignedBy = t[3]
146 case "EXPSIG":
147 t := strings.SplitN(line, " ", 4)
148 md.SignedByKeyId, err = longKeyToUint64(t[2])
149 if err != nil {
150 return err
151 }
152 md.SignatureError = "gpg: expired signature"
153 md.SignedBy = t[3]
154 case "EXPKEYSIG":
155 t := strings.SplitN(line, " ", 4)
156 md.SignedByKeyId, err = longKeyToUint64(t[2])
157 if err != nil {
158 return err
159 }
160 md.SignatureError = "gpg: signature made with expired key"
161 md.SignedBy = t[3]
162 case "REVKEYSIG":
163 t := strings.SplitN(line, " ", 4)
164 md.SignedByKeyId, err = longKeyToUint64(t[2])
165 if err != nil {
166 return err
167 }
168 md.SignatureError = "gpg: signature made with revoked key"
169 md.SignedBy = t[3]
170 case "ERRSIG":
171 t := strings.SplitN(line, " ", 9)
172 md.SignedByKeyId, err = longKeyToUint64(t[2])
173 if err != nil {
174 return err
175 }
176 if t[7] == "9" {
177 md.SignatureError = "gpg: missing public key"
178 }
179 if t[7] == "4" {
180 md.SignatureError = "gpg: unsupported algorithm"
181 }
182 md.SignedBy = "(unknown signer)"
183 case "INV_RECP":
184 t := strings.SplitN(line, " ", 4)
185 if t[2] == "10" {
186 return fmt.Errorf("gpg: public key of %s is not trusted", t[3])
187 }
188 case "SIG_CREATED":
189 fields := strings.Split(line, " ")
190 micalg, err := strconv.Atoi(fields[4])
191 if err != nil {
192 return MicalgNotFound
193 }
194 md.Micalg = micalgs[micalg]
195 case "VALIDSIG":
196 fields := strings.Split(line, " ")
197 micalg, err := strconv.Atoi(fields[9])
198 if err != nil {
199 return MicalgNotFound
200 }
201 md.Micalg = micalgs[micalg]
202 case "NODATA":
203 t := strings.SplitN(line, " ", 3)
204 if t[2] == "4" {
205 md.SignatureError = "gpg: no signature packet found"
206 }
207 if t[2] == "1" {
208 return NoValidOpenPgpData
209 }
210 case "FAILURE":
211 if line == "[GNUPG:] FAILURE gpg-exit 33554433" {
212 log.Errorf("skipping gpg failure: gpg-exit 33554433")
213 break
214 }
215 return fmt.Errorf("%s", strings.TrimPrefix(line, "[GNUPG:] "))
216 }
217 }
218 return nil
219 }
220
221 // parseDecryptionKey returns primary key from DECRYPTION_KEY line
222 func parseDecryptionKey(l string) (uint64, error) {
223 key := strings.Split(l, " ")[3]
224 fpr := string(key[len(key)-16:])
225 fprUint64, err := longKeyToUint64(fpr)
226 if err != nil {
227 return 0, err
228 }
229 getIdentity(fprUint64)
230 return fprUint64, nil
231 }
232
233 type StatusFdParsingError int32
234
235 const (
236 EncryptionFailed StatusFdParsingError = iota + 1
237 MicalgNotFound
238 NoValidOpenPgpData
239 )
240
241 func (err StatusFdParsingError) Error() string {
242 switch err {
243 case EncryptionFailed:
244 return "gpg: decryption failed"
245 case MicalgNotFound:
246 return "gpg: micalg not found"
247 case NoValidOpenPgpData:
248 return "gpg: no valid OpenPGP data found"
249 default:
250 return "gpg: unknown status fd parsing error"
251 }
252 }
253
254 // micalgs represent hash algorithms for signatures. These are ignored by many
255 // email clients, but can be used as an additional verification so are sent.
256 // Both gpgmail and pgpmail implementations in aerc check for matching micalgs
257 var micalgs = map[int]string{
258 1: "pgp-md5",
259 2: "pgp-sha1",
260 3: "pgp-ripemd160",
261 8: "pgp-sha256",
262 9: "pgp-sha384",
263 10: "pgp-sha512",
264 11: "pgp-sha224",
265 }