Hosts Morocco needed extra-time to overcome a stubborn Libyan side 3-1 to reach the final of the African Nations Championship (CHAN) in front of a packed crowd in Casablanca.
Ayoub El Kaabi's seventh goal of the tournament looked like sending Morocco to the final until an error from his keeper Anas Zniti gifted Libya's Abdoulraham Khalifa an equaliser.
El Kaabi put Morocco 2-1 up in the sixth minute of extra-time with a simple tap-in before Walid El Karti's penalty put the result beyond doubt.
In Sunday's final of the tournament for home-based African footballers, Morocco will now face either Nigeria or Sudan who meet in the second semi-final later on Wednesday in Marrakech.
Urged on by a vociferous crowd, the first chance of the match fell to Morocco after just six minutes when Walid El Karti managed to flick the ball past the goalkeeper only to see Motasem Sabbou hook it away for a corner.
After 24 minutes, Morocco should have taken the lead after a Bencharki free-kick was headed against the bar by Salaheddine Saidi - and a follow up header from Ayoub El Kaabi was easily saved by Mohamed Nashnoush.
Bencharki, who has now signed for Saudi Arabian side Al Hilal, tried his luck with a direct free-kick from outside the area forcing Nashnoush to save well as the ball swerved.
Libya did try and cautiously push forward in the first half but they did not manage a shot on target.
Fifteen minutes after the break, Libya had their best chance of the game when Saleh Taher had his header cleared off the line by Abdeljalil Jbira.
Morocco continued to create the better opportunities and eventually broke the deadlock after 72 minutes when substitute Zakaria Hadraf's cross was met by El Kaabi to guide his header home.
The Libyans continued their quest to score and the Moroccan keeper Anas Zniti made a good save at the feet of Moftah Taktak.
Zniti tried controlling the ball in his area and dribbled away from Libyan attackers, but a heavy touch allowed Taher to get a foot to the ball and it fell to Khalifa to convert an easy chance with an open goal to aim at, making it 1-1.
Libya had the first chance of extra-time as Ahmed Eltrbi's header was scrambled away by a combination of Zniti and two other Moroccan players.
In the 96th minute, El Kaabi scored the easiest of his eight goals at this tournament so far - a simple tap-in at the far post from a Hadraf corner that Jawad El Yamiq flicked on with his head.
With four minutes remaining, the result was sealed when El Karti picked himself up from being fouled by Eltrbi to score from the penalty spot.
The Libyans complained that Eltrbi got the ball - but the referee ruled he had used two feet in the foul.
They also complained about El Karti's stuttering run-up which was also waved away by the officials.