The story
By analogy with the manner whereby a turtle's or tortoise's head gradually emerges from the shell, after having been kept inside for some time for defensive or resting purposes. When threatened (such as by contact), the head rapidly retreats into the shell, which might have further reinforced the vulgar analogy.
Etymology from Wiktionary, CC BY-SA 4.0.