Bangladesh also surpassed their previous highest total of 413 against Sri Lanka in Tests.
The tourists, who avoided the follow-on in the final session, now trail by 132 runs with six wickets in hand.
The 28-year-old Ashraful, who played his last Test in December 2011, hit one six and 20 fours in his sixth Test hundred, and the fifth against Sri Lanka, while Rahim, 24, smashed one six and 18 fours in his second Test century.
It was a frustrating day for Sri Lanka, because none of their bowlers could keep up the pressure on Ashraful and wicketkeeper-batsman Rahim on a good batting pitch.
The hosts went wicketless after striking twice in the opening 11 overs.
Bangladesh added 303 to their overnight total of 135-2 for the loss of just two wickets.
Ashraful, 65 overnight, completed his century in the morning with an aggressive shot when he firmly drove unorthodox spinner Ajantha Mendis through the covers for a four.
Rahim also played some handsome shots during his big innings and reached his hundred in the last session, when he swept Mendis for a four.
Debutant Mominul Haque also impressed, scoring an 83-ball 55, with nine fours. He added 105 for the third wicket with Ashraful before being caught at first slip by skipper Angelo Mathews off paceman Nuwan Kulasekara.
The left-hander added 20 runs to his overnight score of 35.
Sri Lanka struck again when left-arm spinner Rangana Herath had Mohammad Mahmudullah stumped for no score to reduce Bangladesh to 177-4, before Ashraful and Rahim propped up the innings.
The partnership helped Bangladesh’s chances of drawing the match. Sri Lanka has won all 12 Tests against Bangladesh.