Esta página describe las mejores prácticas para desarrollar su aplicación al usar las bibliotecas cliente de MongoDB. Siga estas recomendaciones para reducir el riesgo de ataques de inyección y otros problemas de seguridad que pueden surgir cuando su aplicación maneja datos de entrada no confiables.
Utilice cadenas de conexión SRV
Use the mongodb+srv:// connection string format instead of the standard mongodb:// format when your deployment supports it. The +srv format automatically enables Transport Layer Security (TLS) for the connection, encrypting traffic between your application and your MongoDB deployment by default. The standard format doesn't enable TLS unless you set it explicitly.
The +srv format also resolves the full list of seed hosts from a DNS SRV record. Your connection string doesn't need updates when the underlying hosts change.
Advertencia
Drivers trust SRV lookup results that share the same parent domain as the original seed hostname. For example, a lookup for foo.example.com may return node1.foo.example.com. It may also return node1.example.com, which shares the example.com parent domain even though it isn't under foo.example.com.
Un servidor DNS malicioso o comprometido puede intentar redirigir su aplicación a un host controlado por un atacante durante el establecimiento de la conexión. La restricción del dominio principal limita este riesgo. Verifique que el dominio principal de su nombre de host semilla se resuelva únicamente en hosts de su clúster o en clústeres controlados por la misma entidad de confianza.
To learn more, see SRV Connection Format and Connection Strings in the MongoDB Server manual.
Validar la entrada no confiable antes de convertir JSON a BSON.
Muchas bibliotecas cliente ofrecen un método práctico para convertir una cadena JSON en un documento BSON, por ejemplo, mediante JSON extendido. Si su aplicación pasa el documento resultante a una consulta, actualización o comando sin validación, un atacante puede alterar el significado de dicha operación.
Consider an API endpoint that accepts a JSON request body and expects a name field containing a string value. Assume the endpoint converts the request body to BSON and uses the result in a query filter without validation. An attacker can submit an object in place of the expected string, as shown in the following example:
{"name": {"$ne": null}}
MongoDB evaluates the $ne field as a query operator instead of as a literal value. Instead of matching a single document by name, this filter matches every document with a non-null name field, exposing more data than intended.
Concatenar datos de entrada no confiables en una cadena JSON antes de convertirla a BSON genera el mismo riesgo. El siguiente ejemplo en C++ crea un filtro de consulta mediante la concatenación de cadenas para insertar un valor proporcionado por el usuario en una cadena JSON:
std::string json_query = "{ \"name\": \"" + user_supplied_name + "\" }"; bsoncxx::document::value filter = bsoncxx::from_json(json_query); mongocxx::cursor cursor = collection.find(filter.view());
If user_supplied_name contains a double quote or a JSON operator, the resulting string can escape the intended field value and inject arbitrary query syntax.
Este riesgo se aplica siempre que una cadena JSON provenga de un usuario, una solicitud a la API u otra fuente que su aplicación no controle. Para reducir este riesgo, verifique el tipo y valide la entrada no confiable antes de convertirla a BSON. Muchos controladores ofrecen una API de documentos tipados o un generador de consultas que puede usar para crear consultas. También puede aplicar un esquema JSON o una capa de validación similar dentro de su aplicación antes de aceptar la entrada JSON para su conversión.
El siguiente ejemplo crea el mismo filtro que el ejemplo de concatenación anterior, pero utiliza un generador de documentos tipado:
bsoncxx::builder::basic::document filter_builder; filter_builder.append( bsoncxx::builder::basic::kvp("name", user_supplied_name)); mongocxx::cursor cursor = collection.find(filter_builder.view());
Because the builder treats user_supplied_name as a value rather than as part of a string to parse, the value can't alter the structure of the query.
Building queries as BSON documents instead of strings avoids traditional SQL injection, since attackers have no query string to manipulate. To learn more, see FAQ: MongoDB Fundamentals in the MongoDB Server manual. To learn more about Extended JSON types and conversions, see MongoDB Extended JSON in the MongoDB Server manual.
Restringir la ejecución de JavaScript del lado del servidor
MongoDB supports operators and commands that execute JavaScript, including $where, $function, $accumulator, and mapReduce. When your application builds one of these expressions from user input, the server executes that input as code. This behavior creates the same class of risk as passing untrusted input to an eval function in application code.
Para reducir este riesgo, siga estas recomendaciones:
Avoid string concatenation: Don't build
$whereexpressions,$functionbodies, or$accumulatorfunctions by concatenating or interpolating untrusted input into a JavaScript string. Use standard query operators instead, since MongoDB evaluates them without executing JavaScript.Disable server-side scripting: Disable server-side scripting if your application doesn't use
$where,$function,$accumulator, ormapReduce. Set thesecurity.javascriptEnabledconfiguration option tofalse, or start themongodormongosprocess and pass the--noscriptingoption.
To learn more about securing server-side JavaScript execution, see Run MongoDB with Secure Configuration Options.
To learn more about the $where operator, see $where in the MongoDB Server manual.
Información Adicional
For a list of best practices on securing self-managed deployments, see the Security Checklist in the MongoDB Server manual.