If the ball goes in the goal off the referee, none of them.
If the ball hitting the ref had resulted in a change of possession or started a promising attack, none of them.
If the ball hits the ref, stays in possession of the team that played it and they go down the pitch and score, it is legal...