7 - Discovery and validation with hashes.

We now have the tools we need to fix our security issues from exercise 4.

As we know, hashes can be used to summarize the contents of a file. This means we can use them as an id for our service discovery strategy.

Build on the solution to exercise 4, but use file hashes as a way to identify channels for service discovery. Also, when the file is downloaded in the client, verify that the hash of the downloaded file matches the expected hash.

We expect the person sharing the file via the server, to send the hash (id) to the client by other means, e.g. over IM.

Solution from exercise 4

Server:

var fs = require('fs')
var net = require('net')
var pump = require('pump')
var DC = require('discovery-channel')

var channel = DC({dht: false}) // set true to work over the internet

var server = net.createServer(function (socket) {
  console.log('New peer connected: %s:%s', socket.remoteAddress, socket.remotePort)
  var file = fs.createReadStream(__filename)
  pump(file, socket)
})

server.listen(function () {
  var id = process.argv[2]
  var port = server.address().port
  channel.join(id, port)

  console.log('Server named %s is listening on port %d', id, port)
})

Client:

var fs = require('fs')
var net = require('net')
var pump = require('pump')
var DC = require('discovery-channel')

var channel = DC({dht: false}) // set true to work over the internet
var id = process.argv[2]

channel.join(id)

channel.once('peer', function (peerId, peer, type) {
  console.log('New peer %s:%s found via %s:', peer.host, peer.port, type)

  var socket = net.connect(peer.port, peer.host)
  var filename = 'file-' + Date.now() + '.js'
  var file = fs.createWriteStream(filename)

  console.log('Fetching %s...', filename)
  pump(socket, file, function (err) {
    if (err) throw err
    console.log('File successfully written to disk')
    channel.destroy()
  })
})

Assignment

Update the server/client from exercise 4 with the following:

Server:

Client:

Testing

Share a file using the server and download it using the client.

For fun, when the server/client works as expected, try to tamper with the hash so the validation fails.

When you are done click here to go to the next exercise