This paper proposes a methodology to develop countermeasures against code injection attacks, and validates the methodology by working out a specific countermeasure. This methodology is based on modeling the execution environment of a program. Such a model is then used to build countermeasures. The paper justifies the need for a more structured approach to protect programs against code injection attacks: we examine advanced techniques for injecting code into C and C++ programs and we discuss state-ofthe-art (often ad hoc) approaches that typically protect singular memory locations. We validate our methodology by building countermeasures that prevent attacks by protecting a broad variety of memory locations that may be used by attackers to perform code injections. The paper evaluates our approach and discusses ongoing and future work.