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 like 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.