Dogs kick their back legs when being rubbed and tickled because of an involuntary reaction called the scratch reflex. It is caused by nerves in the dog's stomach reacting to the tickling in an effort to get rid of an irritation.
When these nerves, which are connected to the dog's spinal cord, are activated, a message is relayed from the brain to the legs. The legs involuntarily kick to try and get rid of the irritation. Many dogs enjoy having tummy rubs, and they are not actually irritated. The reflex is reliable enough that veterinarians sometimes use it to help diagnose neurological problems or nerve damage.