N
N
Nwton2016-12-22 23:26:21
Node.js
Nwton, 2016-12-22 23:26:21

Possible vulnerabilities in this code?

I have never personally encountered information security, but I'm interested in an example in the forehead.
Let's say there is a node js with a server connected by socket io and a mongo base. During the user registration process, the client sends data like this:
socket.emit('register', {login: login});
On the server, I receive it like this:

socket.on('register', function(data){
  if(data.login.replace(/[a-zA-Z0-9]/g, '').length != 0)return;
  new User({login: data.login}).save();
});

Omitted the password, and checking for the presence of the user in the database, it does not matter. The question is: is it possible to inject malicious code through a data line in such a chain? And what security/checks should be added?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2016-12-23
@Nwton

A banal request socket.emit('register');will crash your server with an error, since data will be undefined (null and undefined cannot have properties).
Similarly, for data.login
, only strings have a replace method, calling a non-function will also throw an error.
Correctly something like this:

const LOGIN_REGEX = /[^a-zA-Z0-9]/; //скомпилим регулярку заранее, дабы не компилить при каждом запросе
socket.on('register', function(data){
  if(!data || typeof data.login !== 'string') { return; } //проверка на наличие и правильный тип
  if(data.login.length < 4 || data.login.length > 12) { return; } //проверка на допустимую длину, числа ставьте свои
  if(LOGIN_REGEX.test(data.login)) { return; } // такая проверка в 18 раз быстрее чем у Вас
  new User({login: data.login}).save();
});

D
Dark Hole, 2016-12-22
@abyrkov

По-моему, можно получить ошибку(отправив число, к примеру), хотя сомневаюсь.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question