/
gpg2.go
264 lines (225 loc) · 7.73 KB
/
gpg2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package gpg2
import (
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"sync"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"go.mozilla.org/autograph/signer"
)
const (
// Type of this signer is "gpg2" represents a signer that
// shells out to gpg2 to sign artifacts since the golang "pgp"
// signer doesn't support signing with subkeys
// https://godoc.org/golang.org/x/crypto/openpgp#ArmoredDetachSign
// or loading keys exported with gnu-dummy s2k encrypted
// passphrases https://github.com/golang/go/issues/13605
Type = "gpg2"
keyRingFilename = "autograph_gpg2_keyring.gpg"
secRingFilename = "autograph_gpg2_secring.gpg"
)
var isAlphanumeric = regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString
// gpg2 fails when multiple signers are called at in parallel so we serialize
// invoking this signer through a global mutex. For more info on this particular
// piece of gpg sadness, see https://answers.launchpad.net/duplicity/+question/296122
var serializeSigning sync.Mutex
// GPG2Signer holds the configuration of the signer
type GPG2Signer struct {
signer.Configuration
// KeyID is the fingerprint of the gpg key or subkey to use
// e.g. 0xA2B637F535A86009
KeyID string
// passphrase is the optional passphrase to use decrypt the
// gpg secret key
passphrase string
// tmpDir is the signer's temporary working directory. It
// holds the gpg sec and keyrings
tmpDir string
}
// New initializes a pgp signer using a configuration
func New(conf signer.Configuration) (s *GPG2Signer, err error) {
s = new(GPG2Signer)
if conf.Type != Type {
return nil, errors.Errorf("gpg2: invalid type %q, must be %q", conf.Type, Type)
}
s.Type = conf.Type
if conf.ID == "" {
return nil, errors.New("gpg2: missing signer ID in signer configuration")
}
s.ID = conf.ID
if conf.PrivateKey == "" {
return nil, errors.New("gpg2: missing private key in signer configuration")
}
s.PrivateKey = conf.PrivateKey
if conf.PublicKey == "" {
return nil, errors.New("gpg2: missing public key in signer configuration")
}
s.PublicKey = conf.PublicKey
if conf.KeyID == "" {
return nil, errors.New("gpg2: missing gpg key ID in signer configuration")
}
// validate KeyID since it is injected into the temp dir
// prefix and could be used for command injection
if !isAlphanumeric(conf.KeyID) {
return nil, errors.New("gpg2: non-alphanumeric key ID in signer configuration")
}
s.KeyID = conf.KeyID
s.passphrase = conf.Passphrase
s.tmpDir, err = createKeyRing(s)
if err != nil {
return nil, errors.Wrap(err, "gpg2: error creating keyring")
}
return
}
// createKeyRing creates a temporary gpg sec and keyrings, loads the
// private and public keys for the signer, and returns the temporary
// director holding the rings
func createKeyRing(s *GPG2Signer) (string, error) {
// reuse keyring in tempdir
prefix := fmt.Sprintf("autograph_%s_%s", s.Type, s.KeyID)
dir, err := ioutil.TempDir("", prefix)
if err != nil {
return "", errors.Wrap(err, "gpg2: error creating tempdir for keyring")
}
// write the public key to a temp file in our signer's temp dir
tmpPublicKeyFile, err := ioutil.TempFile(dir, "gpg2_publickey")
if err != nil {
return "", errors.Wrap(err, "gpg2: error creating tempfile for public key")
}
defer os.Remove(tmpPublicKeyFile.Name())
err = ioutil.WriteFile(tmpPublicKeyFile.Name(), []byte(s.PublicKey), 0755)
if err != nil {
return "", errors.Wrap(err, "gpg2: error writing public key to tempfile")
}
// write the private key to a temp file in our signer's temp dir
tmpPrivateKeyFile, err := ioutil.TempFile(dir, "gpg2_privatekey")
if err != nil {
return "", errors.Wrap(err, "gpg2: error creating tempfile for private key")
}
defer os.Remove(tmpPrivateKeyFile.Name())
err = ioutil.WriteFile(tmpPrivateKeyFile.Name(), []byte(s.PrivateKey), 0755)
if err != nil {
return "", errors.Wrap(err, "gpg2: error writing private key to tempfile")
}
keyRingPath := filepath.Join(dir, keyRingFilename)
secRingPath := filepath.Join(dir, secRingFilename)
// call gpg to create a new keyring and load the public key in it
gpgLoadPublicKey := exec.Command("gpg",
"--no-default-keyring",
"--keyring", keyRingPath,
"--secret-keyring", secRingPath,
"--no-tty",
"--batch",
"--yes",
"--import", tmpPublicKeyFile.Name(),
)
out, err := gpgLoadPublicKey.CombinedOutput()
if err != nil {
return "", errors.Wrapf(err, "gpg2: failed to load public key into keyring: %s\n%s", err, out)
}
log.Debugf(fmt.Sprintf("gpg2: loaded public key %s", string(out)))
// call gpg to load the private key in it
gpgLoadPrivateKey := exec.Command("gpg", "--no-default-keyring",
"--keyring", keyRingPath,
"--secret-keyring", secRingPath,
"--no-tty",
"--batch",
"--yes",
"--import", tmpPrivateKeyFile.Name())
out, err = gpgLoadPrivateKey.CombinedOutput()
if err != nil {
return "", errors.Wrapf(err, "gpg2: failed to load private key into keyring: %s\n%s", err, out)
}
log.Debugf(fmt.Sprintf("gpg2: loaded private key %s", string(out)))
return dir, nil
}
// AtExit removes the temp dir containing the signer key and sec rings
// when the app is shut down gracefully
func (s *GPG2Signer) AtExit() error {
err := os.RemoveAll(s.tmpDir)
if err == nil {
log.Infof("gpg2: cleaned up %s in exit handler", s.tmpDir)
}
return err
}
// Config returns the configuration of the current signer
func (s *GPG2Signer) Config() signer.Configuration {
return signer.Configuration{
ID: s.ID,
Type: s.Type,
PrivateKey: s.PrivateKey,
PublicKey: s.PublicKey,
}
}
// SignData takes data and returns an armored signature with pgp header and footer
func (s *GPG2Signer) SignData(data []byte, options interface{}) (signer.Signature, error) {
keyRingPath := filepath.Join(s.tmpDir, keyRingFilename)
secRingPath := filepath.Join(s.tmpDir, secRingFilename)
// write the input to a temp file
tmpContentFile, err := ioutil.TempFile(s.tmpDir, fmt.Sprintf("gpg2_%s_input", s.ID))
if err != nil {
return nil, errors.Wrap(err, "gpg2: failed to create tempfile for input to sign")
}
defer os.Remove(tmpContentFile.Name())
ioutil.WriteFile(tmpContentFile.Name(), data, 0755)
// take a mutex to prevent multiple invocations of gpg in parallel
serializeSigning.Lock()
defer serializeSigning.Unlock()
gpgVerifySig := exec.Command("gpg",
"--no-default-keyring",
"--keyring", keyRingPath,
"--secret-keyring", secRingPath,
"--armor",
"--no-tty",
"--batch",
"--yes",
"--sign-with", s.KeyID,
"--output", "-",
"--pinentry-mode", "loopback",
"--passphrase-fd", "0",
"--detach-sign", tmpContentFile.Name(),
)
stdin, err := gpgVerifySig.StdinPipe()
if err != nil {
return nil, errors.Wrap(err, "gpg2: failed to create stdin pipe for sign cmd")
}
io.WriteString(stdin, s.passphrase)
stdin.Close()
out, err := gpgVerifySig.CombinedOutput()
if err != nil {
return nil, errors.Wrapf(err, "gpg2: failed to sign input %s\n%s", err, out)
}
log.Debugf("signed as:\n%s\n", string(out))
sig := new(Signature)
sig.Data = out
return sig, nil
}
// Signature is a PGP signature
type Signature struct {
Data []byte
}
// Marshal doesn't do much for this signer. sig.Data already contains
// an armored signature, so we simply convert it to a string and return it
func (sig *Signature) Marshal() (string, error) {
return string(sig.Data), nil
}
// Unmarshal also does very little. It simply converts the armored signature
// from a string to an []byte, but doesn't attempt to parse it, and returns it
// as a Signature
func Unmarshal(sigstr string) (signer.Signature, error) {
sig := new(Signature)
sig.Data = []byte(sigstr)
return sig, nil
}
// Options are not implemented for this signer
type Options struct {
}
// GetDefaultOptions returns default options of the signer
func (s *GPG2Signer) GetDefaultOptions() interface{} {
return Options{}
}