Thursday 21 June 2012

How Can Companies Be Expected to Keep Communication Information Secure?

The British government is trying to push through legislation called the "Communications Bill" that will force Internet Service Providers (ISPs) to record and store all the point-to-point information for all their users. For example, the dates and times of all the emails a user sent or received and who they were delivered to or from. They are not at this stage asking for the content of the communication to be stored, just the when and who parts.

It's not just emails either, it's all Internet communication, e.g. social networking sites like Facebook and Twitter, voice calls over the Internet like Skype and MSN, webmail services like GMail and Hotmail, Gaming services, etc. It will cost industry billions of pounds to implement.

Advocates of the bill insist the information would only be used by appropriately vetted agencies (e.g. the police or security services) and even then, only after a court order. But I'm not so sure. If a publicly listed company like LinkedIn cannot keep its own customers' passwords secure, and this from a company whose very existence depends on the trust of its users, then what chance is there that communications data held by all ISPs will remain hidden from prying eyes?

LinkedIn's security failed because it didn't follow industry best practices and became susceptible to a dictionary attack. This type of attack has been known about for decades and works because, although the passwords are encrypted, there's nothing stopping an attacker who has access to them from encrypting all known, or at least common, passwords and comparing this to the ones in the database.

An easy way to make this type of attack harder is to use a method called salting. This stores a random value along with the encrypted password. When the user needs to authenticate with the system both the password and the salt are encrypted together and only if this value matches the stored value is the user permitted access. An attacker now has to encrypt every possible password for every user, as each user will have a different salt. In most circumstances this makes a dictionary attack infeasible.

LinkedIn's security breach is by no means a one off. There have been thousands of other similar failings in security in companies of all sizes. Sony's PlayStation network faced similar problems in 2011 when the personal information for 77 million users was stolen. The Wired Equivalent Privacy (WEP) standard used in 802.11b WiFi technology to secure communications has been broken and the key for any network using this outdated standard can now be recovered in just a few minutes. The Content Scramble System (CSS) used to encrypt DVDs only uses a 40-bit encryption key and has been comprehensively broken. Even the Advanced Encryption Standard (AES) which went through rigorous peer review, offered 256-bit key sizes and is a worldwide standard has been broken (admittedly only theoretically).

These are examples of just a few high-profile services and standards that are used the world over. There are a huge number of other broken standards that I could have mentioned here. The point is, if these systems were broken so soon after they came into widespread use, what hope do private small to medium, or even publicly large, enterprises have of keeping their users' communication history secret just in case a government agency wants to invade our civil liberties and see who we have been communicating with? If this bill comes into law, attackers will know all ISPs must keep this data, so will develop ever more sophisticated techniques to seize this information.

Tuesday 13 March 2012

Getting your iPad To Work on the giffgaff Network

If you have an iPad with 3G you may be tempted to give the giffgaff network a try. They are a SIM only network provider running on the O2 network in the UK and they offer significant savings over other airtime providers.

If you have not already ordered a SIM then please do so via my affiliate link giffgaff.com/orders/affiliate/anturgyffrous and you'll get £5 of credit free and I'll receive points for spreading the word!.

The first thing to note is they do not provide micro SIMs, which the iPad (and iPhone 4/4S) need. However, the normal size SIMs do work in these devices, you've just got to cut them to size in order for them to work. Guides with templates for doing this can be found by searching the Internet, but if you'd prefer not have to do this you can order a pre-cut micro SIM from www.giffgaffmicrosim.co.uk

The next thing you'll need to do is enter different settings into the Mobile Data page. On your iPad go to Settings, then Mobile Data, then APN Settings and enter the following details:

APN:giffgaff.com
Username:giffgaff
Password:password

If, after upgrading iOS on your iPad, or after resetting it you are unable to browse the Internet on 3G and instead receive a 'Mobile Data Plan Usage' message stating that 'There is no data remaining on your current plan' and asking 'Would you like to extend your data plan now? If you don't do so now, you can do it later in Settings' then simple go back into APN Settings page of Mobile Data on your iPad as explained above.

Sunday 1 May 2011

What Is AV And Why Do We Need It?

AV stands for the Alternative Vote and is a voting system where the electorate, that's you, can rank the candidates in order of preference, rather than only being able to express your opinion about one person. On 5th May 2011 the British public are being asked in a referendum to vote if they want to change to this new AV system.

In the United Kingdom we currently elect our politicians using a voting system called First Past the Post, this is where all the votes are counted up and the candidate with the most wins. Sounds simple, but it does have one important drawback. And that is that a candidate can win even though the majority of the votes were not for them.

Let me explain how, for simplicity I'll use rounded numbers. Let's assume 4 candidates received the following number of votes, 7,000 to the blue party, 6,000 to the red party, 4,000 to the yellow party and 3,000 to the green party. That's 20,000 votes in total, but only 35% of them were for the candidate with the most votes, the one for the blue party. In other words, the majority of the voters, 65%, voted against the blue party. Yet, in the First Past the Post system, the blue party candidate would have been declared the winner.

In the 2010 general election the conservative party won the most seats. However, when you add up all the individual votes cast by everyone across the entire country, nearly 64% of the electorate voted for a different party. The Alternative Vote is the first step in attempting to redress the balance.

It works by asking you to rank the candidates in order of preference. So if, for example, you liked the red party the most, then the yellow party, then blue and finally green, you'd vote by putting a number 1 next to the red party candidate, a 2 next to the yellow party, a 3 for the blues and a 4 for the greens.

It does not, as some people have claimed, mean you get several votes. You can still only vote once, but instead you get to list the candidates in the order in which you like them. If you only like one party and have no preference in order for the other parties, you can of course choose to just put a number 1 next to your favourite candidate and ignore the rest.

The way that it works when deciding who the winner is, is by counting up everyone's first preference. If the candidate with the most votes has less than 50% of all the votes then the candidate with the fewest votes is eliminated and the second preference for everyone who voted for that candidate is counted and added to the ballot, this continues until someone has at least 50% of the vote, or there are no preferences left.

In the example I provided earlier, the green party would be the first one eliminated. Then, all the voting cards for the people who put the green party in the first position would be collected and re-counted using their second preference. If we assume 2,000 second preferences were for the yellows and 1,000 for the reds, the votes would now be distributed thus: 7,000 to both the blues and reds and 6,000 to the yellows.

We still wouldn't have a majority, so the yellow party, the one now with the least number of votes would be eliminated, all the voting cards where the yellows were first or second preference would be collected and re-counted, but this time choosing the third preference. Let's say 1,000 chose the blue party and the rest red, the red party candidate would have 60% of the vote and would be declared the winner.

Why is this fairer than the First Past the Post system? Well, in the example above the majority of the electorate prefer the winning candidate to the runner up, only 40% like the second candidate more. Therefore, the winner can truly say they stand for the majority. Remember, you wouldn't have to work any of that out, that would be done by the counters, all you'd have to do is put the candidates in order from most to least favourable.

Changing our election system will incur a small cost, most of which will actually be in running the referendum, money we wouldn't get back regardless of the outcome. Nevertheless, this is something a few have objected to. Let me put this cost in perspective, our nation spends more on defence each week running military campaigns like those attempting to bring democracy to Afghanistan, Iraq and Libya, than the total one off cost of switching to AV, that's one week of defence spending versus a lifetime of electoral reform! So it really is a very small price to pay to make our electoral system more fair and democratic.


References:

  1. AV referendum: Everything you need to know | Politics | guardian.co.uk
  2. BBC NEWS | Election 2010 | Results | United Kingdom - National Results
  3. Instant-runoff voting - Wikipedia, the free encyclopedia
  4. Yes to fairer votes - Yes to AV - Alternative Vote
  5. NO to AV » Against the Alternative Vote
  6. How much will AV cost? | Full Fact
  7. Ministry of Defence | About Defence | Organisation | Key Facts about Defence | Defence Spending

Monday 21 March 2011

Creating a COM Visible C# Component

If you want to expose a C# Class to COM you'll need to use the System.Runtime.InteropServices namespace. Then you need to create an interface and implement this interface in your class. Next add attributes to your interface and class to inform the compiler these should be exposed and finally, you set the properties of your component to make the assembly COM visible and register for COM interop on output.

In more detail, first add the following line to the top of your class to include the InteropServices namespace:

using System.Runtime.InteropServices;

All COM components need a globally unique identifier (a GUID) in order to be registered and used. Visual Studio can create a GUID for you. Click the Create GUID item in the Tools menu and select the fifth option which will format the line exactly as it's required for COM Interop.

Create GUID Dialog Box

Then hit the Copy button and paste the GUID into your code file below the namespace declaration but before the class declaration. Below that you need to create the interface for your component.

[Guid("5715C11C-55E8-45B4-9372-FD0FD9AA6F7C")] public interface IMyComponent { void Initialise(double version); int Add(int num1, int num2); double Version { get; set; } }

Now you need to create a new GUID for your actual class which will implement the interface. This is done in exactly the same way as you did for the interface, if the Create GUID dialog box is still open ensure you click the New GUID button in order to create a unique GUID. You mustn't use the same GUID.

Add the line just before your class declaration. This time however, you need to add extra information to the attribute. You must add a ClassInterface of None, and a ComSourceInterface that points back to your interface. Here is an example of what it should look like:

[Guid("92D467E4-F6B7-4B88-8B87-00CF78794852"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(IMyComponent))] public class MyComponent

Finally, as far as code is concerned, you need to implement the interface. Here is a complete code listing of an example COM exposed class:

using System.Runtime.InteropServices; namespace MyComComponent { [Guid("5715C11C-55E8-45B4-9372-FD0FD9AA6F7C")] public interface IMyComponent { void Initialise(double version); int Add(int num1, int num2); double Version { get; set; } } [Guid("92D467E4-F6B7-4B88-8B87-00CF78794852"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(IMyComponent))] public class MyComponent : IMyComponent { public double Version { get; set; } public void Initialise(double version) { this.Version = version; } public int Add(int num1, int num2) { return num1 + num2; } } }

Now you need to actually mark the assembly as COM visible. To do this, open the project's properties and under the Application tab click the Assembly Information... button, then tick the Make assembly COM-Visible checkbox.

Assembly Information DIalog Box

Visual Studio can automatically register the type library for you after compiling the component. In order to enable this option, open the Build tab of the project's properties and tick the Register for COM interop check box.

Project properties build tab showing the Register for COM interop option checked.

If you don't want Visual Studio to automatically register for COM interop, you'll need to use the regasm command to create a COM compatible type library. To do this, open the Visual Studio Command Prompt, type in regasm followed by the full path to your dll (if you're not already in the correct folder) and then add /tlb to the end. You should see a message stating the types were registered successfully.

Visual Studio Command Prompt shown registering the assembly for COM Interop using the regasm command.

Finally, if your assembly contains multiple interfaces and classes, you can hide the ones you don't want to expose via COM. To do this simply specify false in the ComVisible attribute before the class or interface declaration.

[ComVisible(false)] public class HiddenClass

And that's it. An entire guide to creating a C# COM component. Your component will now be immortalised as one of the wonders of the universe and will be visible from space*.


* Assuming your spaceship has a link to a Windows PC with your component installed on it.

Sunday 13 June 2010

Butterfly Cakes

Some of my friends ran in the Race for Life today, raising money for Cancer Research UK. I made some butterfly cakes for them as a well deserved treat. These are pretty cup cakes with the middle dug out, cut in half and stuck back on top, resembling wings. They are really easy to make, and take very little time, if you want to have a go, and I really would recommend it, then here's what you need to do.

Butterfly CakeCake mixture is one of the simplest things, you only need to remember what the ingredients are, not the amounts or proportions. These ingredients are eggs, butter, sugar and flour. All you do is weigh the eggs before you crack them, then use that as the measure for all the other ingredients. So assuming 3 eggs weigh 170g (6oz) then you'll need 170g (6oz) of butter, sugar and flour.

So without further ado, here's how to make 12 yummy muffin sized butterfly cakes. All my measurements are based on 3 large eggs weighing 170g (6oz), if you are using a different size of egg, or your eggs weigh a little differently then adjust your measurements to suit how much your eggs weigh.

For the cake mixture:
170g (6oz) softened butter (unsalted)
170g (6oz) caster sugar
3 large eggs, lightly beaten
170g (6oz) self raising flour
1 teaspoon of baking powder
2 dessertspoons of milk
1 dessertspoon of vegetable or olive oil
1 teaspoon of vanilla extract

For the icing:
85g (3oz) softened butter (unsalted)
200g (7oz) icing sugar
1 teaspoon of vanilla extract
1 teaspoon of milk

First of all, it's really important for the butter to be very soft, you should be able to push a knife through it flat side down. If you keep your butter in the fridge then you’ll need to take it out the night before and let it soften naturally. You can use margarine instead if you prefer, but I find butter tastes better. Margarine should still be very soft though, so remove it from the fridge at least half an hour before you begin.

Pre-heat the oven to gas mark 4, 180oC, 350oF or 160oC for fan assisted ovens.

Start by whisking the butter, an electric whisk will really help here. Then add the sugar and keep whisking until it's fluffy and pale. Now add the beaten eggs a little at a time, continuously mixing after each addition. Once you've added all the egg, mix in the vanilla extract.

Hold a sieve high above the mixing bowl (at least 15cm, 6 inches) and add half of the flour, but don't whisk it. Instead use a wooden spoon to fold the mixture in on itself, combining all of the flour.

A very important ingredient of cakes is air, that's what all that whisking and sieving was doing, adding air. Folding the mixture rather than whisking it keeps the air in and makes wonderfully fluffy, spongy cakes.

Finally, add the milk, oil, baking powder and sift in the remaining flour. Keep folding the mixture in on itself using the wooden spoon until you've got a smooth, consistent mixture.

Place a dozen muffin cake cases into the holes in a muffin cake tin and spoon in the mixture (a second spoon will help push the mixture off the spoon into the cup). Don't overfill them, they'll rise in the oven to about twice the size!

Now place them on the middle shelf in the oven, close the door and wait 20-25 minutes. Whatever you do, don't open the oven door before this. If you do then the hot air will rush out of the oven and you're cakes will not rise properly and won't taste wonderfully fluffy. A timer will help you a lot here.

While they're cooking, you can make the icing. Whisk the butter to ensure it's really soft, then gradually sift in the icing sugar while you continue to whisk. Now add the vanilla extract and milk and keep whisking until the mixture has a fluffy consistency, adding more milk if necessary.

Once 20-25 minutes have passed you'll need to check your cakes are cooked properly, do this by gently pressing a finger in the middle of one them, if it bounces back without leaving an impression, then it's cooked. If not then give them another 5 minutes in the oven.

After they're cooked, remove them from their tin and let them cool for about half an hour. Then using a knife cut a diamond shape into the top of each cake. Dig out the centre of the cake and generously fill it with icing. Turn your diamond shape of cake upside down on the work surface and cut in two along the longest points to make the wings and then stick these either side of the centre of the cake using the icing as glue.

To make them extra special sprinkle some icing sugar on top to give them a frosting. The hardest part now will be sharing them.

If you only have a cup cake tin handy, and not a muffin tin, then you can still make wonderful butterfly cakes, just use 2 eggs (and 110g of butter, sugar and flour) for the cakes, reduce the cooking time to 15-20 minutes and use 55g butter and 130g icing sugar for the icing.

Tuesday 11 May 2010

Why Did It Take So Long For The Winner Of The Election To Become The Prime Minister?

We have just heard that David Cameron, leader of the Conservative party, has this evening become the next Prime Minister of Great Britain. But the election was held 5 days ago and his party had the greatest number of elected Members of Parliament, and the most number of votes cast in its favour. So why has it taken so long for him to be declared as Gordon Brown's successor?

In Britain we have a system that elects local candidates, not a US style presidential system. Each winning candidate in every constituency takes one of 650 seats in the House of Commons. Each individual in this lower chamber represents their people back in their local constituency. If more than 50% of these seats are held by one political party then that party is said to represent the majority of the people and is thus entitled to choose its leader as the Prime Minister.

And therein lies the problem. David Cameron's Conservative party only holds 306 seats, 20 short of a majority (disregarding the fact the Sinn Fein MP's won't take their seats and the one ward, Thirsk & Malton, which hasn't yet elected an MP due to the death of a candidate). This means that the Conservative party cannot be said to represent the people.

This principle of a majority government is deeply enshrined in British democracy. Each bill, or law, that the government proposes is voted on by every MP. If less than half of the MP's vote in favour of the legislation then it is not passed and the law doesn't change. And it is exactly for this reason that minority governments are so ineffective.

Mr. Cameron had only one option if he wanted to form an effective, decisive government that represented the people, and that was to discuss with the leaders of other parties the possibilities of forming a coalition, thus making up the number of seats needed to form a majority. The most obvious choice was the Liberal Democrat party. If you combine both their seats together, they would have 363 seats, a comfortable majority of 37 seats.

So what's the problem, why wasn't that done last Friday? Well; the Tories and the Lib Dems have core values, policies, ways of doing things, which are completely opposed. For example, the Conservative party wants to raise the Inheritance Tax threshold to £1 million, this would only benefit people set to inherit between £325,000 and one million pounds, in other words, some of the richest people in our society. The Liberal Democrats on the other hand wanted to raise the threshold at which basic rate tax is paid to £10,000, which would benefit everyone earning over £6,475, some of the poorest people in our society.

Just these two manifesto pledges demonstrate how different the parties are. The Tories represent the values to the right of centre and the Lib Dems to the left. And although it may look as if the people haven't decisively voted in favour of any particular party, they have decisively voted for a neither right wing, nor a left wing government. A Lib Dem/Tory pact would represent exactly this.

What has been happening over the past few days is that Nick Clegg, the leader of the Liberal Democrats, has been talking with David Cameron trying to find concessions that both parties can agree on. As part of this process Mr. Clegg has also been in talks with the Labour party. Not with any real expectation that they could work with them to form a government, but to prove to the electorate that they considered every avenue.

The debates were no doubt heated, and certainly went on well into the night. Bear in mind that any deal is not just up to the leaders of the parties, but of their MP's and senior party members. One of the biggest concessions the Liberal Democrats wanted was a referendum on electoral reform, and this is exactly what many Tory members very much didn't want. There were also many Lib Dem members that felt a deal with the Conservatives was impossible as it went against what the two parties believed in.

But finally, after several days a deal has been struck. David Cameron will be the 12th Prime Minister since our Queen's coronation, Gordon Brown has resigned, not only as PM, but also as the leader of the Labour party. It has also been rumoured that Nick Clegg will be offered the post of deputy PM and that George Osborne will step aside and let Ken Clarke take the post of Chancellor of the Exchequer with the Liberal Democrat's Vince Cable as his deputy.

Tuesday 17 March 2009

Creating a Custom Collection Object

Have you ever tried to create an object in VB6 that acts like a collection? If you have, you will certainly have come up against some stumbling blocks along the way. You may well have used some rather nasty hacks to get it to work, or worse still, given up altogether and just used a plain old vanilla Collection object.

In this post I shall show you how to get around these pitfalls, including assigning a default procedure and creating an enumerator for use in For Each...Next loops. We shall follow a set of simple examples to create an object that is a collection of integers. You will be able to build upon the things you learn here to create your own objects that act like collections.

First, let's look at the VB6 Collection object. There are four actions associated with it, namely Add, Count, Item and Remove. However there's something special about the Item function.

If we look at the members of the Collection in the Object Browser we can see that the Item function is shown with a turquoise dot. This simply means that it is the default member of any Collection object. What this means is, you do not need to explicitly call the Item function to return one of the items from the Collection object. A simple code example will help demonstrate this:

Dim myColl As Collection ' Instantiate the Collection object ' and populate it with some test data. Set myColl = New Collection myColl.Add 1 myColl.Add 2 myColl.Add 3 ' The following two lines of code are functionally ' equivalent even though the second line does not ' explicitly call the .Item function: Debug.Print myColl.Item(2) Debug.Print myColl(2)

Now how do we go about implementing this behaviour in VB6 with our own object? In .NET it is easy, we simple include the word Default in the routines definition. However, this does not work in VB6. Instead we have to use the Procedure Attributes dialog box. We will come to this in a moment.

In the mean time let's create the outline of our Integer Collection object which we will be using to build upon throughout the remainder of this post. Start by adding a new Class Module to your VB6 project, call it IntegerCollection and add the following code to the code file:

Option Explicit Dim m_colIntegers As Collection Private Sub Class_Initialize() Set m_colIntegers = New Collection End Sub Public Sub Add(ByVal Item As Long) m_colIntegers.Add Item End Sub Public Property Get Count() As Long Count = m_colIntegers.Count End Property Public Property Get Item(ByVal Index As Long) As Long Item = m_colIntegers(Index) End Property Public Sub Remove(ByVal Index As Long) m_colIntegers.Remove Index End Sub Private Sub Class_Terminate() Set m_colIntegers = Nothing End Sub

We now need to make the Item property the default property, as currently if we try and implicitly access it we will, at best get a run-time error, and at worst our project won't even compile. To do this select the "Procedure Attributes..." menu item from the "Tools" menu. The dialog box that is displayed allows us to enter a description and context sensitive help to each procedure. You can add information here if you want, but what we are really interested in is currently hidden.

Click the "Advanced >>" button to display the extra options. Make sure the Item property is the currently selected procedure from the "Name" drop down at the top. You should see that the "Procedure ID" drop down (on the left hand side, about half way down the dialog box) currently says "(None)", change this to say "(Default)" then click the "OK" button to apply your changes.

Our collection object now acts just like the built in Collection object in VB6 in the sense that we do not need to explicitly call the Item property, it will be implicitly called when we include the index of the item we want in brackets. Also, it is strongly typed, meaning we can only use it to store variables of type Long. If we try and pass anything else we will get a type mismatch error. This of course means that if we get passed an object of this type, we can be sure that every item in the collection is an integer. We no longer need to worry about checking the types as Variants are no longer allowed.

So we have done it! Well, not exactly. I said that our collection acted just like the built in Collection, however there's one important difference. That difference is the For Each...Next loop. If we try and iterate through each of the items in our collection with one of these loops we will be told that our object does not support this property or method.

The reason for this is that the For Each...Next loop works by calling a hidden enumerator that returns the next item in the collection. This enumerator is of type IUnknown, one of the main building blocks of COM Interoperability. (Well actually it's of type IEnumVariant and VB6 hides the implementation details of returning the item from the collection, but we won't go into that here.)

The collection object we are using to store our integers implements this enumerator as _NewEnum. Because it starts with an underscore we have to wrap our call to it in square brackets. We can then return this as our own enumerator. Add the following code to the IntegerCollection class:

Public Property Get NewEnum() As IUnknown Set NewEnum = m_colIntegers.[_NewEnum] End Property

However, we are not done yet. We now need to tell Visual Basic that this new procedure is our enumerator. This is harder than it first may seem. As unlike the Default procedure ID there is no corresponding item for the collection enumerator in the Procedure Attributes dialog box.

All is not lost though. It's just that VB doesn't include the enumerator procedure ID. I have no idea why this is, I can only assume it is because of short sightedness on the part of the VB developers. The procedure ID we are looking for corresponds to the constant FFFFFFFC, in VB this evaluates to -4.

Therefore all we need to do is go back into the "Procedure Attributes" dialog box, select the NewEnum routine from the drop down, click "Advanced >>", delete what's in the "Procedure ID" drop down and enter -4. At this point we should also tick the "Hide this member" check box so that it is not shown in the IntelliSense dropdown for our object when accessed via COM. This creates a consistent interface for our users.

Now our object truly represents a collection. It is strongly typed, has a default routine and can work in For Each...Next loops. Here is an example of how it could be implemented:

Dim myColl As IntegerCollection Dim value As Variant ' Instantiate our collection object. Set myColl = New IntegerCollection ' Add some values to it. myColl.Add 1 myColl.Add 2 myColl.Add 3 ' We do not need to explicitly call .Item ' to return a value from our collection. Debug.Print myColl(2) ' And we can cycle through all the values ' in it using a For Each...Next loop. For Each value In myColl Debug.Print value Next

I hope you've enjoyed reading this guide and that it has helped and informed you. If you have any comments or questions please get in touch by leaving a comment below. Feel free to link to this article from your own web site or pass on the address of my blog to your colleagues and friends.


References:

  1. vbVision -- Replace the Visual Basic Collections Object!
  2. How To Use the Procedure Attributes Dialog Box
  3. Paul Lomax's Top 15 VB Tips and Tricks