public
Last active

The HearSay P2P File Sharer

  • Download Gist
HearSay.md
Markdown

HearSay

The HearSay P2P File Sharer; a response to The Copyright Alert System, as well as several other internet regulation attempts. The goal of this project is to prove the viability of semi-anonymous and confidential file sharing. Consists of several proofs of concepts such as the formation of ad-hoc mix networks and routing throughout them while maintaining anonymity and semantic security.

However, lets be honest with ourselves for a second. Don't use this to fight an oppressive regime. I can not (and will not try) to 'prove' its security, and I have no idea how this system will perform under high stress or in large clusters. All of this code is simply the product of basic cryptographic research and application.

Beware of bugs in the [below] code; I have only proved it correct, not tried it. ~ Donald Knuth

Setup

  • Dependencies: Node.js, npm
  • Installation: npm install (May require sudo.)
  • Start: coffee hearsay (Never run with sudo.)

Usage

  1. chunks - Lists the hashes of all the chunks you are currently hosting. These consist of the chunks you've uploaded as well as the chunks that you're co-hosting.
  2. peers - Lists all of the peers on a network that you're currently connected to.
  3. enter {host} {port} - Attempts to enter a cluster through the given node. This requires that your server be publicly available as well. (Through the use of port forwarding, or a DMZ.)
  4. upload - Will then prompt you for an input file (the file to be uploaded) and an output file (where the torrent data will be written), and upload the input file to the cluster.
  5. download - Will then prompt you for an input file (the file with the torrent data) and an output file (where the file contents will be written), and attempt to download the file.

To Do

  1. Allow a public organization to sponsor uploads to a network without being legally responsible for them.
  2. Re-uploads
  3. Limiting number of failed requests before giving up.
  4. Requesting a specific port for the server to listen on.
  5. Cleaning, perhaps?
hearsay.coffee
CoffeeScript
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
fs = require 'fs'
net = require 'net'
path = require 'path'
async = require 'async'
crypto = require 'crypto'
readline = require 'readline'
msgpack = require 'msgpack'
secure = require './secure'
{BigInteger} = require 'bigdecimal'
 
# Network state
# Server information
[peers, pendingHookups, pendingDownloads, chunks] = [{}, {}, {}, {}]
[peersLength, chunksLength, serverPort] = [0, 0, 0]
routingKey = secure.randomHex()
 
console.log 'Hearsay File Sharer v0.0.1'
console.log 'Starting up...'
 
# Start the server. Handles inter-cluster requests. (Insecure)
server = net.createServer (conn) ->
conn.once 'data', (data) =>
data = data.toString().split ' '
switch data[0]
when 'hookup'
address = conn.remoteAddress + ':' + data[1]
conn.end()
# 1. Check that given port is valid.
# 2. Decide if we want this connection for ourselves.
# 3. Make sure we don't know this peer.
# 4. Make sure this isn't one of ours.
port = parseInt data[1]
want = secure.want peersLength
know = peers[address]?
ours = pendingHookups[data[2]]?
if not isNaN(port) and want and not know and not ours
# Connect and befriend.
conn = net.connect data[1], conn.remoteAddress, ->
conn.write 'mate ' + serverPort + ' ' + data[2]
conn.once 'data', (res) ->
if res.toString() is 'ok' then peer conn, data[1], true
conn.on 'error', ->
else if not isNaN port and not ours
# Pass on.
drain.push cmd: 'hookup', address: address, tracker: data[2]
when 'mate'
# If ours, acknowledge. If not, throw away.
if pendingHookups[data[2]]?
delete pendingHookups[data[2]]
conn.write 'ok'
peer conn, data[1], false
else
conn.end 'no'
# So there's never an 'unhandeled' error.
conn.on 'error', ->
 
