Iran won their first match at a World Cup finals since 1998 as Morocco substitute Aziz Bouhaddouz scored an own goal in injury time.
Bouhaddouz put the ball into his own net with a diving header at the near post in the 95th minute as Morocco defended a left-wing free-kick.
The result was harsh on the African side, who had wasted numerous chances in the first half and were denied late on when Iran goalkeeper Alireza Beiranvand produced a fine save from Hakim Ziyech.
But Iran took the victory, only their second in World Cup history after a 2-1 win over the United States at France 1998.
Morocco became the second African side to concede a late winning goal in the World Cup on Friday, after Egypt lost 1-0 to Uruguay in Group A, thanks to a last-minute header from Jose Gimenez.
Both Morocco and Iran impressed in qualifying with Morocco only conceding one goal in their eight games, while Iran remained unbeaten and only let in five goals in their 18 qualifying matches.
However, they were both left rueing the draw that saw them placed in the same group as 2010 winners Spain and European champions Portugal, with only the top two sides advancing to the last 16.
Spain and Portugal, 10th and fourth in the world rankings respectively, have won four major tournaments between them in the past 10 years. Before the match, Iran’s coach Carlos Queiroz said his side had been “drawn in the hardest group in the World Cup”.
Going into injury time in St Petersburg, it looked like being a result neither Morocco or Iran wanted before Morocco’s Sofyan Amrabat conceded a needless free-kick by fouling Saman Ghoddos near the corner flag.
But that gave Ehsan Haji Safi the opportunity to whip in the free-kick, and Bouhaddouz could only steer the ball into his own net for an unlikely Iran victory.
Morocco will now need a positive result when they play Portugal on Wednesday, 20 June (13:00 BST), before Iran play Spain at 19:00 BST on the same day.