There is no defense against terrorism, but there is a viable policy to deal with it. Problem is, it's a hot potato: no one really wants to adopt it, because it looks weak and it costs a lot. That policy is to stop attacking countries that don't espouse Western values, and leave them to evolve in their own way at their own rate. That policy is to invest the billions that the US is now spending on arms, to instead provide those countries with humanitarian aid -- money and supplies for education, infrastructure-building, medicines, and civilian technologies and training in how to use them. No strings attached except that we need to be able to audit to ensure the money and technologies are used for their intended purposes. Nothing to be paid back. In fact, for countries whose foreign debt to us is crushing them, making them economic slaves to us, we need to write that debt off. Goodwill is the only dividend we need.
If we did this, there would be nothing for terrorists to react to. And while there will always be a few deranged minds in the world who will blow up government buildings and commit other dreadful acts, and while under the auspices of the UN we may still need to intervene together to deal with leaders who inflict genocide or other massive cruelty on their own people or their neighbours, for the most part such a policy of incessant investment in nation-building will inevitably produce a world that is more peaceful, less harsh, and yes, safer and more secure for all of us than the one we live in today.