server.listen ->
serverPort = server.address().port
console.log 'Server port:', serverPort
frontend()
 
 
# Peers
drainer = (task, done) ->
if peersLength is 0 then return
cb = task.cb
delete task.cb
if (task.cmd is 'req' or task.cmd is 'res') and task.from?
# Hash tracker
c = crypto.createCipher 'aes-256-ctr', routingKey
c.end task.tracker, 'hex'
tracker = c.read().toString 'hex'
# Generate lists of peers to reference.
first = (addr for addr of peers).sort()
second = (addr for addr of peers).sort (a, b) ->
c = crypto.createCipher 'aes-256-ctr', routingKey
c.write tracker, 'hex'
c.end a
a = c.read().toString 'hex'
c = crypto.createCipher 'aes-256-ctr', routingKey
c.write tracker, 'hex'
c.end b
b = c.read().toString 'hex'
a > b
if task.cmd is 'res' then [first, second] = [second, first]
# Choose next.
n = first.indexOf task.from
delete task.from
addr = second[n]
else
# Randomly choose peer.
[n, m] = [secure.random(peersLength), 0]
for addr of peers
if n is m then break else m++
# Encrypt.
peers[addr].writeCipher.write msgpack.pack task
ct = peers[addr].writeCipher.read().toString 'base64'
# MAC.
mac = crypto.createHmac 'sha256', peers[addr].writeMACKey
mac.end ct, 'base64'
tag = mac.read().toString 'base64'
peers[addr].conn.write ct + tag + '\n', 'utf8', (err) ->
if cb? then cb err
done err
 
drain = async.queue drainer, 1
 
peer = (conn, port, init) ->
# Secure the connection.
secure.remote conn, init
address = conn.remoteAddress + ':' + port
conn.on 'secure', (writeCipher, writeMKey) ->
peersLength++
peers[address] =
conn: conn
writeCipher: writeCipher
writeMACKey: writeMKey
conn.on 'end', ->
peersLength--
delete peers[address]
conn.on 'line', (data) ->
if data.cmd is 'hookup' and data.address? and data.tracker?
want = secure.want peersLength
know = peers[data.address]?
ours = pendingHookups[data.tracker]?
[host, port] = data.address.split ':'
if want and not know and not ours
# Connect and befriend.
conn = net.connect port, host, ->
conn.write 'mate ' + serverPort + ' ' + data.tracker
conn.once 'data', (res) ->
if res.toString() is 'ok' then peer conn, port, true
conn.on 'error', ->
else if not ours and not secure.drop()
drain.push data
else if data.cmd is 'distr' and data.tag? and data.chunk?
know = chunks[data.tag]?
if secure.want() and not know
chunks[data.tag] = data: data.chunk, own: false
chunksLength++
if not secure.drop() then drain.push data
else if data.cmd is 'req' and data.tracker? and data.tag?
if chunks[data.tag]?
drain.push {
cmd: 'res',
tracker: data.tracker,
chunk: chunks[data.tag].data
}
else if not secure.drop()
drain.push data
else if data.cmd is 'res' and data.tracker? and data.chunk?
if pendingDownloads[data.tracker]?
pendingDownloads[data.tracker](data.chunk)
else if not secure.drop()
drain.push data
 
# General maintenance.
maintenance = ->
# Clean up old hookups.
d = (new Date()).getTime()
clean = (tracker) ->
if d - pendingHookups[tracker] >= 5000
delete pendingHookups[tracker]
clean tracker for tracker of pendingHookups
# Clean out unwanted chunks.
clean = (tag) ->
if chunks[tag].own is false and secure.drop()
delete chunks[tag]
clean tag for tag of chunks
# Play matchmaker.
if peersLength is 0 or peersLength >= 5 then return
[n, m] = [secure.random(peersLength), 0]
for addr of peers
if n is m then break
m++
[host, port] = addr.split ':'
conn = net.connect port, host, ->
d = new Date()
tracker = secure.randomHex()
pendingHookups[tracker] = d.getTime()
conn.end 'hookup ' + serverPort + ' ' + tracker
conn.on 'error', ->
 
setInterval maintenance, 5000
 
publish = () ->
if peersLength is 0 then return setTimeout publish, 10000
# Publish chunks.
args = ({tag: tag, chunk: chunk} for tag, chunk of chunks)
pub = (item, done) ->
drain.push cmd: 'distr', tag: item.tag, chunk: item.chunk.data, cb: ->
setTimeout done, Math.random() * 50000
async.mapSeries args, pub, -> setTimeout publish, 10000
 
