The Real Madrid forward had already netted two first-half goals to put his side ahead, only for Diego Costa to score either side and Nacho - at fault for the Selecao's opener - to complete the stunning turnaround.
On his 36th outing at a major international tournament, however, Ronaldo sent a free kick up and over the wall to beat David de Gea for a third time, meaning that the Group B spoils were shared at the Fisht Olympic Stadium.
Prior to that late twist, Spain had hit back twice to put themselves on course for a positive end to a difficult week, with this classic coming just two days after the sacking of manager Julen Lopetegui.
That would prove a big call as, after just two minutes of an action-packed contest, Nacho stuck out a leg and Ronaldo took full advantage of the contact inside the box, before tucking away the penalty.
In response, David Silva sent a couple of chances wide as Spain took control of possession, patiently probing away for an opening.
Portugal were happy to live off counter-attacks, though, and they should have doubled their tally through one such move as only a poor first touch prevented Goncalo Guedes from converting inside the box.
Moments later, Costa showed his qualities of old as he aggressively won the ball from Pepe, held off Jose Fonte and then picked out the bottom corner after waiting a couple of seconds for the perfect time to shoot.
Buoyed by that impressive individual strike, Isco sent a bullet shot against the underside of the bar - goal-line technology confirming that it did not cross the line, despite the midfielder's protests.
Portugal went into the interval a goal in front, though, with Ronaldo's routine 20-yarder somehow squirming through the hands of De Gea.
Just 10 minutes of the second half were required for the 2010 winners to get back on level terms for a second time, courtesy of Costa's close-range finish from a Sergio Busquets knockdown at the back post.
The game was then turned on its head less than three minutes later, as Nacho redeemed himself for his early challenge on Ronaldo by guiding a perfectly-struck half-volley past Patricio from outside the box.
Costa spurned the chance to score his own World Cup hat-trick when dragging a decent opportunity wide, with Iago Aspas coming on in his place for the final 13 minutes.
Aspas tested Patricio soon after being introduced, but it was at the other end of the field where the late drama would come as Ronaldo sent a free kick dipping over the Spain wall, completing the 51st hat-trick in World Cup finals history and the 51st hat-trick of his senior career.
PORTUGAL (4-2-3-1): Rui Patricio; Cedric, Pepe, Fonte, Guerreiro; Carvalho, Moutinho; Fernandes (Joao Mario 68'), B.Silva (Quaresma 69'), Guedes (Andre Silva 80'); Ronaldo
SPAIN (4-2-3-1): De Gea; Nacho, Pique, Ramos, Alba; Busquets, Koke; Silva (Lucas Hernandez), Isco, Iniesta (Alcantara 70'); Diego Costa (Aspas 77')