The militants attacked Mohmand Rifles Headquarters in Ghalanai in Mohmand Agency, one of seven tribal districts, and reached the mosque, where residents and a large number of recruits had gathered for an early morning prayer.
The attackers were wearing suicide jackets and opened fire while attempting to enter the mosque.
"They were taken on and contained in the outer courtyard of mosque. Security forces surrounded the attackers and killed all of them," the army said in a statement.
"Security forces valiantly defeated suicide attack on Ghalani Camp in Mohmand agency killing all four suicide bombers," army spokesman Lt Gen Asim Saleem Bajwa tweeted.
More From This Section
He said two soldiers were also killed in the attack.
Tehreek-e-Taliban Pakistan's breakaway faction Jamaat-ul Ahrar claimed responsibility for the attack.
The group was designated as a terrorist entity by Pakistan's interior ministry early this month.
After the attack, district administration imposed curfew in Mohmand and started search operation for militants.
Mohmand was once a stronghold of militants but it has become largely peaceful due to repeated operation by the army.