AMMAN, Dec 18 (Reuters) - Jordanian security forces freed tourists trapped inside a medieval castle on Sunday after storming the building where armed men had taken shelter following a shoot-out with police that killed at least nine people, security sources said.

A Canadian woman, three other civilians and five police officers were among the nine killed during the exchange of gunfire between the assailants and security forces. At least 29 people were taken to hospital, some with serious injuries, the sources said.

Police in the mountainous city of Karak had earlier freed 10 people, including foreign tourists, but some were still being held in the Crusader-era castle from where the gunmen shot at security forces who were surrounding it, a security source said.

The identity of the assailants was not immediately clear.

A former government minister from Karak city, Sameeh Maaytah, said there were signs Islamist militants may have been behind the attack but the government has so far steered away from saying this.

“The operation is continuing, it has not ended and the criminals are still inside the castle ... This was a group that was plotting certain operations inside Jordan,” Maaytah told pan-Arab news channel al-Hadath.

Video footage on social media showed security forces taking groups of young Asian tourists up the castle’s steep steps to its main entrance as gunshots were heard overhead.

The castle is one of the country’s most popular tourist attractions.

Prime Minister Hani al Mulki told parliament “a number of security personnel” had been killed and that security forces were laying siege to the castle. The Canadian government confirmed one of its nationals had been killed.

Police and witnesses said gunmen had earlier gone on a shooting spree aimed at officers patrolling the town before entering the castle, perched on top of a hill. They used one of the castle’s towers to fire at a nearby police station.

Police said the gunmen had arrived from the desert town of Qatraneh nearly 30 km northeast of Karak city, a desert outpost known for smuggling, where many tribal residents are heavily armed.

They had fled to Karak after an exchange of fire with the police at a residential building, security forces said.

Jordan is one of the few Arab states that have taken part in a U.S.-led air campaign against Islamic State militants holding territory in Syria. But many Jordanians oppose their country’s involvement, saying it has led to the killing of fellow Muslims and raised security threats inside Jordan.

Officials worry about radical Islam’s growing profile in Jordan and support in impoverished areas for militant groups.