Barca were looking for a response from last weekend's 2-0 El Clasico defeat to Real Madrid, but appeared set for another frustrating evening.
Then with 10 minutes left, Sociedad defender Robin Le Normand was penalised for an inadvertent handball as he dived to clear a cross in the six-yard box and Messi made no mistake from the spot.
During stoppage time, Jordi Alba had an effort on the break ruled out by VAR for an offside in the build-up, as Quique Setien's side moved two points in front of their title rivals, who travel to Real Betis on Sunday.
Barcelona created an early opening when Martin Braithwaite's low shot was saved at the near post.
The Denmark forward – making a first start since a specially-sanctioned transfer from Leganes outside the transfer window – raced clear again past a high defensive line to knock the ball into the net, but the offside flag had already gone up.
Barcelona went close again just after the hour mark when Ivan Rakitic fired in an angled drive which Remiro pushed behind. From the resulting corner, Gerard Pique sent a header straight at the goalkeeper.
In the 73rd minute, Sociedad broke into the Barcelona penalty area and Mikel Oyarzabal sent a rising drive just over with Marc-Andre Ter Stegen beaten.
The home side were awarded a penalty in the 80th minute following a lengthy VAR review for handball.
Sociedad defender Le Normand dived in to try to head clear a cross in the six-yard box, with the ball striking him on the upper arm.
Referee Juan Martinez Munuera went to look at the incident on the pitchside monitor from several angles, eventually returning to point to the spot. Remiro went the right way, but could not keep Messi's curling penalty out.
Sociedad were then calling for a penalty themselves after full-back Nacho Monreal looked to have been bundled over after getting ahead of Antoine Griezmann, but the officials waved play on.
Barcelona thought they had netted a second in added time when Alba knocked in a cutback from Ansu Fati, but VAR ruled the substitute had been offside when taking Messi's pass.