Showing posts with label Networking. Show all posts
Showing posts with label Networking. Show all posts

2014-11-14

Basic Authentication, SSL and Pyslet's HTTP/OData client

Pyslet is my Python package for Standards in Learning Education and Training and represents a packaging up of the core of my QTI migration script code in a form that makes it easier for other developers to use. Earlier this year I released Pyslet to PyPi and moved development to Github to make it easier for people to download, install and engage with the source code.

Note: this article updated 2017-05-24 with code correction (see comments for details).

Warning: The code in this article will work with the latest Pyslet master from Github, and with any distribution on or later than pyslet-0.5.20141113. At the time of writing the version on PyPi has not been updated!

A recent issue that came up concerns Pyslet's HTTP client. The client is the base class for Pyslet's OData client. In my own work I often use this client to access OData feeds protected with HTTP's basic authentication but I've never properly documented how to do it. There are two approaches...

The simplest way, and the way I used to do it, is to override the client object itself and add the Authorization header at the point where each request is queued.

from pyslet.http.client import Client

class MyAuthenticatedClient(Client):

    # add an __init__ method to set some credentials 
    # in the client

    def queue_request(self, request):
        # add in the authorization credentials
        if (self.credentials is not None and
                not request.has_header("Authorization")):
            request.set_header('Authorization',
                               str(self.credentials))
            super(MyAuthenticatedClient, self).queue_request(request)

This works OK but it forces the issue a bit and will result in the credentials being sent to all URLs, which you may not want. The credentials object should be an instance of pyslet.http.auth.BasicCredentials which takes care of correctly formatting the header. Here is some sample code to create that object:

from pyslet.http.auth import BasicCredentials
from pyslet.rfc2396 import URI

credentials = BasicCredentials()
credentials.userid = "user@example.com"
credentials.password = "secretPa$$word"
credentials.protectionSpace = URI.from_octets(
    'https://www.example.com/mypage').get_canonical_root()

With the above code, str(credentials) returns the string: 'Basic dXNlckBleGFtcGxlLmNvbTpzZWNyZXRQYSQkd29yZA==' which is what you'd expect to pass in the Authorization header.

To make this code play more nicely with the HTTP standard I added some core-support to the HTTP client itself, so you don't need to override the class anymore. The HTTP client now has a credential store and an add_credentials method. Once added, the following happens when a 401 response is received:

  1. The client iterates through any received challenges
  2. Each challenge is matched against the stored credentials
  3. If matching credentials are found then an Authorization header is added and the request resent
  4. If the request receives another 401 response the credentials are removed from the store and we go back to (1)

This process terminates when there are no more credentials that match any of the challenges or when a code other than 401 is received.

