Warm tip: This article is reproduced from serverfault.com, please click

NodeJS Net server crashes upon nmap scan

发布于 2021-05-06 21:00:53

I have programmed a server based on the Net module of NodeJS. It works perfectly fine, if I try to connect to it using a Net socket. However, if I try to scan it with nmap, it can't write to the socket, giving an EPIPE error.

    Error: write EPIPE
    at afterWriteDispatched (node:internal/stream_base_commons:160:15)
    at writeGeneric (node:internal/stream_base_commons:151:3)
    at Socket._writeGeneric (node:net:775:11)
    at Socket._write (node:net:787:8)
    at writeOrBuffer (node:internal/streams/writable:400:12)
    at _write (node:internal/streams/writable:341:10)
    at Socket.Writable.write (node:internal/streams/writable:345:10)
    at Server.<anonymous> (/server.js:6:10)
    at Server.emit (node:events:379:20)
    at TCP.onconnection (node:net:1555:8)
Emitted 'error' event on Socket instance at:
    at emitErrorNT (node:internal/streams/destroy:188:8)
    at emitErrorCloseNT (node:internal/streams/destroy:153:3)
    at processTicksAndRejections (node:internal/process/task_queues:81:21) {
  errno: -32,
  code: 'EPIPE',
  syscall: 'write'
}

I have simplified the server code to this:

const net = require('net');
const server = net.createServer(socket => {
  socket.write('Test');
});
server.listen(30);

The nmap output just sais 30/tcp open tcpwrapped. I'm sure it has something to do with how nmap connects to the server. But I just can't work out how.

Questioner
Nils Schwebel
Viewed
0
30 2021-05-07 06:13:34

The reason you're getting this error is that nmap closes the connection immediately. By the time your callback starts executing, Node.js has already got the RST packet and it knows the connection is closed, so it disallows writes to it by throwing an error right away - a socket is a state machine that makes sure of this.

As a rule, you should be ready to handle connection state errors at all times - potentially, any write call can fail. This is different than losing packets because, in this scenario, they never reach the network.