Luis Neto bundled into his own net to hand Mexico a 54th-minute lead, but Pepe stabbed home a stoppage-time equaliser to force an extra 30 minutes at Spartak Stadium.
Silva then struck his first international goal after a handball inside the box on 104 minutes, while both sides finished with 10 men as Nelson Semedo was dismissed for Portugal before Raul Jimenez saw red for Mexico.
World champions Germany face Copa America holders Chile later in the final in Saint Petersburg.
"Of course we wanted to play in the final, to clash for the Confederations Cup. But after we failed to get that result, we needed to show our best in the third-place game. Luckily we did everything right."
More From This Section
European champions Portugal were without captain Cristiano Ronaldo after the Real Madrid star was released from the squad to return home to meet his newborn twins.
Portugal and Mexico drew 2-2 in the opening game of the group stage, when Hector Moreno salvaged a last-gasp point for the Gold Cup winners, but were left fighting for a consolation prize in the Russian capital.
But Mexico goalkeeper Guillermo Ochoa flung himself superbly to his right to tip Andre Silva's low spot-kick round the post.
Rui Patricio produced a sharp stop to deny Javier Hernandez, Mexico's all-time leading scorer, from close range on the half hour, but the Portugal keeper was beaten shortly after the break.
Hernandez's cross from the byline floated beyond Carlos Vela and Patricio, with Zenit St Petersburg centre-back Neto unwittingly turning the ball home.
But Ochoa was beaten in the first minute of injury time as Pepe lunged to get on the end of Ricardo Quaresma's curling right-wing cross to force extra time.
Silva, on as a substitute, then grabbed the winner just before the end of the first period of extra time, burying a penalty after Miguel Layun handled in the box.
Semedo was then sent off on 106 minutes after picking up a second yellow card, but Mexico's numerical advantage was swiftly wiped out when Jimenez received his marching orders.
"We put them under pressure late in extra time but failed to level again, like we did in our first meeting here.