It's pretty hard to definitively know where any type of slang originated, so it's no surprise that etymologists disagree over how "son of a gun" came to be. It could be as simple as a milder take on "son of a bitch," which has been said for centuries in reference to fatherless children. The phrase can be used in a number of situations appropriately, whether out of anger, joy or bewilderment ("Son of a gun, that old Model-T still starts after all these years!")
Another possible origin is that it actually means "son of a military man." The British Navy, in particular, allowed women (wives, prostitutes, what have you) on sailing vessels, and as a result, children were occasionally born on board. So, on the birth certificate the child's father (if paternity was uncertain) would be listed as "son of a gun," translated to "son of a military man." Even if the baby was a girl. Go figure.