Originally, the word meant an arrowslit, a narrow vertical window in a wall through which an archer (or, later, gunman) could shoot.
Located in the sally port, a loophole was considered a last ditch defense, where guards could close off the inner and outer doors trapping enemy soldiers and using small arms fire through the slits.
[1] Legal loopholes are distinct from lacunae, although the two terms are often used interchangeably.
A lacuna, on the other hand, is a situation in which no law exists in the first place to address that particular issue.
Loopholes are searched for and used strategically in a variety of circumstances, including elections, politics, taxes, the criminal justice system, or in breaches of security.