forked from keybase/client
/
pgp_pull.go
306 lines (265 loc) · 8.33 KB
/
pgp_pull.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package engine
import (
"fmt"
"time"
"github.com/keybase/client/go/libkb"
keybase1 "github.com/keybase/client/go/protocol/keybase1"
)
type PGPPullEngineArg struct {
UserAsserts []string
}
type PGPPullEngine struct {
listTrackingEngine *ListTrackingEngine
userAsserts []string
gpgClient *libkb.GpgCLI
libkb.Contextified
}
func NewPGPPullEngine(g *libkb.GlobalContext, arg *PGPPullEngineArg) *PGPPullEngine {
return &PGPPullEngine{
listTrackingEngine: NewListTrackingEngine(g, &ListTrackingEngineArg{}),
userAsserts: arg.UserAsserts,
Contextified: libkb.NewContextified(g),
}
}
func (e *PGPPullEngine) Name() string {
return "PGPPull"
}
func (e *PGPPullEngine) Prereqs() Prereqs {
return Prereqs{}
}
func (e *PGPPullEngine) RequiredUIs() []libkb.UIKind {
return []libkb.UIKind{
libkb.LogUIKind,
}
}
func (e *PGPPullEngine) SubConsumers() []libkb.UIConsumer {
return []libkb.UIConsumer{e.listTrackingEngine}
}
func proofSetFromUserSummary(summary keybase1.UserSummary) *libkb.ProofSet {
proofs := []libkb.Proof{
{Key: "keybase", Value: summary.Username},
{Key: "uid", Value: summary.Uid.String()},
}
return libkb.NewProofSet(proofs)
}
func (e *PGPPullEngine) getTrackedUserSummaries(m libkb.MetaContext) ([]keybase1.UserSummary, []string, error) {
err := RunEngine2(m, e.listTrackingEngine)
if err != nil {
return nil, nil, err
}
allTrackedSummaries := e.listTrackingEngine.TableResult().Users
// Without any userAsserts specified, just all summaries and no leftovers.
if e.userAsserts == nil || len(e.userAsserts) == 0 {
return allTrackedSummaries, nil, nil
}
// With userAsserts specified, return only those summaries. If an assert
// doesn't match any tracked users, that's an error. If an assert matches
// more than one tracked user, that is also an error. If multiple
// assertions match the same user, that's fine.
// First parse all the assertion expressions.
parsedAsserts := make(map[string]libkb.AssertionExpression)
for _, assertString := range e.userAsserts {
assertExpr, err := libkb.AssertionParseAndOnly(e.G().MakeAssertionContext(m), assertString)
if err != nil {
return nil, nil, err
}
parsedAsserts[assertString] = assertExpr
}
// Then loop over all the tracked users, keeping track of which expressions
// have matched before.
matchedSummaries := make(map[string]keybase1.UserSummary)
assertionsUsed := make(map[string]bool)
for _, summary := range allTrackedSummaries {
proofSet := proofSetFromUserSummary(summary)
for assertStr, parsedAssert := range parsedAsserts {
if parsedAssert.MatchSet(*proofSet) {
if assertionsUsed[assertStr] {
return nil, nil, fmt.Errorf("Assertion \"%s\" matched more than one tracked user.", assertStr)
}
assertionsUsed[assertStr] = true
matchedSummaries[summary.Username] = summary
}
}
}
var leftovers []string
// Make sure every assertion found a match.
for _, assertString := range e.userAsserts {
if !assertionsUsed[assertString] {
m.Info("Assertion \"%s\" did not match any tracked users.", assertString)
leftovers = append(leftovers, assertString)
}
}
matchedList := []keybase1.UserSummary{}
for _, summary := range matchedSummaries {
matchedList = append(matchedList, summary)
}
return matchedList, leftovers, nil
}
func (e *PGPPullEngine) runLoggedOut(m libkb.MetaContext) error {
if len(e.userAsserts) == 0 {
return libkb.PGPPullLoggedOutError{}
}
t := time.Now()
for i, assertString := range e.userAsserts {
t = e.rateLimit(t, i)
if err := e.processUserWithIdentify(m, assertString); err != nil {
return err
}
}
return nil
}
func (e *PGPPullEngine) processUserWithIdentify(m libkb.MetaContext, u string) error {
m.Debug("Processing with identify: %s", u)
iarg := keybase1.Identify2Arg{
UserAssertion: u,
ForceRemoteCheck: true,
AlwaysBlock: true,
NeedProofSet: true, // forces prompt even if we declined before
}
topts := keybase1.TrackOptions{
LocalOnly: true,
ForPGPPull: true,
}
ieng := NewResolveThenIdentify2WithTrack(m.G(), &iarg, topts)
if err := RunEngine2(m, ieng); err != nil {
m.Info("identify run err: %s", err)
return err
}
// prompt if the identify is correct
result := ieng.ConfirmResult()
if !result.IdentityConfirmed {
m.Warning("Not confirmed; skipping key import")
return nil
}
idRes, err := ieng.Result(m)
if err != nil {
return err
}
// with more plumbing, there is likely a more efficient way to get this identified user out
// of the identify2 engine, but `pgp pull` is not likely to be called often.
arg := libkb.NewLoadUserArgWithMetaContext(m).WithUID(idRes.Upk.GetUID())
user, err := libkb.LoadUser(arg)
if err != nil {
return err
}
return e.exportKeysToGPG(m, user, nil)
}
func (e *PGPPullEngine) Run(m libkb.MetaContext) error {
e.gpgClient = libkb.NewGpgCLI(m.G(), m.UIs().LogUI)
err := e.gpgClient.Configure(m)
if err != nil {
return err
}
if ok, _ := isLoggedIn(m); !ok {
return e.runLoggedOut(m)
}
return e.runLoggedIn(m)
}
func (e *PGPPullEngine) runLoggedIn(m libkb.MetaContext) error {
summaries, leftovers, err := e.getTrackedUserSummaries(m)
// leftovers contains unmatched assertions, likely users
// we want to pull but we do not track.
if err != nil {
return err
}
pkLookup := make(map[keybase1.UID][]string)
err = m.G().GetFullSelfer().WithSelf(m.Ctx(), func(user *libkb.User) error {
if user == nil {
return libkb.UserNotFoundError{}
}
var trackList []*libkb.TrackChainLink
if idTable := user.IDTable(); idTable != nil {
trackList = idTable.GetTrackList()
}
for _, track := range trackList {
trackedUID, err := track.GetTrackedUID()
if err != nil {
return err
}
keys, err := track.GetTrackedKeys()
if err != nil {
return err
}
for _, key := range keys {
pkLookup[trackedUID] = append(pkLookup[trackedUID], key.Fingerprint.String())
}
}
return nil
})
if err != nil {
return err
}
// Loop over the list of all users we track.
t := time.Now()
for i, userSummary := range summaries {
t = e.rateLimit(t, i)
// Compute the set of tracked pgp fingerprints. LoadUser will fetch key
// data from the server, and we will compare it against this.
trackedFingerprints := make(map[string]bool)
fprs, ok := pkLookup[userSummary.Uid]
if !ok {
fprs = []string{}
}
for _, pubKey := range fprs {
if pubKey != "" {
trackedFingerprints[pubKey] = true
}
}
// Get user data from the server.
user, err := libkb.LoadUser(
libkb.NewLoadUserByNameArg(e.G(), userSummary.Username).
WithPublicKeyOptional())
if err != nil {
m.Error("Failed to load user %s: %s", userSummary.Username, err)
continue
}
if user.GetStatus() == keybase1.StatusCode_SCDeleted {
m.Debug("User %q is deleted, skipping", userSummary.Username)
continue
}
if err = e.exportKeysToGPG(m, user, trackedFingerprints); err != nil {
return err
}
}
// Loop over unmatched list and process with identify prompts.
for i, assertString := range leftovers {
t = e.rateLimit(t, i)
if err := e.processUserWithIdentify(m, assertString); err != nil {
return err
}
}
return nil
}
func (e *PGPPullEngine) exportKeysToGPG(m libkb.MetaContext, user *libkb.User, tfp map[string]bool) error {
for _, bundle := range user.GetActivePGPKeys(false) {
// Check each key against the tracked set.
if tfp != nil && !tfp[bundle.GetFingerprint().String()] {
m.Warning("Keybase says that %s owns key %s, but you have not tracked this fingerprint before.", user.GetName(), bundle.GetFingerprint())
continue
}
if err := e.gpgClient.ExportKey(m, *bundle, false /* export public key only */, false /* no batch */); err != nil {
m.Warning("Failed to import %'s public key %s: %s", user.GetName(), bundle.GetFingerprint(), err.Error())
continue
}
m.Info("Imported key for %s.", user.GetName())
}
return nil
}
func (e *PGPPullEngine) rateLimit(start time.Time, index int) time.Time {
// server currently limiting to 32 req/s, but there can be 4 requests for each loaduser call.
const loadUserPerSec = 4
if index == 0 {
return start
}
if index%loadUserPerSec != 0 {
return start
}
d := time.Second - time.Since(start)
if d > 0 {
e.G().Log.Debug("sleeping for %s to slow down api requests", d)
time.Sleep(d)
}
return time.Now()
}