Since 2012 Western intelligence services detected that at least three of the 13 high-ranking al Qaeda officials who had fled to Iran after the Taliban lost control of Afghanistan in late 2001, had left their sanctuary in Iran. One of them returned to what he thought was sanctuary in his native Libya and was seized by American commandoes in a 2013 raid. The others are showing up, briefly, in places where al Qaeda is operating but otherwise act like they are on the run. That is prudent, because the United States would very much like to capture or kill these guys. While not imprisoned while in Iran, the al Qaeda men were not allowed to move freely and most appeared to have been under house arrest.
The 2011 raid in Pakistan that killed Osama bin Laden also captured lots of documents that shed some light on what happened to al Qaeda after they were chased out of Afghanistan in 2001. In 2012 some of those documents were released that revealed what had long been suspected, al Qaeda and Iran did not get along, despite having a common enemy (the West). Al Qaeda is a radical Sunni organization that considers Shia Moslems heretics (nearly all Iranians are Shia). Iran has long provided sanctuary for al Qaeda but kept all or most of them under house arrest and observation. Iran made it no secret that they wanted bin Laden dead because al Qaeda had slaughtered over 100,000 Shia in the last two decades. In that period most of al Qaeda's victims had been Moslems, most of them Shia. But at the same time Iran appreciated the successful attacks al Qaeda made (or sponsored) in the West. This is something Iraq wanted but was reluctant to do itself as it feared Western retaliation.
Starting in 2008 Iranian president Mahmoud Ahmadinejad publically claimed that the September 11, 2001, attacks were a ploy by Israel or the CIA, to justify a war on Islam. Shortly after that assertion was first made public an al Qaeda leader, Ayman al Zawahri, rushed out an audio tape denouncing the Iranians for casting doubt about the fact that al Qaeda had planned and carried out those attacks. Although Shia Iran and Sunni al Qaeda occasionally cooperate, they are, in fact, bitter enemies. The bin Laden documents make this clear.
Normally the Shia avoid al Qaeda, which officially considers Shia heretics that should be converted (to the Sunni form of Islam) or killed if they refuse. But Iran has taken the position that “the enemy of my enemy is my friend” and provided sanctuary for al Qaeda leaders and encourages it allies to work, when possible, with Sunni terrorists like al Qaeda. The strategy is not popular with a lot of Iranians, although the Iranian government openly approved of the fact that senior al Qaeda leadership (including those outside Iran) had, since at least 2006, advised their subordinates to not kill Shia women and children. That advice has been frequently ignored but Iran has continued to work with al Qaeda when it suited Iranian interests.