When our C++ applications make HTTP requests to servers, there are a number of security considerations to keep in mind to protect our application and users.
If our application sends or receives sensitive data like passwords, API keys, personally identifiable information, etc., the requests and responses must be encrypted. Use https://
URLs instead of http://
to enable SSL/TLS encryption of the traffic.
When using HTTPS, the server's SSL certificate should be validated to ensure we're communicating with the genuine server and not an imposter. By default, cpr validates certificates using the CA (Certificate Authority) certificates installed on the system.
On Windows, cpr uses the Windows Certificate Store. On Unix-based systems, it uses the directory specified by the SSL_CERT_DIR
environment variable, or /usr/lib/ssl/certs
as a fallback.
We can specify custom CA certificates to use instead:
#include <cpr/cpr.h>
int main() {
cpr::Url URL{"https://www.example.com"};
cpr::SslOptions sslOpts{
.ca_info = "path/to/ca-bundle.crt"
};
cpr::Response r = cpr::Get(URL, sslOpts);
}
If we're including user input in the request URL or parameters, it must be properly URL-encoded to prevent injection attacks. The cpr functions handle this for us when we use the cpr::Parameters
type. But if we're constructing URLs manually, we need to be careful.
Any data included in requests, whether in the URL, headers or body, should be treated as untrusted input. Validate it matches the expected format before processing it further or including it in SQL queries, shell commands, file paths, etc. Common validations include:
To protect the servers we communicate with and prevent abuse, it's a good practice to limit the rate at which our application makes requests. Implement exponential backoff to progressively increase the delay between retries if requests are failing.
Be a good citizen and respect the X-RateLimit
headers included in responses, which tell us the maximum number of requests allowed per time period.
By following these best practices, we can help ensure our applications handle HTTP communication safely and securely.
Answers to questions are automatically generated and may not have been reviewed.
A detailed and practical tutorial for working with HTTP in modern C++ using the cpr
library.