If the matching credentials are BasicCredentials (and that's the only type Pyslet supports out of the box!), then some additional logic gets activated on success. RFC 2617 says that for basic authentication, a challenge implies that all paths "at or deeper than the depth of the last symbolic element in the path field" fall into the same protection space. Therefore, when credentials are used successfully, Pyslet adds the path to the credentials using BasicCredentials.add_success_path. Next time a request is sent to a URL on the same server with a path that meets this criterium the Authorization header will be added pre-emptively.

If you want to pre-empt the 401 handling completely then you just need to add a suitable path to the credentials before you add them to the client. So if you know your credentials are good for everything in /website/~user/ you could continue the above code like this:

credentials.add_success_path('/website/~user/')

That last slash is really important, if you leave it off it will add everything in '/website/' to your protection space which is probably not what you want.

SSL

If you're going to pass basic auth credentials around you really should be using https. Python makes it a bit tricky to use HTTPs and be sure that you are using a trusted connection. Pyslet tries to make this a little bit easier. Here's what I do.

  1. With Firefox, go to the site in question and check that SSL is working properly
  2. Export the certificate from the site in PEM format and save to disk, e.g., www.example.com.crt
  3. Repeat for any other sites I want my python script to work with.
  4. Concatenate the files together and save them to, say, 'certificates.pem'
  5. Pass this file name to the HTTP (or OData) client constructor.
from pyslet.http.client import Client

my_client = Client(ca_certs='certificates.pem')
my_client.add_credentials(credentials)

In this code, I've assumed that the credentials were created as above. To be really sure you are secure here, try grabbing a file from a different site or, even better, generate a self-signed certificate and use that instead. (The master version of Pyslet currently has such a certificate ready made in unittests/data_rfc2616/server.crt). Now pass that file for ca_certs and check that you get SSL errors! If you don't, something is broken and you should proceed with caution, or you may just be on a Mac (see notes in Is Python's SSL module correctly validating certificates... for details). And don't pass None for ca_certs as that tells the ssl module not to check at all!

If you don't like messing around with the certificates, and you are using a machine and network that is pretty trustworthy and from which you would happily do your internet banking then the following can be used to proxy for the browser method:

import ssl, string
import pyslet.rfc2396 as uri

certs = []
for s in ('https://www.example.com', 'https://www.example2.com', ):
    # add other sites to the above tuple as you like
    url = uri.URI.from_octets(s)
    certs.append(ssl.get_server_certificate(url.get_addr(),
                 ssl_version=ssl.PROTOCOL_TLSv1))
    with open('certificates.pem', 'wb') as f:
        f.write(string.join(certs,''))

Passing the ssl_version is optional above but the default setting in many Python installations will use the discredited SSLv3 or worse and your server may refuse to serve you, I know mine does! Set it to a protocol you trust.

Remember that you'll have to do this every so often because server certificates expire. You can always grab the certificate authority's certificate instead (and thereby trust a whole slew of sites at once) but if you're going that far then there are better recipes for finding and re-using the built-in machine certificate store anyway. The beauty of this method is that you can self-sign a server certificate you trust and connect to it securely with a Python client without having to mess around with certificate authorities at all, provided you can safely courier the certificate from your server to your client that is! If you are one of the growing number of people who think the whole trust thing is broken anyway since Snowden then this may be an attractive option.

With thanks to @bolhovsky on Github for bringing the need for this article to my attention.

2012-08-14

Thomson Routers from plusnet: problems using Gmail over wifi?

Summary

If you came to this page because of a Google search for this problem then here is my advice in a nutshell:

  1. Turn off the "Web Browsing Interception" feature in your router by setting it to "disabled".
  2. Set your wifi to b/g operation only to reduce data speeds - you probably don't need more than 54Mb/s if you are on ADSL
  3. Power the router off, count to 30 and power it back on.
  4. If the problem returns, repeat step 3.
  5. If the problem comes back frequently consider using a cheap timer plug to power cycle the router automatically in the middle of the night.

Oh, while you're here, could you just look at my PC?

Everyone who works in any job that is vaguely computer related will know that sometimes, when visiting a friend or relation's house the conversation will come around to some little problem they are having with their PC or home network. I had just such an experience at the weekend. I would normally have attempted to post the technical workaround to the plusnet forum where the particular issue I was debugging is being discussed but you have to be a plusnet customer to use the forums and I'm just a visiting techie so I'm posting what I know here.

The Symptoms

The scenario is a simple home network with a Thomson TG585 v8 ADSL router supplied by plusnet and an ordinary Dell laptop. I actually got a report of this problem earlier in the year. The main symptom was that email with attachments couldn't be sent. As the laptop owner spoke to me on a cordless wireless phone I could hear some interference on the line each time the laptop tried to send the email.

The First Diagnosis

This network is in a fairly isolated spot with only one other house within wifi range so interference from other wifi networks seemed unlikely. However, the house does have a cordless phone with a signal booster to reach to outbuildings. As is often the case with wifi issues you have to suspect interference, some older cordless phones are simply unusable alongside 2.4GHz routers. The obvious test is to instruct the user to plug their laptop directly in to one of the ethernet ports on the back of the router. Sure enough, the problem went away.

So is wifi really incompatible with this make of phone? The phone is of a modern design and is supposed to be compatible with wifi but perhaps that booster is the problem? To make the cable-based workaround easier the router was moved nearer the laptop. This took it further away from the phone and the booster - I had hoped that this might improve wifi connectivity enough for attachments to work but the problem remained. Needless to say, next time I visited the house the subject came up!

The problem gets worse

I must confess, I had forgotten about the problem completely until I arrived at the house and attempted to send an email via their wifi network from my own laptop. I was able to receive all my email no problem, web browsing was fast but I could not send messages through either my work email or through my Gmail account. Could this be related to the problem with sending attachments? Here is someone asking a similar question: Gmail, Windows Live Mail and Plusnet problems?

The problem appears so black-and-white I began to suspect that it must be a block at the ISP until I read this thread on plusnet's community forum: Mail cannot send attachments. The thread ends with an answer from a plusnet employee but the original problem from someone using Apple Mail (as I do) goes undiagnosed.

Eventually one of my smaller email messages managed to sneak out of my laptop at the Nth time of trying. Intermittent problems may be the worst to diagnose but at least this showed me that it is just a really bad connectivity problem.

I'm not alone

At this point I went back to my first diagnosis. I tried every channel, I powered off every other wireless device I could find (including the phones) and I still had the same trouble. This is beginning to look like a bug in the router. I checked the firmware version (8.2.7.8) and found a new thread that matched my symptoms: Thomson TG585V8 poor upload speed over wifi and then the more general: Wireless connectivity on the Thomson V8. The second of these has 13 pages of discussion and brings the problem right up to date: but with no resolution!

The solution

To recap, we have a router that is perfectly capable of sending (downloading) data over wifi at high speed but is very bad at receiving it during uploads. I started suspecting some type of buffer overflow or error in one of the protocol stacks but restricting it to b or b/g operation didn't fix the issue either. I then started looking at other tools and settings in the router and came upon "Web Browsing Interception". I have no idea what this means but it was set to automatic. I found one post on a DSL forum which was enough to raise suspicion: Web Browsing Interception?. I disabled it and applied the settings, almost immediately my email started going through as normal.

The same feature is cited in this thread relating to different Thomson hardware (which I found later): "Solved: Thomson Speedtouch Modem, disconnects often and slows down browsing".

So did this solve the problem with attachments? No. At least not directly. Turning this setting off stopped the router interfering with mail clients making outbound connections to Gmail and Microsoft mail products. But I was still getting larger attachments stuck at about the 100Kb mark. It may be that all I have done is free up enough resource (RAM or CPU) to send small messages by turning off a feature of the router software. In which case, it seems likely that a resource leak of some kind is to blame in these routers. To test the theory I powered the router on and off, waited ages for it to restart (it really is slow) and then tried again. Everything worked fine - all attachments sending without error, even large ones.

So is this Web Browsing Interception feature to blame? Possibly, the router has been powered on and off before without fixing the problem so it seems likely that this feature is either causing or exacerbating a resource leak in the unit.

2011-09-05

HP Photosmart: nice screen, shame about the firmware

In an earlier post to this blog I talked about my use of dd-wrt to help me get my home wifi signal to span my house.  See Open Source Routers to the Rescue.  Well, I have finally got fed up with some of the flakey behaviour from my Virgin router.  Periodically it crashes and I have to cycle the power on both my new HP Photosmart B110 and the old HP Officejet 6310 to re-enable printing.
 
To recap, dd-wrt is open source router firmware with a host of well-documented options to allow you control your router hardware.  In the end I found wireless repeating (extending the range of my virgin hub) too unreliable and so I used it to configure my second router as a "Client Bridge" instead.  This allowed me to connect devices without wireless support by plugging them into the LAN ports on the back of the second router.  Client bridge mode is not compatible with the use of DHCP to automatically assign IP addresses.  According to the dd-wrt site this is actually a restriction of the Wifi protocol itself so I configured my home network with manually assigned IP addresses for most devices.

This was easy to do on my the old Officejet printer which has a low-res calculator style LCD screen and a fax-style numeric key pad.  But on my new HP Photosmart B110 printer, which comes with a flashy colour LCD panel and an icon-based interface (no touch screen though) the network settings can only be set through the built in web browser, so it must already be connected to a network.  This seems a bit dumb but I guess most wifi networks will support DHCP so less of a problem in practice.

I now own a third router, I have been planning to take advantage of something called WDS which is the proper way of joining two wireless networks.  With WDS you can extend wifi coverage and bridge the physical LAN ports in a way that fully supports DHCP.  (It is a pity that my Virginmedia router does not support WDS on its own, but given that WDS is not a proper standard yet mixing and matching suppliers is probably unwise anyway.)

I had been putting off the chore of reconfiguring the network but what better way to spend a wet Sunday afternoon?  I now have a normal DHCP-based home network again.  The two connected routers mean I have coverage throughout the whole house and some of the garden.  At last, I've been able to turn off the wifi beacon on the Virgin router and relegated it to little more than the cable modem it replaced.

Reconnecting all the devices to the new network was simple, until I got to the Photomart printer.  The network transformation involved a change of subnet so the static IP was now useless.  I went back through the wireless wizard to join the printer to the new network but the old IP settings persisted.  I then hit the 'reset to factory defaults' option in the menus - restarted the printer and then ran through the wizard again.  The printer still remembered the old static IP.  I even plugged the printer into my Mac via a USB cable and ran the printer utility but there was no way to affect the network settings that I could find.  In the end, I went back to my box of old routers and dug out an old Netgear wireless access point which I was finally able to use to contact the printer and change its IP settings back to automatic.

An option to reset to factory defaults should surely do what it says for all settings?  Now all I need is something like dd-wrt for my Photosmart printer...




2011-07-11

Open Source Routers to the Rescue!

I spent a few happy hours this weekend fiddling with routers and stumbled across a great open source project called dd-wrt.  This one is not for the timid as there is a serious risk of bricking your router but if you are anything like me you have an old box gradually filling up with discarded routers you are keeping just in case you main router fails.

I recently switched tariffs with my broadband supplier, Virgin Media.  As a result, they replaced my cable modem with an all-in-one wireless-router/cable modem.  I can see that this simplifies their business for most customers but when you already had a good router before it is a pain when you realise that you are now tied to something with poorer range and and annoying tendency to make your printer panic.

Anyway, as a result I went and bought an ASUS device (RT-N12) capable of being used as a wireless repeater to improve coverage in those hard-to-reach corners of my small 3-bed semi.  Unfortunately, try as I might I could not get it to work as advertised.  At one point I actually got it to repeat the wifi signal from the Virgin router but the LAN ports were all on their own private network.  My attempts to fix the LAN ports broke wifi connectivity for everyone in the house and almost bricked the device.  I updated to the latest ASUS firmware but still no joy - I was beginning to get bored of the recovery mode procedure for restoring factory defaults.  There has to be a better way, surely?

Part of the problem is that the ASUS device has attempted to simplify the user interface of the router to an extreme making it very hard to fix issues.  The quality of the translation in the UI is very poor and the little help icon almost always brings up a little box with placeholder text explaining what the help function does, rather than actually providing any useful insight into the settings.  The one saving grace is that, with so few settings to control, one can quickly exhaust all possible combinations and conclude that home-networking is not for mere mortals.

But, masochists take note: there is even more fun you can have with these devices and you don't need to spend a penny more (the RT-N12 is available from £28 at 52 stores according to Google).

The software distributed by dd-wrt is a replacement firmware that actually works. Don't be scared off by the use of 'beta' or the frightening stories of bricked devices. I'm sure there is a reason why you are supposed to use the special ASUS firmware updating tool on Windows but I just flashed the firmware through Safari from my Mac and within a few minutes I was looking at a whole new user interface. This software is a breath of fresh air. It may be free but there is more documentation than the supplied firmware and being German the quality of the English is better than I could write myself.

The ASUS device clearly has software shortcomings but it isn't clear when linkingWifi devices which party is to blame. The market always seems to be getting ahead of the standards and even with the faster 802.11n mode it seems that devices can't agree which frequency to talk on and that in practice most networks are operating at b/g speeds for legacy reasons.

Routers like the Virgin hub are understandably configured for compatibility so most people seem to recommend turning off the wireless completely and then using one of the four LAN ports to plug in a completely separate wireless infrastructure to split new 'n' devices from the old b/g - now where is that box I keep all my old routers in...