Origin: The word has its origins in the 16th century. In order to protect medieval castles, builders built narrow windows, high above the ground, that appeared as narrow slits on the exterior, but widened inward to create enough space for an archer. Theses windows were called loopholes, from the late Middle English loupe meaning noose or loop. Some of these can be seen during battle sequences in HBO’s Game of Thrones. The archers in the loopholes have the strategic advantage — they can shoot their arrows at their enemies down below; while most of the invaders’ arrows bounce off the castle walls, unable to fly through the narrow slits. For more than a hundred years, archers and loopholes were effective defenses; however, by the 17th century gunpowder made archery — and hence loopholes — obsolete. After that, the word took on a slightly different meaning: loophole came to mean a narrow escape. Over time the word evolved to represent a clever way out of a legal situation as its primary usage.
For further reading: Word and Phrase Origins by Robert Hendrickson, Facts on File (2008)