It was the first match Benin had ever won at the AFCON.
Sofiane Boufal and Youssef En-Nesyri missed their spot kicks for Morocco, and Seibou Mama buried the decisive penalty as Benin won the shootout 4-2.
The match finished 1-1 after extra time.
Moise Adilehou gave Benin the lead in the 53rd minute when he stuck out a foot to volley home from a corner.
En-Nesyri equalized for Morocco in the 76th, and the Moroccans should have won it when they won a penalty deep in injury time at the end of the 90.
Hakim Ziyach smacked the penalty off the post and Benin survived to advance from its first-ever knockout game at the tournament.