-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathkeybase.go
420 lines (370 loc) · 10.7 KB
/
keybase.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"time"
"github.com/gokyle/keybase/api"
"github.com/gokyle/keybase/openpgp"
"github.com/gokyle/readpass"
)
func zero(in []byte) {
for i := range in {
in[i] ^= in[i]
}
}
func login(username string) (session *api.Session, err error) {
start, err := api.GetSalt(username)
if err != nil {
return
}
password, err := readpass.PasswordPromptBytes("keybase.io password: ")
if err != nil {
return
}
session, err = api.Login(username, password, start)
zero(password)
return
}
const displayTime = "2006-01-02 15:04 MST"
func unixToString(ts int) string {
t := time.Unix(int64(ts), 0)
return t.Format(displayTime)
}
func lookup(name string) {
user, err := api.LookupUser(name)
if err != nil {
fmt.Printf("Lookup failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Details for user %s:\n", user.Basics.Username)
fmt.Printf("\tCreated: %s\n", unixToString(user.Basics.Created))
fmt.Printf("\tLast modified: %s\n", unixToString(user.Basics.Modified))
fmt.Printf("\tProfile:\n")
fmt.Printf("\t\tLast updated: %s\n", unixToString(user.Profile.Modified))
fmt.Printf("\t\tFull name: %s\n", user.Profile.FullName)
fmt.Printf("\t\tLocation: %s\n", user.Profile.Location)
fmt.Printf("\t\tBio:\n")
fmt.Printf("\t\t\t%s\n", user.Profile.Bio) // TODO(kyle): wordwrap bio
if pub, ok := user.PublicKeys["primary"]; ok {
fmt.Printf("\tPublic key\n")
fmt.Printf("\t\tKey ID: %s\n", pub.KeyID)
fmt.Printf("\t\tCreated: %s\n", unixToString(pub.Created))
fmt.Printf("\t\tLast modified: %s\n", unixToString(pub.Modified))
} else {
fmt.Printf("\tNo public key.\n")
}
}
func fetchKey(name, outFile string) {
user, err := api.LookupUser(name)
if err != nil {
fmt.Printf("Fetch failed: %v\n", err)
os.Exit(1)
}
pub, ok := user.PublicKeys["primary"]
if !ok || pub.Bundle == "" {
fmt.Printf("%s hasn't uploaded a public key yet.\n", name)
os.Exit(1)
}
if outFile != "-" {
err = ioutil.WriteFile(outFile, []byte(pub.Bundle+"\n"), 0644)
if err != nil {
fmt.Printf("Couldn't write %s's public key to disk: %v\n", user.Basics.Username, err)
} else {
fmt.Printf("Wrote %s's public key to %s.\n'", user.Basics.Username, outFile)
}
} else {
fmt.Fprintf(os.Stdout, "%s\n", pub.Bundle)
}
}
func deleteKey(session *api.Session) {
pub, ok := session.User.PublicKeys["primary"]
if !ok {
fmt.Println("There is no public key to delete.")
os.Exit(1)
}
err := session.DeleteKey(pub.KeyID)
if err != nil {
fmt.Printf("Failed to delete your public key: %v\n", err)
os.Exit(1)
}
fmt.Println("Your public key has been deleted from your account.")
}
func postAuth(session *api.Session, keyRing *openpgp.KeyRing) {
pub := session.User.PublicKeys["primary"]
if pub == nil {
fmt.Println("No public key for this account.")
os.Exit(1)
}
fmt.Printf("Fingerprint: %s\n", pub.Fingerprint)
signer := keyRing.Entity(pub.Fingerprint)
if signer == nil {
fmt.Println("No private key for this account.")
os.Exit(1)
}
/*
var signature = `-----BEGIN PGP MESSAGE-----
Version: Keybase Go client (OpenPGP version 0.1.0)
xA0DAAIB7k+6hRB9rTcBrQFRYgBTPJCXeyJib2R5Ijp7ImtleSI6eyJmaW5nZXJw
cmludCI6IjNiMGM0ZGU3ZDE2NThkMWE1ZmFlYzEyMGVlNGZiYTg1MTA3ZGFkMzci
LCJob3N0Ijoia2V5YmFzZS5pbyIsImtleV9pZCI6IjAxMDEwYjA0YTFmNzk2M2Nm
YjUxNjQ0ZWUyM2E0YTA2NmY1MzkxN2FmNzE1N2E5Njg5MWViYjAzNTExZTU1Yjk2
MmUzMGEiLCJ1aWQiOiI5NGVmMWUzNTc4OWM2ZmE2NThiNzhlMWIwNWVlZGUwMCIs
InVzZXJuYW1lIjoia2lzb20ifSwic3RyaW5nIjoiIiwidHlwZSI6ImF1dGgiLCJ2
ZXJzaW9uIjoxfSwiY3RpbWUiOjEzOTY0NzgwOTQsImV4cGlyZXNfaW4iOjg2NDAw
LCJ0YWciOiJzaWduYXR1cmUifcLBXAQAAQIAEAUCUzyQlwkQ7k+6hRB9rTcAANSz
EAAseFDy8srABjWmQqp4uhaOPGUDzO9E2wYWm6GcFf60KeenMkYUCssHoP12a4eB
ZLgt2ERkIFAQmn+hQkkfBSK7tQjh6XQmXstHwkhUp2XG2/Kn3Lek7t2sgaqzdt46
/qVmgymBbSgraW0JYzDC+Bta8RRfYhkYyNTjtWnx9Ue2r2R6UcTDGyTS4cWMgAVY
h1ZgQwNLfHMDqjEP93gPj9n8JZb5EN0MXGCe3Z6wMfXIams2QQ4TdsMGvwJffKel
GGOaqUYoTlE01zSF9RA53xTzqwC7PpVcOO6V7FMpRM6UQE6x1MQzy/Iz8gBZONpb
G24IkbpFj+SQYdUJ3fedTUiTWT32n/9sgp3NKY4lFdYKEDhv6fMgSLFkMhbvf6YC
d0Jd1OORtzke3MxJPDHRLlnCNdNA3ZfwD1Dx2Mu8j7JknWBdUsZK2KtDh3hijfmY
TGT1TL6fBT9DAzGfJj305rTNaYR2GnD8ncmqMCD5O+ePVFaQxyrC9zgy50UEOTNS
BLVqFj1mCE38ziBxO39Y1Kx4U0ZUmQ90Fz7nzhw3alnPQaPF6M8f+q2Mx+xuZhHF
hYddlV4afpsHp14sAeLaImLZ+IPvL+KH0f3Pc0N9rSaCJhsR5yLLpoPXk3RXrs+1
kXBuzD8AyhGVVJ+VCOuauUwRQT+Ergl7auG94uQi7SN15w==
=gRI/
-----END PGP MESSAGE-----`
*/
sigData, err := session.SignaturePostAuthData()
if err != nil {
fmt.Printf("Failed to get signature post auth data: %v\n", err)
os.Exit(1)
}
signature, err := keyRing.Sign(sigData, pub.Fingerprint)
if err != nil {
fmt.Printf("Signing failed: %v\n", err)
os.Exit(1)
}
authToken, err := session.SignaturePostAuth([]byte(signature))
if err != nil {
fmt.Printf("Posting signature authentication failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Authentication token: %x\n", authToken)
}
func validCommands() {
fmt.Println("Valid commands:")
fmt.Printf("\tlookup <users...>\n")
fmt.Printf("\tfetch <user>\n")
fmt.Printf("\ttestlogin\n")
fmt.Printf("\tupload\n")
fmt.Printf("\tdelete\n")
}
func main() {
flUser := flag.String("u", "", "keybase.io username or email")
flKeyFile := flag.String("pub", "", "public key file")
flOutFile := flag.String("out", "", "output file")
flGPGDir := flag.String("home", "", "override the default GnuPG home directory")
flag.Parse()
if flag.NArg() == 0 {
fmt.Println("No command specified.")
validCommands()
os.Exit(1)
}
if *flGPGDir != "" {
openpgp.SetKeyRingDir(*flGPGDir)
}
cmd := flag.Arg(0)
switch cmd {
case "lookup":
if flag.NArg() < 2 {
fmt.Println("You didn't specify a user to lookup.'")
os.Exit(1)
}
for _, name := range flag.Args()[1:] {
lookup(name)
}
case "fetch":
if flag.NArg() < 2 {
fmt.Println("You didn't specify the user whose key you want to fetch.'")
os.Exit(1)
} else if flag.NArg() > 2 {
fmt.Println("Only one user's key may be fetched at a time.'")
os.Exit(1)
}
name := flag.Arg(1)
outFile := *flOutFile
if outFile == "" {
outFile = name + ".pub"
}
fetchKey(name, outFile)
case "testlogin":
session, err := login(*flUser)
if err != nil {
fmt.Printf("Login failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Logged in as %s.\n", session.User.Basics.Username)
fmt.Printf("Session token: %s\n", session.Session)
fmt.Printf("CSRF token: %s\n", session.Token)
case "upload":
var armoured string
var err error
pubRing, err := openpgp.LoadKeyRing(openpgp.PubRingPath)
if err != nil {
fmt.Printf("Couldn't open public keyring: %v\n", err)
os.Exit(1)
}
if *flKeyFile == "" {
if flag.NArg() == 2 {
armoured, err = pubRing.Export(flag.Arg(1))
if err != nil {
fmt.Printf("Key not found.")
os.Exit(1)
}
} else {
fmt.Println("No file specified (with -pub) and no fingerprint specified.")
fmt.Println("Cowardly refusing to proceed.")
os.Exit(1)
}
} else {
pub, err := ioutil.ReadFile(*flKeyFile)
if err != nil {
fmt.Printf("Failed to read the public key: %v\n", err)
os.Exit(1)
}
armoured = string(pub)
}
session, err := login(*flUser)
if err != nil {
fmt.Printf("Login failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Logged in as %s.\n", session.User.Basics.Username)
kid, err := session.AddKey(armoured)
if err != nil {
fmt.Printf("Upload failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Successfully uploaded new key with ID %s.\n", kid)
case "delete":
session, err := login(*flUser)
if err != nil {
fmt.Printf("Login failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Logged in as %s.\n", session.User.Basics.Username)
deleteKey(session)
case "auth":
secRing, err := openpgp.LoadKeyRing(openpgp.SecRingPath)
if err != nil {
fmt.Printf("Failed to load GnuPG secret keyring: %v.\n", err)
os.Exit(1)
}
session, err := login(*flUser)
if err != nil {
fmt.Printf("Login failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Logged in as %s.\n", session.User.Basics.Username)
postAuth(session, secRing)
case "genkey":
if *flOutFile == "" {
fmt.Println("Please specify an output file with -out.")
os.Exit(1)
}
newKey(*flOutFile)
case "nextseq":
session, err := login(*flUser)
if err != nil {
fmt.Printf("Login failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Logged in as %s.\n", session.User.Basics.Username)
nextSeq(session)
case "authtwit":
secRing, err := openpgp.LoadKeyRing(openpgp.SecRingPath)
if err != nil {
fmt.Printf("Failed to load GnuPG secret keyring: %v.\n", err)
os.Exit(1)
}
session, err := login(*flUser)
if err != nil {
fmt.Printf("Login failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Logged in as %s.\n", session.User.Basics.Username)
authTwitter(session, secRing)
}
}
func readPrompt(prompt string) (in string, err error) {
fmt.Printf("%s", prompt)
rd := bufio.NewReader(os.Stdin)
line, err := rd.ReadString('\n')
if err != nil {
return
}
in = strings.TrimSpace(line)
return
}
func newKey(outFile string) {
name, err := readPrompt("Name: ")
if err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
} else if name == "" {
fmt.Println("Name required!")
os.Exit(1)
}
email, err := readPrompt("Email: ")
if err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
} else if email == "" {
fmt.Println("Email required!")
os.Exit(1)
}
_, err = openpgp.NewEntity(name, email, outFile)
if err != nil {
fmt.Printf("Failed to generate key: %v\n", err)
os.Exit(1)
}
}
func nextSeq(session *api.Session) {
seqNum, prev, err := session.NextSequence()
if err != nil {
fmt.Printf("[!] %v\n", err)
os.Exit(1)
} else {
fmt.Printf("Next sequence: %d\n", seqNum)
fmt.Printf("Previous hash: %s\n", prev)
}
}
func authTwitter(session *api.Session, keyRing *openpgp.KeyRing) {
username, err := readPrompt("Twitter username: ")
if err != nil {
fmt.Printf("Couldn't read from console: %v\n", err)
}
authData, err := session.TwitterGetAuth(username)
if err != nil {
fmt.Printf("Couldn't get authentication data: %v\n", err)
}
pub := session.User.PublicKeys["primary"]
if pub == nil {
fmt.Println("No public key for this account.")
os.Exit(1)
}
fmt.Printf("Fingerprint: %s\n", pub.Fingerprint)
signer := keyRing.Entity(pub.Fingerprint)
if signer == nil {
fmt.Println("No private key for this account.")
os.Exit(1)
}
ioutil.WriteFile("/tmp/authdata.json", authData, 0644)
sig, err := keyRing.Sign(authData, pub.Fingerprint)
if err != nil {
fmt.Printf("Couldn't sign authentication data: %v\n", err)
os.Exit(1)
}
proof, err := session.ServicePostAuth(sig, username, "twitter")
if err != nil {
fmt.Printf("Couldn't authenticate via Twitter: %v\n", err)
os.Exit(1)
}
fmt.Printf("Proof text: '%s'\n", proof.Text)
}