Police and witnesses said the car bomb caused a huge explosion which allowed the gunmen to force their way into the fortified building.
Ambulance officials said at least 15 people were killed and 20 wounded in the attack.
Six Shebab gunmen were also killed, with two of those blowing themselves up, internal security ministry spokesman Mohamed Yusuf Osman said.
Abdukadir Abdirahman Adan, head of Mogadishu's Ambulance Services, told reporters his crews had taken about 15 dead bodies and 20 wounded civilians to hospital.
More From This Section
"The security forces and AU peacekeepers shot and killed four of the attackers, while the other two blew up themselves," Osman told reporters.
Witness Idil Malim said bodies of those killed and wounded lay around the complex.
"There were several people lying dead at the scene," he said.
Shebab spokesman Abdulaziz Abu Musab claimed responsibility, boasting that their gunmen had been in "fully in control" of the ministry, as well as entering a neighbouring building housing the oil ministry.
The Shebab rebels stage regular attacks in the capital as part of their fight against the country's internationally-backed government and African Union forces supporting it.
A car bombing to force entry into fortified buildings followed by an armed raid has become a trademark tactic of the hard line Islamists.
Somalia has been unstable since the collapse of Siad Barre's hardline regime in 1991, and the country's new government is being supported by a 22,000-strong African Union force that includes troops from Burundi, Djibouti, Ethiopia, Kenya and Uganda.