publish()
 
# Command Line Interface
frontend = ->
# Completion service.
completer = (line) ->
[completions, hits] = [[], []]
line = path.normalize line
[p, n] = [path.dirname(line), path.basename(line)]
exists = fs.existsSync p
completions = if exists then fs.readdirSync p else []
hits = completions.filter (c) -> c.indexOf(n) is 0
if hits.length is 1
h = hits[0]
hits[0] = p
hits[0] += if p[p.length - 1] is path.sep then '' else path.sep
hits[0] += h
stats = fs.statSync hits[0]
if stats.isDirectory() then hits[0] += path.sep
rec = if hits.length > 0 then hits else completions
return [rec, line]
# Create interface.
rl = readline.createInterface {
input: process.stdin
output: process.stdout
completer: completer
}
# Parses and handles lines entered by the user.
rl.on 'line', (line) ->
line = line.trim().split ' '
switch line[0]
when "" then console.log ""
when "chunks"
console.log tag for tag of chunks
when "peers"
console.log addr for addr, _ of peers
if peersLength is 0 then console.log 'No peers.'
when "enter"
if line.length isnt 3 then return rl.prompt true
conn = net.connect line[2], line[1], ->
d = new Date()
tracker = secure.randomHex()
pendingHookups[tracker] = d.getTime()
conn.end 'hookup ' + serverPort + ' ' + tracker
end = (error) =>
if error? then console.log error
rl.prompt true
conn.on 'error', end
conn.on 'end', end
when "upload"
if line.length isnt 1 then return rl.prompt true
readChunk = (inFd, outFd, cipher) ->
buff = new Buffer 262144
fs.read inFd, buff, 0, 262144, null, (err, n, buff) ->
if err isnt null or n is 0
return rl.prompt true
# Encrypt chunk.
cipher.write buff.slice(0, n)
chunk = cipher.read()
# Hash encrypted chunk.
h = crypto.createHash 'sha256'
h.end chunk
tag = h.read().toString 'base64'
# Publish
chunks[tag] = data: chunk.toJSON(), ours: true
chunksLength++
tb = new Buffer tag
fs.write outFd, tb, 0, tb.length, null, ->
readChunk inFd, outFd, cipher
# Get files needed, open them, and prepare for uploading.
questions = [
{ask: 'Input file? ', mode: 'r'},
{ask: 'Output file? ', mode: 'w'},
]
openFile = (task, done) ->
rl.question task.ask, (file) ->
fs.open file, task.mode, null, done
async.mapSeries questions, openFile, (err, fds) ->
if err?
console.log err
rl.prompt true
else
key = secure.randomBase64()
kb = new Buffer key
fs.write fds[1], kb, 0, kb.length, null, ->
c = crypto.createCipher 'aes-256-ctr', key
readChunk fds[0], fds[1], c
return
when "download"
if line.length isnt 1 then return rl.prompt true
nextLine = (fd, cb) ->
buff = new Buffer 44
fs.read fd, buff, 0, 44, null, (err, n, buff) ->
if err is null and n is 44
cb buff.toString()
else
cb()
timeout = (tracker) ->
if not pendingDownloads[tracker]? then return
pendingDownloads[tracker]('timeout')
fetchChunk = (inFd, outFd, cipher, tag) ->
if not tag? then return rl.prompt true
# Choose a random tracker, put it as pending, and send a
# request with it.
tracker = secure.randomHex()
pendingDownloads[tracker] = (chunk) ->
if chunk is 'timeout'
# Timed out waiting for this chunk.
# Add limiters here later.
delete pendingDownloads[tracker]
fetchChunk inFd, outFd, cipher, tag
else
chunk = new Buffer chunk
# Hash encrypted chunk to check integrity.
h = crypto.createHash 'sha256'
h.end chunk
candidateTag = h.read().toString 'base64'
if tag isnt candidateTag then return
delete pendingDownloads[tracker]
# Decrypt chunk.
cipher.write chunk
chunk = cipher.read()
# Output, and get next chunk.
fs.write outFd, chunk, 0, chunk.length, null, ->
nextLine inFd, (tag) ->
fetchChunk inFd, outFd, cipher, tag
drain.push cmd: 'req', tracker: tracker, tag: tag
setTimeout timeout, 5000, tracker
# Get files needed, open them, and prepare for downloading.
questions = [
{ask: 'Input file? ', mode: 'r'},
{ask: 'Output file? ', mode: 'w'},
]
openFile = (task, done) ->
rl.question task.ask, (file) ->
fs.open file, task.mode, null, done
async.mapSeries questions, openFile, (err, fds) ->
if err?
console.log err
rl.prompt true
else
nextLine fds[0], (key) ->
c = crypto.createCipher 'aes-256-ctr', key
nextLine fds[0], (tag) ->
fetchChunk fds[0], fds[1], c, tag
return
else console.log 'Command not known.'
rl.prompt true
rl.on 'close', ->
console.log '\nGoodbye'
process.exit 0
rl.prompt true
package.json
JSON
1 2 3 4 5 6 7 8 9 10 11 12
{
"name": "HearSay",
"version": "0.0.1",
"private": true,
"dependencies": {
"coffee-script": "*",
"bigdecimal": "*",
"async": "*",
"msgpack": "*",
"event-stream": "*"
}
}
secure.coffee
CoffeeScript
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
es = require 'event-stream'
crypto = require 'crypto'
msgpack = require 'msgpack'
{BigInteger} = require 'bigdecimal'
salt = 'vpfSIDPgJ5tBt7gZgnGQeG8G6r0q4fDkDWWtZD7zqAsYWw2Ep81vIjqC3gJM'
 
