Militants disguised as police and armed with bombs and guns attacked a prison in northwest Pakistan holding 40 high-profile inmates on Monday night in an apparent attempt to free their colleagues, officials said.

The attack in the town of Dera Ismail Khan began around midnight with a huge explosion, said intelligence officials. The militants then detonated a series of smaller bombs to destroy the prison’s boundary wall.

At least eight attackers wearing police uniforms stormed inside the prison once the walls fell, said the officials. Security forces engaged the attackers, who were chanting “God is great” and “Long live the Taliban.”

“We are trying to bring the situation under control,” said Dera Ismail Khan police chief Sohail Khalid. “The attack is still continuing.”

“We are not sure if any of them escaped,” Mr. Abbas said.

Authorities received a letter threatening an attack on the prison, but they didn’t expect it so soon, said Mr. Abbas. Army troops encircled the prison and exchanged fire with the attackers, he said, but security forces were having trouble distinguishing the militants in the dark because of their police uniforms.

One prison official, Gul Mohammad, said he had just walked out of the prison at the end of his shift when two militants armed with AK-47s shot him. There are other officials who have been wounded, he said from a hospital bed, although the casualty toll was unclear.