Как предотвратить воспроизведение/атаку "человек посередине" формы в PHP, csrf, xsrf

Я не открыл бы и закрыл бы сеансы по каждому запросу данных к NHibernate. Я пользовался бы библиотеками Unit of Work, что многие другие предлагают или делают еще некоторое чтение. NHForge.org начинает, и я полагаю, что существуют некоторые методы при установке NHibernate для общего веб-приложения.

Один из, "о, ошеломляет, это - прохладные моменты", которые я получил от NHibernate, использовал в своих интересах лениво загружающиеся наборы во время разработки. Это была аккуратная способность опыта не должным быть сделать все те соединения для отображения данных по некоторому связанному объекту.

Путем закрывания сеанса как это, вышеупомянутый сценарий не был бы возможен.

могло бы быть что-то, что продолжает транзакции также.

11
задан lorem monkey 9 August 2012 в 08:57
поделиться

3 ответа

You mentioned CSRF in the title but didn't really cover it in your question.

You can read about it in detail online, but CSRF is basically an attack that lets a legitimate user submit to a site unknowingly. For instance, if SO wasn't protecting against such attacks, I could craft a form that causes your SO profile information to be changed when you click on this bad form of mine, expecting something else to happen ("Win a Million bucks!! Click here!!"). This form would use your browser cookies to auth you with SO and make it appear to SO that you were legitimately submitting updates to your profile.

To protect against this, you really want to do a couple of things:

  • ensure that GETs don't cause updates (for instance, don't post a new status update to a user's profile using query params on a GET)
  • ensure that all POSTs are accompanied by a hidden field that lets you validate that the form was generated by your service and not by someone else, and that it was for the intended user. So this hidden field must be generated by the server each time it sends down the html for the form, and should be unique for that user for that session.

An alternative to that second item is to check that the referrer is always your site or a site you expect the POST from. I don't encourage this for non-HTTPS sites because some browsers/networking hardware strip out referrers, and it's not always reliable that a referrer exists.

5
ответ дан 3 December 2019 в 10:26
поделиться

The method used to generate the token is not highly important. The important thing is that the token gets to be used only once. Keep a list of tokens generated for the user in the user's session. If the user submits a form and the token submitted isn't in the session, you can reject the form.

Protecting against man-in-the-middle is a little difficult. A common technique I've seen is including all of the hidden form fields in the hash function to generate the token, and then regenerating the token based on known hidden fields. However, that would only protect against hidden field manipulation, which may not be the ultimate target of the man in the middle.

When the user successfully submits a form with the token, delete the token from the session, so any replay of that submission will fail. However, all it takes is the user requesting the form again to generate another token. That new token can then be used in subsequent automated attacks. In other words, form tokens are useful against CSRF, but not highly effective against automated replay and man-in-the-middle attacks.

Likewise, you're going to want to adapt your application to not require the use of the user's back button on forms. If there's an issue with their submission, you're going to need to return the form back to the user with their data filled in. If the user hits her back button to correct the error, her submission will then fail due to the now invalid token.

Also, to be frank, by the time you need to worry about request replays and man-in-the-middle attacks, your user's connection has already been compromised, and there's probably not much you can do to mitigate any damage. SSL alone is an adequate protection level against MITM and replay, and if you're that worried about it, you'll be running under SSL...

3
ответ дан 3 December 2019 в 10:26
поделиться

Чтобы сгенерировать этот токен, я использую стратегию, которая, кажется, работает хорошо.

  • Установите для cookie случайное значение (сгенерированное на сервере с помощью обычных трюков) и установите для него значение срок действия истекает в соответствии с вашими потребностями.
  • При обслуживании страницы с формой вставьте скрытое поле, значение которого равно значению этого файла cookie.
  • При обработке сообщения убедитесь, что это поле существует и что значение соответствует cookie пользователя
1
ответ дан 3 December 2019 в 10:26
поделиться
Другие вопросы по тегам:

Похожие вопросы: