Skip to content

Instantly share code, notes, and snippets.

@Bren2010
Last active October 7, 2023 03:42
Show Gist options
  • Save Bren2010/5332107 to your computer and use it in GitHub Desktop.
Save Bren2010/5332107 to your computer and use it in GitHub Desktop.
The HearSay P2P File Sharer
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

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?
{
"name": "HearSay",
"version": "0.0.1",
"private": true,
"dependencies": {
"coffee-script": "*",
"bigdecimal": "*",
"async": "*",
"msgpack": "*",
"event-stream": "*"
}
}
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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment