Yes its legal
They connect to a network in the same way as any oth
Mobile phones are massively subsidised by the networks on the assumption that they will recoup their money from you network usage. For example, a top of the range mobile at retail could easily cost 600 quid or more, but you get it for say 19.99.
If you want to use it on someone else's network, then the original supplier will expect you to pay them back some of the subsidy. To encourage you to do this they "Lock" the phone to their network. The easiest way (but probably not the cheapest) to unlock your phone is to ring your service provider and ask to have it unlocked.