Substitute Seidu Suraj scored eight minutes into added time to give 10-man Ghana a 3-1 win over Sudan in Algeria on Thursday, and an African Nations Championship (Chan) quarter-finals place.
Whatever the outcome of the final Group C match on Monday between Madagascar and Sudan, Ghana are sure to finish among the top two teams, but they had to win by two goals to ensure that feat.
Sudan must win the remaining fixture by at least two goals to prevent debutants Madagascar going through in a competition confined to footballers playing for clubs in their country of birth.
In one of the most dramatic matches so far in the seventh edition o the competition, twice bronze medalists Sudan dominated the early exchanges and deservedly led when Al-Gozoli Nooh scored on 31 minutes.
Two-time runners-up Ghana, back at the tournament after failing to qualify for the last three, equalised in first-half added time, in the eastern city of Constantine, as Konadu Yiadom poked the ball home.
Captain Daniel Afriyie was a constant threat to the Sudanese and, after being fouled, converted the 64th-minute penalty to edge Ghana ahead.
Afriyie thought he scored again with a header only to be ruled offside and was later shown a straight red card for a dangerous foul.
Sudan had several chances to level in added time, and got the ball in the net only for the score to be disallowed because star Mohamed Abdel Rahman committed a foul in the build-up.
Ghana then atoned for a shock loss to Madagascar by clinching a last-eight place as Seidu hammered the ball into the net from close range.
They are the second qualifiers for the quarter-finals after hosts Algeria, who secured a place by beating Ethiopia 1-0 on Tuesday.
On Friday, Angola play Mauritania in Group D and Congo Brazzaville face Niger in Group E in an Oran double-header.