-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclient.go
355 lines (339 loc) · 9.43 KB
/
client.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
// vim: tabstop=2 shiftwidth=2
package main
import (
"errors"
"fmt"
"io/ioutil"
"math"
"net/mail"
"os"
"strings"
"time"
"github.com/Masterminds/log-go"
"github.com/crooks/yamn/crandom"
"github.com/crooks/yamn/keymgr"
//"github.com/codahale/blake2"
)
// readMessage tries to read a file containing the plaintext to be sent
func readMessage(filename string) []byte {
var err error
f, err := os.Open(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "%s: Unable to open file\n", filename)
os.Exit(1)
}
msg, err := mail.ReadMessage(f)
if err != nil {
fmt.Fprintf(os.Stderr, "%s: Malformed mail message\n", filename)
os.Exit(1)
}
if flag.To != "" {
msg.Header["To"] = []string{flag.To}
if !strings.Contains(flag.To, "@") {
fmt.Fprintf(
os.Stderr,
"%s: Recipient doesn't appear to be an "+
"email address\n",
flag.To,
)
}
}
if flag.Subject != "" {
msg.Header["Subject"] = []string{flag.Subject}
}
return assemble(*msg)
}
// mixprep fetches the plaintext and prepares it for mix encoding
func mixprep() {
var err error
err = os.MkdirAll(cfg.Files.Pooldir, 0700)
if err != nil {
panic(err)
}
// plain will contain the byte version of the plain text message
var plain []byte
// final is consistent across multiple copies so we define it early
final := newSlotFinal()
if len(flag.Args) == 0 {
//fmt.Println("Enter message, complete with headers. Ctrl-D to finish")
plain, err = ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
} else if len(flag.Args) == 1 {
// A single arg should be the filename
plain = readMessage(flag.Args[0])
} else if len(flag.Args) >= 2 {
// Two args should be recipient and filename
flag.To = flag.Args[0]
plain = readMessage(flag.Args[1])
}
// plainLen is the length of the plain byte message and can exceed
// the total body size of the payload.
plainLen := len(plain)
if plainLen == 0 {
fmt.Fprintln(os.Stderr, "No bytes in message")
os.Exit(1)
}
// Download stats URLs if the time is right
if cfg.Urls.Fetch {
// Retrieve Mlist2 and Pubring URLs
timedURLFetch(cfg.Urls.Pubring, cfg.Files.Pubring)
timedURLFetch(cfg.Urls.Mlist2, cfg.Files.Mlist2)
}
// Create the Public Keyring
Pubring = keymgr.NewPubring(
cfg.Files.Pubring,
cfg.Files.Mlist2,
)
// Set the Use Expired flag to include remailers with expired keys as
// candidates.
if cfg.Stats.UseExpired {
Pubring.UseExpired()
}
err = Pubring.ImportPubring()
if err != nil {
log.Warnf("Pubring import failed: %s", cfg.Files.Pubring)
return
}
// Read the chain from flag or config
var inChain []string
var inChainFunc []string
if flag.Chain == "" {
inChain = strings.Split(cfg.Stats.Chain, ",")
} else {
inChain = strings.Split(flag.Chain, ",")
}
if len(inChain) == 0 {
err = errors.New("empty input chain")
return
}
var cnum int // Chunk number
var numc int // Number of chunks
numc = int(math.Ceil(float64(plainLen) / float64(maxFragLength)))
final.setNumChunks(numc)
var exitnode string // Address of exit node (for multiple copy chains)
var gotExit bool // Flag to indicate an exit node has been selected
var firstByte int // First byte of message slice
var lastByte int // Last byte of message slice
// Fragments loop begins here
for cnum = 1; cnum <= numc; cnum++ {
final.setChunkNum(cnum)
// First byte of message fragment
firstByte = (cnum - 1) * maxFragLength
lastByte = firstByte + maxFragLength
// Don't slice beyond the end of the message
if lastByte > plainLen {
lastByte = plainLen
}
gotExit = false
// If no copies flag is specified, use the config file NUMCOPIES
if flag.Copies == 0 {
flag.Copies = cfg.Stats.Numcopies
}
if flag.Copies > maxCopies {
// Limit copies to a maximum of 10
flag.Copies = maxCopies
}
// Copies loop begins here
for n := 0; n < flag.Copies; n++ {
if gotExit {
// Set the last node in the chain to the
// previously select exitnode
inChain[len(inChain)-1] = exitnode
}
var chain []string
inChainFunc = append(inChain[:0:0], inChain...)
chain, err = makeChain(inChainFunc)
if err != nil {
log.Error(err)
os.Exit(0)
}
if len(chain) != len(inChain) {
err = fmt.Errorf("chain length mismatch: in=%d, out=%d", len(inChain), len(chain))
panic(err)
}
//fmt.Println(chain)
if !gotExit {
exitnode = chain[len(chain)-1]
gotExit = true
}
// Retain the entry hop. We need to mail the message to it.
sendTo := chain[0]
// Report the chain if we're running as a client.
if flag.Client {
log.Infof("Chain: %s\n", strings.Join(chain, ","))
}
yamnMsg := encodeMsg(
plain[firstByte:lastByte],
chain,
*final,
)
writeMessageToPool(sendTo, yamnMsg)
} // End of copies loop
} // End of fragments loop
// Decide if we want to inject a dummy
if !flag.NoDummy && Pubring.HaveStats() && crandom.Dice() < 80 {
dummy()
}
}
// encodeMsg encodes a plaintext fragment into mixmaster format.
func encodeMsg(
plain []byte,
chain []string,
final slotFinal) []byte {
var err error
var hop string
m := newEncMessage()
m.setChainLength(len(chain))
length := m.setPlainText(plain)
// Pop the exit remailer address from the chain
hop = popstr(&chain)
// Insert the plain message length into the Final Hop header.
final.setBodyBytes(length)
slotData := newSlotData()
// Identify this hop as Packet-Type 1 (Exit).
slotData.setExit()
// For exit hops, the AES key can be entirely random.
slotData.setAesKey(crandom.Randbytes(32))
// Override the random PacketID so that multi-copy messages all share a
// common Exit PacketID.
slotData.setPacketID(final.getPacketID())
// Encode the (final) Packet Info and store it in the Slot Data.
slotData.setPacketInfo(final.encode())
// Get KeyID and NaCl PK for the remailer we're enrypting to.
remailer, err := Pubring.Get(hop)
if err != nil {
log.Errorf(
"%s: Remailer unknown in public keyring\n",
hop,
)
os.Exit(1)
}
// Create a new Header.
header := newEncodeHeader()
// Tell the header function what KeyID and PK to NaCl encrypt with.
header.setRecipient(remailer.Keyid, remailer.PK)
log.Tracef(
"Encrypting Final Hop: Hop=%s, KeyID=%x",
hop,
remailer.Keyid,
)
// Only the body needs to be encrypted during Exit encoding. At all other
// hops, the entire header stack will also need encrypting.
m.encryptBody(slotData.aesKey, final.aesIV)
// Shift all the header down by headerBytes
m.shiftHeaders()
// We've already popped an entry from the Chain so were testing for
// length greater than zero rather than 1.
if len(chain) > 0 {
// Single hop chains don't require deterministic headers. All
// longer chains do.
m.deterministic(0)
}
// Set the Anti-tag hash in the slotData.
slotData.setTagHash(m.getAntiTag())
// Encode the slot data into Byte form.
slotDataBytes := slotData.encode()
// Encode the header and insert it into the payload.
m.insertHeader(header.encode(slotDataBytes))
// That concludes Exit hop compilation. Now for intermediates.
interHops := m.getIntermediateHops()
for interHop := 0; interHop < interHops; interHop++ {
inter := newSlotIntermediate()
inter.setPartialIV(m.getPartialIV(interHop))
// hop still contains the previous iteration (or exit) address.
inter.setNextHop(hop)
// Pop another remailer from the left side of the Chain
hop = popstr(&chain)
// Create new Slot Data
slotData = newSlotData()
slotData.setAesKey(m.getKey(interHop))
slotData.setPacketInfo(inter.encode())
m.encryptAll(interHop)
m.shiftHeaders()
m.deterministic(interHop + 1)
slotData.setTagHash(m.getAntiTag())
slotDataBytes = slotData.encode()
header = newEncodeHeader()
remailer, err := Pubring.Get(hop)
if err != nil {
log.Errorf(
"%s: Remailer unknown in public keyring\n",
hop,
)
os.Exit(1)
}
header.setRecipient(remailer.Keyid, remailer.PK)
log.Tracef(
"Encrypting: Hop=%s, KeyID=%x",
hop,
remailer.Keyid,
)
m.insertHeader(header.encode(slotDataBytes))
}
if len(chain) != 0 {
panic("After encoding, chain was not empty.")
}
return m.getPayload()
}
func injectDummy() {
// Populate public keyring
Pubring = keymgr.NewPubring(
cfg.Files.Pubring,
cfg.Files.Mlist2,
)
Pubring.ImportPubring()
dummy()
}
// TimedURLFetch attempts to read a url into a file if the file is more
// than an hour old or doesn't exist.
func timedURLFetch(url, filename string) {
var err error
var stamp time.Time
var doFetch bool
if cfg.Urls.Fetch {
stamp, err = fileTime(filename)
if err != nil {
doFetch = true
} else if time.Since(stamp) > time.Hour {
doFetch = true
} else {
doFetch = false
}
if doFetch {
log.Infof("Fetching %s and storing in %s", url, filename)
err = httpGet(url, filename)
if err != nil {
log.Warn(err)
}
}
}
}
// dummy is a simplified client function that sends dummy messages
func dummy() {
var err error
plainMsg := []byte("I hope Len approves")
// Make a single hop chain with a random node
var inChain []string
if flag.Chain == "" {
inChain = []string{"*", "*"}
} else {
inChain = strings.Split(flag.Chain, ",")
}
final := newSlotFinal()
// Override the default delivery method (255 = Dummy)
final.setDeliveryMethod(255)
var chain []string
chain, err = makeChain(inChain)
sendTo := chain[0]
if err != nil {
log.Warnf("Dummy creation failed: %s", err)
return
}
log.Tracef("Sending dummy through: %s.", strings.Join(chain, ","))
yamnMsg := encodeMsg(plainMsg, chain, *final)
writeMessageToPool(sendTo, yamnMsg)
return
}