The Australian Open champion had lost his previous two Masters finals and looked like losing a third until Federer's level dropped suddenly late in the second set, and Wawrinka began troubling the 17-time Grand Slam champion with his aggressive backhand.
The fourth-seeded Federer, who accepted a wild card invitation to play in the tournament, was also looking to win it for the first time after losing his three previous finals here to eight-time champion Rafael Nadal from 2006-08.
Wawrinka has beaten Federer only twice in 15 matches but both victories have come here. He also beat him in the third round in 2009.
“It's exceptional to be able to win my first Masters title here,” Wawrinka said.
It was the first time that Federer and Wawrinka met in a championship decider. In the last all-Swiss final, Marc Rosset beat Federer in Marseille in 2000.
With the third-seeded Wawrinka serving for the match, Federer shouted in frustration as he missed an easy forehand on second serve at 15-15. On the next point, Federer's backhand went wide and Wawrinka clinched the victory with a crisp forehand winner that landed on the line.
The players, who are good friends, shared a warm hug at the net.
“I had a great week here,” Federer said. “Congratulations to Stan.”
It is the seventh title of the 29-year-old Wawrinka's career, and his third this year. He lost his previous Masters finals at Madrid last year and Rome in 2008.
Federer broke for a 3-2 lead when Wawrinka's backhand long, and served out the first set when his countryman over-hit another backhand.
Wawrinka secured a break to take a 2-0 lead in the second, but Federer broke straight back with a brilliant passing shot down the line and confidently held to love to send the second set into a tiebreaker.
But then he seemed to lose his way.
One sloppy backhand from Federer allowed Wawrinka to move 2-0 ahead, and the Australian Open champion moved 4-1 up with a volley at the net.
Federer saved two set points at 6-3 but Wawrinka leveled the match with a clinical smash after Federer had returned his serve a bit too high.
Federer was seeking the 79th title of his illustrious career, and his 22nd Masters trophy. The 32-year-old Swiss has lost three of his four finals this year, with the other defeats against Novak Djokovic at Indian Wells and to Lleyton Hewitt at Brisbane.
The next two Masters events on clay are at Madrid and Rome leading up to the French Open, which starts on May 25.