South Africa was moving along solidly enough at 4-199 early on in the final session of the opening day, but then Pakistan skipper Misbah-ul-Haq threw the ball to Hafeez and the game took a dramatic turn in favour of the tourists.
Hafeez ripped through South Africa's lower order with his off-spinners to see the Proteas to go from 4-199 to all out for 253 with Hafeez claiming 4-16 from his 7.2 overs.
Pakistan then had to come out and bat for two overs to close out the day, and Hafeez and Nasir Jamshed both survived an over apiece, with Hafeez not out on six and Jamshed yet to score in his Test debut.
South African captain Graeme Smith won the toss to open his 100th Test match, the most by any captain in international cricket history, and chose to bat first on a wicket that did look set to give some life for the bowlers but one that could play well for batsmen if they got in.
Right through South Africa's top seven they were all able to make starts, but never looked totally comfortably at the crease and no batsmen made more than Jacques Kallis' 50.
Pakistan elected to give a Test debut to non-threatening left-arm quick Rahat Ali rather than 7'1 giant Mohammad Irfan to partner Umar Gul and Junaid Khan as the seam bowlers.
South Africa's openers Smith and Alviro Petersen made a solid start putting on 46 for the first wicket before Khan picked up Petersen for 20. The score was then 2-46 when Smith fell the very next over, caught behind by Sarfraz Ahmed off Gul for 24.
Kallis and Hashim Amla then led a recovery mission and put on 79 for the third wicket before Kallis fell for 50 when Asad Shafiq took a tremendous outfield catch off Gul from a hook shot.
Once again the other member of the partnership fell soon after when Amla was out for 37 to the innocuous medium-pace bowling of Younis Khan. It was just Khan's eighth wicket of his 80-match Test career.
It was then another steadying partnership for South Africa between AB de Villiers and Faf du Plessis. The pair combined for 64 before de Villiers became Hafeez's first victim when he was caught behind for 31.
Du Plessis was next to go for 41 when a defensive shot off Junaid Khan bounced off and clipped the stumps, and knocked one bail off.
Robin Peterson was next to go without scoring when he left a ball from Hafeez and it cannoned into his off-stump. Vernon Philander and Dean Elgar then had a disastrous mix up running leaving the former to be run out for one.
Elgar was then caught behind off Hafeez as well for 27 before Morne Morkel was clean bowled by him for a duck. Dale Steyn remained not out on 12.
As well as Hafeez's 4-16, Gul claimed 2-56, Junaid Khan 2-33 and Younis Khan 1-16 for Pakistan.