The Islamist militant group Al-Shabaab is responsible for the attack in the center of Mogadishu, group spokesman Abu Musab said.
The attack began when two suicide bombers detonated their car at the entrance of the two-story building housing the Ministry of Education, Culture & Higher Education, Somali National Security Ministry spokesman Mohamed Yusuf said.
Five gunmen then entered the building, shooting people inside, Yusuf said.
Security guards at the building, and, later, Somali special forces battled the gunmen inside, witnesses said.
Soldiers from the African Union, who are in Somalia in part to support the government's fight against Al-Shabaab, teamed up with Somali security forces to shoot and kill the five attackers, Yusuf said.
The attack killed four Somali soldiers and eight civilians, according to Yusuf.
The special forces helped people out of the building while the attack was underway, city police Capt. Mohamud Abdi said. Ali Hassan, a man who was helped from the building, confirmed that a rescue operation was happening inside.
Somalia-based Al-Shabaab has battled the country's government for years, aiming to overthrow it and turn the nation into a fundamentalist Islamic state. In recent years, the group also launched terror attacks beyond Somalia's borders, sometimes targeting non-Muslims.
Earlier this month, Al-Shabaab gunmen stormed Garissa University College in neighboring Kenya, killing 147 people, mostly students
. The terrorists separated Christians from Muslims and shot those who couldn't recite verses from the Quran, witnesses said.
In Somalia, Al-Shabaab has been blamed for attacks that have killed international aid workers, journalists, civilian leaders and African Union peacekeepers.
Late last month, Al-Shabaab militants detonated a bomb and sprayed bullets at a Mogadishu hotel, leaving at least 20 people dead
in an attack that lasted a number of hours. Among those killed was Yusuf Mohamed Ismail Bari-Bari, Somalia's permanent representative to the United Nations in Geneva, Switzerland.