exports.remote = (conn, init) ->
dh = crypto.getDiffieHellman 'modp14'
dh.generateKeys()
conn.write dh.getPublicKey 'hex'
conn.once 'data', (data) ->
# Generate keys.
secret = dh.computeSecret data.toString(), 'hex', 'hex'
key = crypto.pbkdf2Sync secret, salt, 2048, 128
[readCKey, readMKey] = [key.slice(0, 32), key.slice(32, 64)]
[writeCKey, writeMKey] = [key.slice(64, 96), key.slice(96, 128)]
if init
[readCKey, writeCKey] = [writeCKey, readCKey]
[readMKey, writeMKey] = [writeMKey, readMKey]
readCipher = crypto.createDecipher 'aes-256-ctr', readCKey
writeCipher = crypto.createCipher 'aes-256-ctr', writeCKey
# Begin handling input.
handle = (line, cb) ->
# Decrypt and validate.
ct = line.slice 0, line.length - 44
tag = line.slice line.length - 44
readCipher.write ct, 'base64'
pt = msgpack.unpack readCipher.read()
readMAC = crypto.createHmac 'sha256', readMKey
readMAC.end ct, 'base64'
candidateTag = readMAC.read().toString 'base64'
if candidateTag != tag then return conn.end()
# Handle data.
conn.emit 'line', pt
cb null, null
p = es.pipeline conn, es.split(), es.map handle
p.on 'error', ->
conn.emit 'secure', writeCipher, writeMKey
 
# Probabilistically decides if we 'want' something.
exports.want = (n) ->
a = BigInteger('3', 10).pow(n)
b = BigInteger('4', 10).pow(n)
r = crypto.randomBytes(2).toString('hex')
x = BigInteger(r, 16).remainder(b)
if x.compareTo(a) is 1 then false else true
 
# Probablistically decides if we should drop a packet.
exports.drop = ->
x = exports.random 10
if x is 2 then true else false
 
# Choose a random number in the range [0, max)
exports.random = (max) ->
max = BigInteger max.toString(), 10
n = Math.ceil(((Math.log(max) / Math.log(2)) + 1) / 8)
r = crypto.randomBytes(n).toString('hex')
x = BigInteger(r, 16).remainder(max)
(Number) x
 
# Returns a string of random hex.
exports.randomHex = (n = 32) -> crypto.randomBytes(n).toString 'hex'
exports.randomBase64 = (n = 32) -> crypto.randomBytes(n).toString 'base64'

Yes, but will it blend?

I've never been a fan of blended coffee. I guess some like it hot.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.