Its origins are nautical.
Back in the early 1800s, the British did something called impressment. During the Napoleonic wars, the British considered any ship that traded with the French an enemy. They would steal the supplies and capture the crew. They impressed the crew into the navy for life. These guys would work as sailors for the rest of their lives and never step on dry land again. If they had a wife, the British would bring the wife aboard the ship. If the wife was pregnant, they would place her on the gun deck near the cannons. When she started having contractions, they would fire the cannons to make her push to have the baby. When the baby was born, it was called a son of a gun. This termis is very negative.
Where's your dad, you son of a gun.