Remove csurf middleware

This commit is contained in:
Douglas Christopher Wilson
2022-09-13 15:58:22 -04:00
parent ef5e637bc7
commit 867a10d748
36 changed files with 0 additions and 374 deletions

View File

@@ -4,7 +4,6 @@
- [cookie-parser](/resources/middleware/cookie-parser.html)
- [cookie-session](/resources/middleware/cookie-session.html)
- [cors](/resources/middleware/cors.html)
- [csurf](/resources/middleware/csurf.html)
- [errorhandler](/resources/middleware/errorhandler.html)
- [method-override](/resources/middleware/method-override.html)
- [morgan](/resources/middleware/morgan.html)

View File

@@ -1,326 +0,0 @@
# csurf
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][node-url]
[![Build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
Node.js [CSRF][wikipedia-csrf] protection middleware.
Requires either a session middleware or [cookie-parser](https://www.npmjs.com/package/cookie-parser) to be initialized first.
* If you are setting the ["cookie" option](#cookie) to a non-`false` value,
then you must use [cookie-parser](https://www.npmjs.com/package/cookie-parser)
before this module.
* Otherwise, you must use a session middleware before this module. For example:
- [express-session](https://www.npmjs.com/package/express-session)
- [cookie-session](https://www.npmjs.com/package/cookie-session)
If you have questions on how this module is implemented, please read
[Understanding CSRF](https://github.com/pillarjs/understanding-csrf).
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install csurf
```
## API
<!-- eslint-disable no-unused-vars -->
```js
var csurf = require('csurf')
```
### csurf([options])
Create a middleware for CSRF token creation and validation. This middleware
adds a `req.csrfToken()` function to make a token which should be added to
requests which mutate state, within a hidden form field, query-string etc.
This token is validated against the visitor's session or csrf cookie.
#### Options
The `csurf` function takes an optional `options` object that may contain
any of the following keys:
##### cookie
Determines if the token secret for the user should be stored in a cookie
or in `req.session`. Storing the token secret in a cookie implements
the [double submit cookie pattern][owsap-csrf-double-submit].
Defaults to `false`.
When set to `true` (or an object of options for the cookie), then the module
changes behavior and no longer uses `req.session`. This means you _are no
longer required to use a session middleware_. Instead, you do need to use the
[cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware in
your app before this middleware.
When set to an object, cookie storage of the secret is enabled and the
object contains options for this functionality (when set to `true`, the
defaults for the options are used). The options may contain any of the
following keys:
- `key` - the name of the cookie to use to store the token secret
(defaults to `'_csrf'`).
- `path` - the path of the cookie (defaults to `'/'`).
- `signed` - indicates if the cookie should be signed (defaults to `false`).
- `secure` - marks the cookie to be used with HTTPS only (defaults to
`false`).
- `maxAge` - the number of seconds after which the cookie will expire
(defaults to session length).
- `httpOnly` - flags the cookie to be accessible only by the web server
(defaults to `false`).
- `sameSite` - sets the same site policy for the cookie(defaults to
`false`). This can be set to `'strict'`, `'lax'`, `'none'`, or `true`
(which maps to `'strict'`).
- `domain` - sets the domain the cookie is valid on(defaults to current
domain).
##### ignoreMethods
An array of the methods for which CSRF token checking will disabled.
Defaults to `['GET', 'HEAD', 'OPTIONS']`.
##### sessionKey
Determines what property ("key") on `req` the session object is located.
Defaults to `'session'` (i.e. looks at `req.session`). The CSRF secret
from this library is stored and read as `req[sessionKey].csrfSecret`.
If the ["cookie" option](#cookie) is not `false`, then this option does
nothing.
##### value
Provide a function that the middleware will invoke to read the token from
the request for validation. The function is called as `value(req)` and is
expected to return the token as a string.
The default value is a function that reads the token from the following
locations, in order:
- `req.body._csrf` - typically generated by the `body-parser` module.
- `req.query._csrf` - a built-in from Express.js to read from the URL
query string.
- `req.headers['csrf-token']` - the `CSRF-Token` HTTP request header.
- `req.headers['xsrf-token']` - the `XSRF-Token` HTTP request header.
- `req.headers['x-csrf-token']` - the `X-CSRF-Token` HTTP request header.
- `req.headers['x-xsrf-token']` - the `X-XSRF-Token` HTTP request header.
## Example
### Simple express example
The following is an example of some server-side code that generates a form
that requires a CSRF token to post back.
```js
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express()
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.get('/form', csrfProtection, function (req, res) {
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
app.post('/process', parseForm, csrfProtection, function (req, res) {
res.send('data is being processed')
})
```
Inside the view (depending on your template language; handlebars-style
is demonstrated here), set the `csrfToken` value as the value of a hidden
input field named `_csrf`:
```html
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
Favorite color: <input type="text" name="favoriteColor">
<button type="submit">Submit</button>
</form>
```
#### Using AJAX
When accessing protected routes via ajax both the csrf token will need to be
passed in the request. Typically this is done using a request header, as adding
a request header can typically be done at a central location easily without
payload modification.
The CSRF token is obtained from the `req.csrfToken()` call on the server-side.
This token needs to be exposed to the client-side, typically by including it in
the initial page content. One possibility is to store it in an HTML `<meta>` tag,
where value can then be retrieved at the time of the request by JavaScript.
The following can be included in your view (handlebar example below), where the
`csrfToken` value came from `req.csrfToken()`:
```html
<meta name="csrf-token" content="{{csrfToken}}">
```
The following is an example of using the
[Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to post
to the `/process` route with the CSRF token from the `<meta>` tag on the page:
<!-- eslint-env browser -->
```js
// Read the CSRF token from the <meta> tag
var token = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
// Make a request using the Fetch API
fetch('/process', {
credentials: 'same-origin', // <-- includes cookies in the request
headers: {
'CSRF-Token': token // <-- is the csrf token as a header
},
method: 'POST',
body: {
favoriteColor: 'blue'
}
})
```
#### Single Page Application (SPA)
Many SPA frameworks like Angular have CSRF support built in automatically.
Typically they will reflect the value from a specific cookie, like
`XSRF-TOKEN` (which is the case for Angular).
To take advantage of this, set the value from `req.csrfToken()` in the cookie
used by the SPA framework. This is only necessary to do on the route that
renders the page (where `res.render` or `res.sendFile` is called in Express,
for example).
The following is an example for Express of a typical SPA response:
<!-- eslint-disable no-undef -->
```js
app.all('*', function (req, res) {
res.cookie('XSRF-TOKEN', req.csrfToken())
res.render('index')
})
```
### Ignoring Routes
**Note** CSRF checks should only be disabled for requests that you expect to
come from outside of your website. Do not disable CSRF checks for requests
that you expect to only come from your website. An existing session, even if
it belongs to an authenticated user, is not enough to protect against CSRF
attacks.
The following is an example of how to order your routes so that certain endpoints
do not check for a valid CSRF token.
```js
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// create express app
var app = express()
// create api router
var api = createApiRouter()
// mount api before csrf is appended to the app stack
app.use('/api', api)
// now add csrf and other middlewares, after the "/api" was mounted
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(csrf({ cookie: true }))
app.get('/form', function (req, res) {
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
app.post('/process', function (req, res) {
res.send('csrf was required to get here')
})
function createApiRouter () {
var router = new express.Router()
router.post('/getProfile', function (req, res) {
res.send('no csrf to get here')
})
return router
}
```
### Custom error handling
When the CSRF token validation fails, an error is thrown that has
`err.code === 'EBADCSRFTOKEN'`. This can be used to display custom
error messages.
```js
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var express = require('express')
var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(csrf({ cookie: true }))
// error handler
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
// handle CSRF token errors here
res.status(403)
res.send('form tampered with')
})
```
## References
- [Cross-side request forgery on Wikipedia][wikipedia-csrf]
- [OWASP Cross-Site Request Forgery Prevention Cheat Sheet][owsap-csrf]
[owsap-csrf]: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html
[owsap-csrf-double-submit]: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie
[wikipedia-csrf]: https://en.wikipedia.org/wiki/Cross-site_request_forgery
## License
[MIT](LICENSE)
[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/csurf/master
[coveralls-url]: https://coveralls.io/r/expressjs/csurf?branch=master
[node-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/csurf
[npm-url]: https://npmjs.org/package/csurf
[npm-version-image]: https://badgen.net/npm/v/csurf
[travis-image]: https://badgen.net/travis/expressjs/csurf/master
[travis-url]: https://travis-ci.org/expressjs/csurf

View File

@@ -144,7 +144,6 @@ app.use(session({
Dies sind einige weitere Empfehlungen aus der hervorragenden [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). In diesem Blogbeitrag finden Sie alle Details zu diesen Empfehlungen:
* Implementieren Sie Rate-Limiting, um Brute-Force-Attacken gegen Authentifizierungen zu verhindern. Hierfür können Sie beispielsweise das [StrongLoop API Gateway](https://strongloop.com/node-js/api-gateway/) verwenden, um eine Rate-Limiting-Richtlinie durchzusetzen. Alternativ können Sie eine Middleware wie [express-limiter](https://www.npmjs.com/package/express-limiter) verwenden. Hierzu müssen Sie jedoch Ihren Code etwas modifizieren.
* Verwenden Sie die [csurf](https://www.npmjs.com/package/csurf)-Middleware, um CSRF-Attacken (Cross-Site Request Forgery) vorzubeugen.
* Filtern und bereinigen Sie immer Benutzereingaben, um sich gegen XS-Angriffe (Cross-Site Scripting) und Befehlsinjektionsattacken zu schützen.
* Implementieren Sie Verteidungsmaßnahmen gegen SQL-Injection-Attacken, indem sie parametrisierte Abfragen oder vorbereitete Anweisungen einsetzen.
* Nutzen Sie das Open-Source-Tool [sqlmap](http://sqlmap.org/), um SQL-Injection-Schwachstellen in Ihrer Anwendung zu erkennen.

View File

@@ -19,7 +19,6 @@ Nachfolgend sind einige Express-Middlewaremodule aufgeführt:
- [connect-timeout](https://github.com/expressjs/timeout): Bisher: `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser): Bisher: `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session): Bisher: `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf): Bisher: `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler): Bisher: `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug): Entwicklungstool, mit dem eine Registerkarte mit Informationen zu Vorlagenvariablen (lokalen Variablen), zur aktuellen Sitzung, zu hilfreichen Anforderungsdaten usw. Ihrer Anwendung hinzugefügt werden können.
- [express-partial-response](https://github.com/nemtsov/express-partial-response): Express-Middlewaremodul für die Filterung von Teilen von JSON-Antworten auf Basis der Abfragezeichenfolge `fields` durch Verwendung der Google-API Partial Response.

View File

@@ -224,7 +224,6 @@ Finally, Express apps - like any other web apps - can be vulnerable to a variety
Here are some further recommendations from the excellent [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Refer to that blog post for all the details on these recommendations:
* Use [csurf](https://www.npmjs.com/package/csurf) middleware to protect against cross-site request forgery (CSRF).
* Always filter and sanitize user input to protect against cross-site scripting (XSS) and command injection attacks.
* Defend against SQL injection attacks by using parameterized queries or prepared statements.
* Use the open-source [sqlmap](http://sqlmap.org/) tool to detect SQL injection vulnerabilities in your app.

View File

@@ -20,7 +20,6 @@ The Express middleware modules listed here are maintained by the
| [cookie-parser](/resources/middleware/cookie-parser.html) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies) and [keygrip](https://github.com/jed/keygrip). | express.cookieParser|
| [cookie-session](/resources/middleware/cookie-session.html) | Establish cookie-based sessions.| express.cookieSession |
| [cors](/resources/middleware/cors.html) | Enable cross-origin resource sharing (CORS) with various options.| NA
| [csurf](/resources/middleware/csurf.html) | Protect from CSRF exploits.|express.csrf |
| [errorhandler](/resources/middleware/errorhandler.html) |Development error-handling/debugging. |express.errorHandler |
| [method-override](/resources/middleware/method-override.html) |Override HTTP methods using header. |express.methodOverride |
| [morgan](/resources/middleware/morgan.html) | HTTP request logger. | express.logger |

View File

@@ -1,8 +0,0 @@
---
layout: middleware
title: Express csurf middleware
menu: resources
lang: en
redirect_from: '/resources/middleware/csurf.html'
module: csurf
---

View File

@@ -204,7 +204,6 @@ Por último, las aplicaciones de Express, como cualquier otra aplicación web, s
A continuación, se muestran algunas recomendaciones para la excelente lista de comprobación [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Consulte el post de este blog para ver todos los detalles de estas recomendaciones:
* Implemente el límite de velocidad para evitar ataques de fuerza bruta contra la autenticación. Una forma de hacerlo es utilizar [StrongLoop API Gateway](https://strongloop.com/node-js/api-gateway/) para forzar una política de limitación de velocidad. También puede utilizar middleware como [express-limiter](https://www.npmjs.com/package/express-limiter), aunque para ello deberá modificar el código de alguna forma.
* Utilice el middleware [csurf](https://www.npmjs.com/package/csurf) para protegerse contra la falsificación de solicitudes entre sitios (CSRF).
* Filtre y sanee siempre la entrada de usuario para protegerse contra los ataques de scripts entre sitios (XSS) e inyección de mandatos.
* Defiéndase contra los ataques de inyección de SQL utilizando consultas parametrizadas o sentencias preparadas.
* Utilice la herramienta [sqlmap](http://sqlmap.org/) de código abierto para detectar vulnerabilidades de inyección de SQL en la aplicación.

View File

@@ -19,7 +19,6 @@ Estos son algunos módulos de middleware de Express:
- [connect-timeout](https://github.com/expressjs/timeout): anteriormente `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser): anteriormente `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session): anteriormente `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf): anteriormente `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler): anteriormente `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug): herramienta de desarrollo discreta que añade a la aplicación un separador con información sobre las variables de plantilla (locals), la sesión actual, datos de solicitud útiles, etc.
- [express-partial-response](https://github.com/nemtsov/express-partial-response): módulo de middleware de Express middleware para filtrar partes de las respuestas JSON basándose en la serie de consulta `fields`; utiliza la respuesta parcial de la API de Google.

View File

@@ -144,7 +144,6 @@ app.use(session({
Voici d'autres recommandations issues de l'excellente [liste de contrôle de sécurité Node.js](https://blog.risingstack.com/node-js-security-checklist/). Pour tous les détails sur ces recommandations, reportez-vous à cet article de blogue :
* Implémentez la limitation de débit pour empêcher les attaques de force brute liées à l'authentification. Une façon de faire consiste à utiliser [StrongLoop API Gateway](https://strongloop.com/node-js/api-gateway/) pour mettre en place une règle de limitation de débit. Sinon, vous pouvez utiliser des middleware tels que [express-limiter](https://www.npmjs.com/package/express-limiter), mais vous devrez alors modifier quelque peu votre code.
* Utilisez le middleware [csurf](https://www.npmjs.com/package/csurf) pour vous protéger contre les CSRF (Cross-Site Request Forgery).
* Filtrez et nettoyez toujours les entrées utilisateur pour vous protéger contre les attaques de cross-site scripting (XSS) et d'injection de commande.
* Défendez-vous contre les attaques par injection SQL en utilisant des requêtes paramétrées ou des instructions préparées.
* Utilisez l'outil [sqlmap](http://sqlmap.org/) à code source ouvert pour détecter les vulnérabilités par injection SQL dans votre application.

View File

@@ -19,7 +19,6 @@ Voici quelques modules de middleware Express :
- [connect-timeout](https://github.com/expressjs/timeout) : précédemment `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser) : précédemment `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session) : précédemment `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf) : précédemment `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler) : précédemment `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug) : outil de développement discret qui ajoute un onglet avec des informations sur les variables de canevas (environnements locaux), les sessions en cours, les données de demandes utiles et bien plus, à votre application.
- [express-partial-response](https://github.com/nemtsov/express-partial-response) : module Express Middleware permettant de filtrer des éléments de réponses JSON en fonction de la chaîne de requête `zones` ; en utilisant la réponse partielle de l'API Google.

View File

@@ -14,7 +14,6 @@ expressjs connect-rid master
expressjs cookie-parser master
expressjs cookie-session master
expressjs cors master
expressjs csurf master
expressjs errorhandler master
expressjs method-override master
expressjs morgan master

View File

@@ -144,7 +144,6 @@ app.use(session({
Ecco alcuni consigli sull'eccellente [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Fare riferimento a quel post del blog per tutti i dettagli su questi consigli:
* Implementare il limite di intervallo per evitare attacchi pesanti al processo di autenticazione. Un modo per effettuare ciò è quello di utilizzare [StrongLoop API Gateway](https://strongloop.com/node-js/api-gateway/) per rafforzare una policy per il limite di intervallo. In alternativa, è possibile utilizzare il middleware, ad esempio [express-limiter](https://www.npmjs.com/package/express-limiter), ma questo richiede di modificare in parte il codice.
* Utilizzare il middleware [csurf](https://www.npmjs.com/package/csurf) come protezione contro CSRF (cross-site request forgery).
* Filtrare sempre e verificare gli input utente come protezione contro attacchi XSS (cross-site scripting) e command injection.
* Creare una difesa contro attacchi SQL injection utilizzando query con parametri o istruzioni preparate.
* Utilizzare lo strumento [sqlmap](http://sqlmap.org/) open source per rilevare le vulnerabilità SQL injection nell'applicazione.

View File

@@ -19,7 +19,6 @@ Di seguito vengono riportati alcuni moduli middleware Express:
- [connect-timeout](https://github.com/expressjs/timeout): in precedenza `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser): in precedenza `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session): in precedenza `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf): in precedenza `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler): in precedenza `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug): uno strumento di sviluppo riservato che aggiunge una scheda contenente informazioni sulle variabili di template (locali), sessione corrente, dati della richiesta utili e altro ancora all'applicazione.
- [express-partial-response](https://github.com/nemtsov/express-partial-response): modulo middleware Express per filtrare le parti delle risposte JSON in base alla stringa query `fields`; utilizzando una risposta parziale API Google.

View File

@@ -186,7 +186,6 @@ $ snyk wizard
次に、優れた [Node.js セキュリティー・チェックリスト](https://blog.risingstack.com/node-js-security-checklist/)に記載されているその他の推奨事項をリストします。これらの推奨事項の詳細については、ブログの投稿を参照してください。
* 認証に対する総当たり攻撃を防止するために、回数制限を実装してください。そのための 1 つの方法では、[StrongLoop API Gateway](https://strongloop.com/node-js/api-gateway/) を使用して回数制限ポリシーを適用します。あるいは、[express-limiter](https://www.npmjs.com/package/express-limiter) などのミドルウェアを使用できますが、そのためにはコードを若干変更する必要があります。
* クロスサイト・リクエスト・フォージェリー (CSRF) から保護するために、[csurf](https://www.npmjs.com/package/csurf) ミドルウェアを使用してください。
* クロスサイト・スクリプティング (XSS) とコマンド・インジェクション攻撃から保護するために、必ず、ユーザー入力のフィルタリングとサニタイズを実行してください。
* パラメーター化照会または作成済みステートメントを使用して、SQL インジェクション攻撃に対して防衛してください。
* オープン・ソースの [sqlmap](http://sqlmap.org/) ツールを使用して、アプリケーションの SQL インジェクションに対する脆弱性を検出してください。

View File

@@ -18,7 +18,6 @@ lang: ja
- [connect-timeout](https://github.com/expressjs/timeout): 以前の `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser): 以前の `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session): 以前の `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf): 以前の `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler): 以前の `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug): テンプレート変数 (ローカル)、現行セッション、有用な要求データなどに関する情報を示すタブをアプリケーションに追加する小規模な開発ツール。
- [express-partial-response](https://github.com/nemtsov/express-partial-response): Google API の Partial Response を使用することで、`fields` 照会ストリングに基づいて JSON 応答の一部をフィルターで除去するための Express ミドルウェア・モジュール。

View File

@@ -199,7 +199,6 @@ Express에, 또는 앱에 사용되는 다른 모듈에 영향을 미칠 수 있
유용한 [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/)에서 발췌한 몇 가지 추가적인 권장사항은 다음과 같습니다. 아래의 권장사항에 대한 모든 상세 정보를 확인하려면 해당 블로그 게시물을 참조하십시오.
* [csurf](https://www.npmjs.com/package/csurf) 미들웨어를 이용하여 교차 사이트 요청 위조(CSRF)로부터 보호하십시오.
* 항상 사용자 입력을 필터링하고 사용자 입력에서 민감한 데이터를 제거하여 XSS(Cross-site scripting) 및 명령 인젝션 공격으로부터 보호하십시오.
* 매개변수화된 조회 또는 준비된 명령문을 이용하여 SQL 인젝션 공격으로부터 방어하십시오.
* 오픈 소스 방식의 [sqlmap](http://sqlmap.org/) 도구를 이용하여 앱 내의 SQL 인젝션 취약성을 발견하십시오.

View File

@@ -19,7 +19,6 @@ module: mw-home
| [cookie-parser](/resources/middleware/cookie-parser.html) | 쿠키 헤더를 파싱하고 `req.cookies`에 할당합니다. [cookies](https://github.com/jed/cookies)와 [keygrip](https://github.com/jed/keygrip)도 참고하세요. | express.cookieParser |
| [cookie-session](/resources/middleware/cookie-session.html) | 쿠키 기반의 세션을 만듭니다. | express.cookieSession |
| [cors](/resources/middleware/cors.html) | 다양한 옵션들을 이용하여 Cross-origin resource sharing (CORS)를 활성화합니다. | 없음 |
| [csurf](/resources/middleware/csurf.html) | CSRF 취약점을 방어합니다. | express.csrf |
| [errorhandler](/resources/middleware/errorhandler.html) | 개발 중에 발생하는 에러를 핸들링하고 디버깅합니다. | express.errorHandler |
| [method-override](/resources/middleware/method-override.html) | 헤더를 이용해 HTTP method를 덮어씁니다. | express.methodOverride |
| [morgan](/resources/middleware/morgan.html) | HTTP 요청 로그를 남깁니다. | express.logger |

View File

@@ -223,7 +223,6 @@ bruta contra a autenticação. Uma forma de fazer isso é usar o [Gateway
da API do StrongLoop](https://strongloop.com/node-js/api-gateway/) para impingir políticas de limitação de tráfego. Alternativamente,
é possível usar um middleware como o [express-limiter](https://www.npmjs.com/package/express-limiter),
mas fazer isso irá requerer que você modifique seu código de alguma forma.
* Use o middleware [csurf](https://www.npmjs.com/package/csurf) para se proteger contra falsificações de solicitação cross-site (CSRF).
* Sempre filtrar e limpar a entrada do usuário para se proteger de ataques de cross-site scripting (XSS) e injeção de comando.
* Proteja-se contra ataques de injeção de SQLs usando consultas parametrizadas ou instruções preparadas.
* Use a ferramenta de software livre [sqlmap](http://sqlmap.org/) para detectar

View File

@@ -20,7 +20,6 @@ Aqui estão alguns módulos middleware do Express:
- [connect-timeout](https://github.com/expressjs/timeout): anteriormente `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser): anteriormente `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session): anteriormente `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf): anteriormente `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler): anteriormente `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug): ferramenta não obstrutiva de desenvolvimento que inclui uma guia com informações sobre variáveis de modelo (locais), sessão corrente, dados de solicitação úteis e mais para o seu aplicativo.
- [express-partial-response](https://github.com/nemtsov/express-partial-response): módulo de middleware do Express para filtrar partes das respostas JSON baseado nos `fields` da sequência de consultas; usando a Resposta parcial da API do Google.

View File

@@ -144,7 +144,6 @@ app.use(session({
Ниже приводится несколько дополнительных рекомендаций, взятых из исчерпывающего [Контрольного списка требований к защите Node.js](https://blog.risingstack.com/node-js-security-checklist/). В этой публикации можно найти дополнительную информацию по всем приведенным ниже рекомендациям:
* Введите ограничение скорости передачи данных во избежание атак методом грубого подбора сочетаний символов для идентификации. Для реализации стратегии ограничения скорости передачи данных можно воспользоваться [Шлюзом API StrongLoop](https://strongloop.com/node-js/api-gateway/). В качестве альтернативы, можно использовать промежуточный обработчик, например, [express-limiter](https://www.npmjs.com/package/express-limiter), но для этого придется внести некоторые изменения в код.
* Используйте промежуточный обработчик [csurf](https://www.npmjs.com/package/csurf) для защиты от подделки межсайтовых запросов (CSRF).
* Всегда применяйте фильтрацию и очистку пользовательского ввода в целях защиты от атак межсайтового скриптинга (XSS) и ввода ложных команд.
* Обеспечьте защиту от атак внедрения SQL-кода с помощью параметризованных запросов или подготовленных операторов.
* Используйте инструмент [sqlmap](http://sqlmap.org/) с открытым исходным кодом для выявления уязвимостей к внедрению SQL-кода в приложение.

View File

@@ -19,7 +19,6 @@ lang: ru
- [connect-timeout](https://github.com/expressjs/timeout): ранее `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser): ранее `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session): ранее `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf): ранее `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler): ранее `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug): простой инструмент разработки, предназначенный для добавления вкладки с информацией о переменных шаблона (локалях), текущем сеансе, полезных данных запроса и т.д. для приложения.
- [express-partial-response](https://github.com/nemtsov/express-partial-response): Модуль промежуточного обработчика Express для отфильтровывания частей ответов JSON на основе строки запроса `fields`; используется Частичный ответ API Google.

View File

@@ -151,7 +151,6 @@ app.use(session({
Tu sú ďalšie odporúčania zo skvelého [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/) zoznamu. Pre viac detailov ohľadom jednotlivých odporúčaní si prečítajte samotný blog post:
* Implementujte tzv. rate-limiting pre vyhnutie sa brute-force útokom voči autentifikácii. Jednou z možností ako to dosiahnuť je použitie [StrongLoop API Gateway](https://strongloop.com/node-js/api-gateway/) k vynúteniu rate-limiting policy. Ako alternatívu môžete použiť middleware, ako napr. [express-limiter](https://www.npmjs.com/package/express-limiter), avšak to si už vyžaduje mierny zásah do kódu vašej aplikácie.
* Používajte [csurf](https://www.npmjs.com/package/csurf) middleware k ochrane voči útokom typu cross-site request forgery (CSRF).
* Vždy filtrujte a overte vstup od používateľa, aby ste vašu aplikáciu ochránili voči útokom typu cross-site scripting (XSS) a command injection.
* Bránte sa voči útokom typu SQL injection použitím parametrizovaych queries, príp. prepared statements.
* Používajte open source tool [sqlmap](http://sqlmap.org/) k detekcii SQL injection vulnerabilities vo vašej aplikácii.

View File

@@ -23,7 +23,6 @@ Tu je zoznam niektorých Express middleware modulov:
- [connect-timeout](https://github.com/expressjs/timeout): kedysi `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser): kedysi `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session): kedysi `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf): kedysi `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler): kedysi `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug): nenápadný development tool, ktorý pridá panel s informáciami ohľadom template premenných, aktuálnej session, informácie o request dátach a ďalšie užitočné informácie.
- [express-partial-response](https://github.com/nemtsov/express-partial-response): Express middleware modul slúžiaci k odfiltrovaniu častí JSON odpovedi na podľa hodnoty query parametra `fields`.

View File

@@ -192,7 +192,6 @@ Finally, Express apps - like any other web apps - can be vulnerable to a variety
Here are some further recommendations from the excellent [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Refer to that blog post for all the details on these recommendations:
* Implement rate-limiting to prevent brute-force attacks against authentication. One way to do this is to use [StrongLoop API Gateway](https://strongloop.com/node-js/api-gateway/) to enforce a rate-limiting policy. Alternatively, you can use middleware such as [express-limiter](https://www.npmjs.com/package/express-limiter), but doing so will require you to modify your code somewhat.
* Use [csurf](https://www.npmjs.com/package/csurf) middleware to protect against cross-site request forgery (CSRF).
* Always filter and sanitize user input to protect against cross-site scripting (XSS) and command injection attacks.
* Defend against SQL injection attacks by using parameterized queries or prepared statements.
* Use the open-source [sqlmap](http://sqlmap.org/) tool to detect SQL injection vulnerabilities in your app.

View File

@@ -19,7 +19,6 @@ The Express middleware modules listed here are maintained by the
| [cookie-parser](/resources/middleware/cookie-parser.html) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies) and [keygrip](https://github.com/jed/keygrip). | express.cookieParser|
| [cookie-session](/resources/middleware/cookie-session.html) | Establish cookie-based sessions.| express.cookieSession |
| [cors](/resources/middleware/cors.html) | Enable cross-origin resource sharing (CORS) with various options.| NA
| [csurf](/resources/middleware/csurf.html) | Protect from CSRF exploits.|express.csrf |
| [errorhandler](/resources/middleware/errorhandler.html) |Development error-handling/debugging. |express.errorHandler |
| [method-override](/resources/middleware/method-override.html) |Override HTTP methods using header. |express.methodOverride |
| [morgan](/resources/middleware/morgan.html) | HTTP request logger. | express.logger |

View File

@@ -1,7 +0,0 @@
---
layout: middleware
title: Express csurf middleware
menu: resources
lang: en
module: csurf
---

View File

@@ -198,7 +198,6 @@ Son olarak, Express uygulamaları - diğer web uygulamaları gibi - çeşitli we
İşte mükemmel [Node.js Güvenlik Kontrol Listesi](https://blog.risingstack.com/node-js-security-checklist/)'nden bazı ek öneriler. Bu önerilerle ilgili tüm ayrıntılar için o blog gönderisine bakın:
* Siteler arası istek sahteciliği'ne (CSRF) karşı korumak için [csurf](https://www.npmjs.com/package/csurf) ara yazılımını kullanın.
* Siteler arası komut dosyası oluşturma (XSS) ve komut enjeksiyon saldırılarına karşı korumak için kullanıcı girişini her zaman filtreleyin ve sanitize edin.
* Parametreli sorgular veya hazırlanmış ifadeler kullanarak SQL enjeksiyon saldırılarına karşı savunma yapın.
* Uygulamanızdaki SQL enjeksion güvenlik açıklarını tespit etmek için açık kaynak olan [sqlmap](http://sqlmap.org/) aracını kullanın.

View File

@@ -18,7 +18,6 @@ The Express middleware modules listed here are maintained by the
| [cookie-parser](/resources/middleware/cookie-parser.html) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies) and [keygrip](https://github.com/jed/keygrip). | express.cookieParser|
| [cookie-session](/resources/middleware/cookie-session.html) | Establish cookie-based sessions.| express.cookieSession |
| [cors](/resources/middleware/cors.html) | Enable cross-origin resource sharing (CORS) with various options.| NA
| [csurf](/resources/middleware/csurf.html) | Protect from CSRF exploits.|express.csrf |
| [errorhandler](/resources/middleware/errorhandler.html) |Development error-handling/debugging. |express.errorHandler |
| [method-override](/resources/middleware/method-override.html) |Override HTTP methods using header. |express.methodOverride |
| [morgan](/resources/middleware/morgan.html) | HTTP request logger. | express.logger |

View File

@@ -170,7 +170,6 @@ $ snyk wizard
Here are some further recommendations from the excellent [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Refer to that blog post for all the details on these recommendations:
* Implement rate-limiting to prevent brute-force attacks against authentication. One way to do this is to use [StrongLoop API Gateway](https://strongloop.com/node-js/api-gateway/) to enforce a rate-limiting policy. Alternatively, you can use middleware such as [express-limiter](https://www.npmjs.com/package/express-limiter), but doing so will require you to modify your code somewhat.
* Use [csurf](https://www.npmjs.com/package/csurf) middleware to protect against cross-site request forgery (CSRF).
* Always filter and sanitize user input to protect against cross-site scripting (XSS) and command injection attacks.
* Defend against SQL injection attacks by using parameterized queries or prepared statements.
* Use the open-source [sqlmap](http://sqlmap.org/) tool to detect SQL injection vulnerabilities in your app.

View File

@@ -19,7 +19,6 @@ Here are some Express middleware modules:
- [connect-timeout](https://github.com/expressjs/timeout): previously `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser): previously `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session): previously `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf): previously `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler): previously `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug): unobtrusive development tool that adds a tab with information about template variables (locals), current session, useful request data, and more to your application.
- [express-partial-response](https://github.com/nemtsov/express-partial-response): Express middleware module for filtering-out parts of JSON responses based on the `fields` query-string; by using Google API's Partial Response.

View File

@@ -19,7 +19,6 @@ Here are some Express middleware modules:
- [connect-timeout](https://github.com/expressjs/timeout): previously `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser): previously `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session): previously `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf): previousy `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler): previously `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug): unobtrusive development tool that adds a tab with information about req, session, locals, and more to your application.
- [express-partial-response](https://github.com/nemtsov/express-partial-response): Express middleware for filtering-out parts of JSON responses based on the `fields` query-string; using Google API's Partial Response.

View File

@@ -144,7 +144,6 @@ app.use(session({
以下是来自非常出色的 [Node.js 安全核对表](https://blog.risingstack.com/node-js-security-checklist/)的一些进一步建议。请参阅此博客帖子以了解关于这些建议的所有详细信息:
* 实施速率限制,防止针对认证的暴力攻击。实现这一点的一种方式是使用 [StrongLoop API ](https://strongloop.com/node-js/api-gateway/)来强制实施速率限制策略。或者,可以使用诸如 [express-limiter](https://www.npmjs.com/package/express-limiter) 的中间件,但是这样做需要对代码作些修改。
* 使用 [csurf](https://www.npmjs.com/package/csurf) 中间件来防御跨站点请求伪造 (CSRF)。
* 始终过滤和净化用户输入,防御跨站点脚本编制 (XSS) 和命令注入攻击。
* 使用参数化查询或预编译的语句来防御 SQL 注入攻击。
* 使用开源的 [sqlmap](http://sqlmap.org/) 工具来检测应用程序中的 SQL 注入漏洞。

View File

@@ -18,7 +18,6 @@ lang: zh-cn
- [connect-timeout](https://github.com/expressjs/timeout):先前为 `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser):先前为 `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session):先前为 `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf):先前为 `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler):先前为 `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug):不引人注目的开发工具,用于向应用程序添加一个选项卡,其中包含有关模板变量(本地)、当前会话、有用请求数据等方面的信息。
- [express-partial-response](https://github.com/nemtsov/express-partial-response)Express 中间件模块,使用 Google API 的 Partial Response根据 `fields` 查询字符串过滤掉 JSON 响应的各个部分。

View File

@@ -148,7 +148,6 @@ app.use(session({
以下是優異的 [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/) 所提供的進一步建議。如需這些建議的所有詳細資料,請參閱該部落格文章:
* 實作速率限制,以防對鑑別發動強制入侵攻擊。其中一個作法是使用 [StrongLoop API Gateway](https://strongloop.com/node-js/api-gateway/) 來施行速率限制原則。或者,您可以使用 [express-limiter](https://www.npmjs.com/package/express-limiter) 之類的中介軟體,但是如果這樣做,您需要稍微修改程式碼。
* 使用 [csurf](https://www.npmjs.com/package/csurf) 中介軟體,來防範偽造跨網站要求 (CSRF)。
* 一律對使用者輸入進行過濾和消毒,來防範跨網站 Scripting (XSS) 和指令注入攻擊。
* 使用參數化查詢或備妥陳述式,來防禦 SQL 注入攻擊。
* 使用開放程式碼 [sqlmap](http://sqlmap.org/) 工具,來偵測您應用程式中的 SQL 注入漏洞。

View File

@@ -18,7 +18,6 @@ lang: zh-tw
- [connect-timeout](https://github.com/expressjs/timeout):即先前的 `express.timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser):即先前的 `express.cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session):即先前的 `express.cookieSession`
- [csurf](https://github.com/expressjs/csurf):即先前的 `express.csrf`
- [errorhandler](https://github.com/expressjs/errorhandler):即先前的 `express.errorHandler`
- [express-debug](https://github.com/devoidfury/express-debug):低調的開發工具,可在您的應用程式中新增標籤,內含範本變數 (locals)、現行階段作業、有用的要求資料等相關資訊。
- [express-partial-response](https://github.com/nemtsov/express-partial-response)Express 中介軟體模組,會根據 `fields` 查詢字串,使用 Google API 的 Partial Response 來濾除 JSON 回應部分。