NAIROBI, Kenya — The plot was hatched weeks or months ago on Somali soil, by the Shabab’s “external operations arm,” officials say. A team of English-speaking foreign fighters was carefully selected, along with a target: Nairobi’s gleaming Westgate mall.

The building’s blueprints were studied, down to the ventilation ducts. The attack was rehearsed and the team dispatched, slipping undetected through Kenya’s porous borders, often patrolled by underpaid — and deeply corrupt — border guards.

A day or two before the attack, powerful belt-fed machine guns were secretly stashed in a shop in the mall with the help of a colluding employee, officials say. At least one militant had even packed a change of clothes so he could slip out with fleeing civilians after the killings were done.