Nikos C.
Nikos C.

Reputation: 51910

How do I enforce SSL when using WebClient?

In a .NET 2.0 Forms application, I'm using WebClient to communicate with a web server over SSL. In the communication, a password is sent to the server in the HTTP GET or POST parameters (meaning it's put in WebClient.QueryString).

The transmission of the password in cleartext must (obviously) be avoided. Right now, and what I've done so far, is to assume that simply making sure that the URI argument to the various WebClient functions begins with "https://" is enough:

// 'path' is something like "www.example.com/example.php"
var uri = new Uri(string.Format("https://{0}", path));
webCl.QueryString = new NameValueCollection();
webCl.QueryString.Add("passwd", "my_password");
var reply = webCl.DownloadString(uri);

But I'm not sure. Is this really enough to guarantee that no cleartext transmission of the GET or POST parameters (for UploadString()) is happening if the connection is not encrypted? My assumption is that the transmission of the HTTP parameters will not happen if the SSL handshake fails, and that the SSL handshake can only succeed if encryption is enabled.

Upvotes: 1

Views: 1300

Answers (1)

Armin Sadeghi
Armin Sadeghi

Reputation: 845

You assumption is correct. If you force the base URI to be "https" then the querystring traffic will be over an encrypted SSL link. You can alternatively use the WebClient.BaseAddress property.

What you may want to be particular about however is the specific security protocol that you allow. In particular, after the recent SSL 3 security issues, you may want to only allow TLS.

System.Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Tls

On a related note, you will of course want to put a try/catch around your call to DownloadString to ensure you handle errors.

Upvotes: 1

Related Questions