-
Notifications
You must be signed in to change notification settings - Fork 1
/
collider.go
438 lines (395 loc) · 10.2 KB
/
collider.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
package main
import (
"bufio"
"bytes"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"runtime"
"strconv"
"time"
"nullprogram.com/x/optparse"
"nullprogram.com/x/passphrase2pgp/openpgp"
)
const (
// mask selects the bits to be collided.
mask = (1 << 64) - 1
// distingish is a mask that determintes the average hash chain length.
// A chain ends when these bits are all zero. This sets the trade-off
// between computation time and memory use.
distinguish = (1 << 17) - 1
cmdDefault = iota
cmdClient
cmdServer
)
// Print the message like fmt.Printf() and then os.Exit(1).
func fatal(format string, args ...interface{}) {
buf := bytes.NewBufferString("pgpcollider: ")
fmt.Fprintf(buf, format, args...)
buf.WriteRune('\n')
os.Stderr.Write(buf.Bytes())
os.Exit(1)
}
// expand fills a 32-byte key seed from a 64-bit PRNG seed.
func expand(kseed []byte, seed uint64) {
for i := 0; i < 4; i++ {
seed += 0x9e3779b97f4a7c15
z := seed
z ^= z >> 30
z *= 0xbf58476d1ce4e5b9
z ^= z >> 27
z *= 0x94d049bb133111eb
z ^= z >> 31
binary.LittleEndian.PutUint64(kseed[i*8:], z)
}
}
// link represents a individual link in a hash chain: a seed and its
// resulting truncated key ID.
type link struct {
seed uint64
truncID uint64
}
// Returns the final truncated key ID of a hash chain starting at the
// given seed, as well as the length of the chain. If not nil, the chain
// itself is recorded into the link slice for inspection.
func computeChain(seed uint64, created int64, record *[]link) (uint64, int) {
var kseed [32]byte
var key openpgp.SignKey
key.SetCreated(created)
for count := 1; ; count++ {
expand(kseed[:], seed)
key.Seed(kseed[:])
keyID := key.KeyID()
truncID := binary.BigEndian.Uint64(keyID[12:]) & mask
if record != nil {
*record = append(*record, link{seed, truncID})
}
seed = truncID
if truncID&distinguish == 0 {
return truncID, count
}
}
}
// chain represents a complete hash chain: the starting seed, the final
// truncated key ID, and the chain's length.
type chain struct {
seed uint64
truncID uint64
length int
}
// Continuously fills the channel with new seeds.
func seeder(seeds chan<- uint64) {
seed := uint64(time.Now().UnixNano())
seed ^= seed >> 32
seed *= 0xd6e8feb86659fd93
seed ^= seed >> 32
seed *= 0xd6e8feb86659fd93
seed ^= seed >> 32
for {
seeds <- seed
seed++
}
}
// Processes each chain from the channel looking for collisions.
func consumer(chains <-chan chain, config *config) {
var total int64
seen := make(map[uint64]uint64)
mean := newMovingAverage(64)
start := time.Now()
for chain := range chains {
total += int64(chain.length)
rate := mean.add(float64(total))
log.Printf("chains %d, keys %d, keys/sec %.0f\n",
len(seen)+1, total, rate)
if seed, ok := seen[chain.truncID]; ok {
// Recreate chains, but record all the links this time.
var recordA, recordB []link
computeChain(seed, config.created, &recordA)
computeChain(chain.seed, config.created, &recordB)
mapB := make(map[uint64]uint64)
for _, link := range recordB {
mapB[link.truncID] = link.seed
}
for _, link := range recordA {
seedB, ok := mapB[link.truncID]
if !ok {
continue
}
seedA := link.seed
duration := time.Now().Sub(start)
log.Printf("duration %s\n", duration)
var buf bytes.Buffer
userid := openpgp.UserID{ID: []byte(config.uid)}
var kseed [32]byte
// Recreate and self-sign first key
var keyA openpgp.SignKey
expand(kseed[:], seedA)
keyA.Seed(kseed[:])
keyA.SetCreated(config.created)
if config.public {
buf.Write(keyA.PubPacket())
} else {
buf.Write(keyA.Packet())
}
buf.Write(userid.Packet())
buf.Write(keyA.SelfSign(&userid, config.created, 0))
armor := openpgp.Armor(buf.Bytes())
if _, err := os.Stdout.Write(armor); err != nil {
fatal("%s", err)
}
buf.Truncate(0)
// Recreate and self-sign second key
var keyB openpgp.SignKey
expand(kseed[:], seedB)
keyB.Seed(kseed[:])
keyB.SetCreated(config.created)
if config.public {
buf.Write(keyB.PubPacket())
} else {
buf.Write(keyB.Packet())
}
buf.Write(userid.Packet())
buf.Write(keyB.SelfSign(&userid, config.created, 0))
armor = openpgp.Armor(buf.Bytes())
if _, err := os.Stdout.Write(armor); err != nil {
fatal("%s", err)
}
log.Printf("key ID %X\n", keyA.KeyID())
log.Printf("key ID %X\n", keyB.KeyID())
os.Exit(0)
}
} else {
seen[chain.truncID] = chain.seed
}
}
}
// Start a bunch of local chain builders.
func startWorkers(seeds <-chan uint64, chains chan<- chain, created int64) {
for i := 0; i < runtime.GOMAXPROCS(0); i++ {
go func() {
for seed := range seeds {
truncID, length := computeChain(seed, created, nil)
chains <- chain{seed, truncID, length}
}
}()
}
}
// Continuously fill a channel with seeds from a connection.
func netSeeder(seeds chan<- uint64, conn net.Conn) {
var buf [8]byte
r := bufio.NewReader(conn)
for {
if _, err := r.Read(buf[:]); err != nil {
fatal("%s", err)
}
seed := binary.BigEndian.Uint64(buf[:])
log.Printf("%#016x", seed)
seeds <- seed
}
}
// Take chains from the channel and send them over the network.
func netConsumer(chains <-chan chain, conn net.Conn) {
var buf [20]byte
for chain := range chains {
binary.BigEndian.PutUint64(buf[0:], chain.seed)
binary.BigEndian.PutUint64(buf[8:], chain.truncID)
binary.BigEndian.PutUint32(buf[16:], uint32(chain.length))
if _, err := conn.Write(buf[:]); err != nil {
fatal("%s", err)
}
}
}
// Send seeds to remote workers and receive their chains.
func netWorker(seeds <-chan uint64, chains chan<- chain, conn net.Conn) {
go func() {
var buf [8]byte
w := bufio.NewWriter(conn)
for seed := range seeds {
binary.BigEndian.PutUint64(buf[:], seed)
if _, err := w.Write(buf[:]); err != nil {
log.Println(err)
return
}
}
}()
var buf [20]byte
for {
if _, err := io.ReadFull(conn, buf[:]); err != nil {
log.Println(err)
return
}
seed := binary.BigEndian.Uint64(buf[0:])
truncID := binary.BigEndian.Uint64(buf[8:])
length := int(binary.BigEndian.Uint32(buf[16:]))
chains <- chain{seed, truncID, length}
}
}
// Listen for new workers and connect them to the channels.
func workerListen(seeds <-chan uint64, chains chan<- chain,
addr string, created int64) {
ln, err := net.Listen("tcp", addr)
if err != nil {
fatal("%s", err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
log.Println("client connected", conn.RemoteAddr())
var buf [4]byte
binary.BigEndian.PutUint32(buf[:], uint32(created))
if _, err := conn.Write(buf[:]); err != nil {
log.Println(err)
continue
}
go netWorker(seeds, chains, conn)
}
}
type config struct {
cmd int
addr string
help bool
public bool
created int64
uid string
verbose bool
}
func parse() *config {
config := config{
cmd: cmdDefault,
created: time.Now().Unix(),
}
options := []optparse.Option{
{"client", 'C', optparse.KindRequired},
{"server", 'S', optparse.KindRequired},
{"help", 'h', optparse.KindNone},
{"public", 'p', optparse.KindNone},
{"time", 't', optparse.KindRequired},
{"uid", 'u', optparse.KindRequired},
{"verbose", 'v', optparse.KindNone},
}
results, rest, err := optparse.Parse(options, os.Args)
if err != nil {
fatal("%s", err)
}
for _, result := range results {
switch result.Long {
case "client":
config.cmd = cmdClient
config.addr = result.Optarg
case "server":
config.cmd = cmdServer
config.addr = result.Optarg
case "help":
usage(os.Stdout)
os.Exit(0)
case "public":
config.public = true
case "time":
time, err := strconv.ParseUint(result.Optarg, 10, 32)
if err != nil {
fatal("--time (-t): %s", err)
}
config.created = int64(time)
case "uid":
config.uid = result.Optarg
case "verbose":
config.verbose = true
}
}
if len(rest) > 0 {
fatal("too many arguments")
}
return &config
}
func usage(w io.Writer) {
bw := bufio.NewWriter(w)
p := "pgpcollider"
i := " "
f := func(s ...interface{}) {
fmt.Fprintln(bw, s...)
}
f("Usage:")
f(i, p, "[-pv] [-t CREATED] [-u USERID]")
f(i, p, "-C HOSTNAME [-v]")
f(i, p, "-S BINDADDR [-pv] [-t CREATED] [-u USERID]")
f("Commands (distributed computation):")
f(i, "-C, --server BINDADDR generate hash chains for a server")
f(i, "-S, --client HOSTNAME listen for worker clients")
f("Options:")
f(i, "-h, --help print this help message")
f(i, "-p, --public only output the public key")
f(i, "-t, --time SECONDS key creation date (unix epoch seconds)")
f(i, "-u, --uid USERID user ID for the keys")
f(i, "-v, --verbose print progress information")
bw.Flush()
}
func main() {
chains := make(chan chain)
seeds := make(chan uint64)
config := parse()
if !config.verbose {
log.SetOutput(ioutil.Discard)
}
switch config.cmd {
case cmdDefault:
// Feed unique seeds one at a time to the workers.
go seeder(seeds)
// Spin off workers to create chains.
startWorkers(seeds, chains, config.created)
consumer(chains, config)
case cmdClient:
conn, err := net.Dial("tcp", config.addr)
if err != nil {
fatal("%s", err)
}
// Get created date
var buf [4]byte
if _, err := io.ReadFull(conn, buf[:]); err != nil {
fatal("%s", err)
}
created := int64(binary.BigEndian.Uint32(buf[:]))
// Set up pipeline
go netSeeder(seeds, conn)
startWorkers(seeds, chains, created)
netConsumer(chains, conn)
case cmdServer:
// Set up pipeline
go seeder(seeds)
go workerListen(seeds, chains, config.addr, config.created)
consumer(chains, config)
}
}
type sample struct {
what float64
when time.Time
}
type movingAverage struct {
queue []sample
head, tail int
}
func newMovingAverage(n int) *movingAverage {
return &movingAverage{queue: make([]sample, n)}
}
func (m *movingAverage) add(value float64) float64 {
head := &m.queue[m.head]
m.head = (m.head + 1) % len(m.queue)
if m.head == m.tail {
m.tail = (m.tail + 1) % len(m.queue)
}
tail := &m.queue[m.tail]
head.what = value
head.when = time.Now()
num := head.what - tail.what
den := head.when.Sub(tail.when).Seconds()
if den == 0.0 {
return 0.0
}
return num / den
}