Achraf Hakimi hit a stunning free kick six minutes from the end to save Morocco from an upset defeat against a Gabon side which had eight players ruled out due to COVID-19 infections, including talisman Pierre-Emerick Aubameyang.
- Africa Cup of Nations bracket and fixtures schedule
- Africa Cup of Nations: Everything you need to know
- AFCON kit rankings: Who has the best jersey?
- Don't have ESPN? Get instant access
Morocco finished with seven points, two ahead of second-placed Gabon.
Gabon had some good fortune for their 22nd-minute opener as a long ball kicked up field by goalkeeper Jean-Noel Amonome was missed by Morocco centre back Sofian Chakla, who slipped as he attempted to clear and Allevinah came running through to hit it in first time with his left foot.
For all their possession, Morocco struggled to create chances and Gabon might have had two more goals in the first half, showing no signs of missing Aubameyang, who has returned to London for further medical tests after his bout of COVID-19.
First Boupendza turned Chakla and got goalside only to put his effort narrowly wide before Lloyd Palun headed firmly towards the target only for a flying save from Morocco goalkeeper Munir to deny him.
Morocco eventually equalised after Andre Biyogo Poko brought down Boufal, although it looked a marginal decision confirmed by VAR.
Boufal got up to slam home the penalty but six minutes later Boupendza was at the end of a square pass, squeezing the ball home from a tight angle to restore Gabon's lead.
Hakimi then hammered in a late, long-range free kick to make it 2-2 and ensure Morocco topped the group.
"It was satisfying to see the character of the players although Gabon were very difficult, especially on the counter attack," said Morocco coach Vahid Halilhodzic.
Morocco must wait to find out who they face next, while Gabon will take on Burkina Faso in Sunday's opening match of the last 16.
Zambian referee Janny Sikazwe, who caused a furore last week when he ended the match between Mali and Tunisia before time and then tried to get the teams back on the pitch some 30 minutes later to play an additional four minutes, served as the Video Assistant Referee for the match.