Hello everyone.
My Brothers 2004 subaru legacy did the same thing and my wife has the same model. I looked for a fix read forum after forum. One thing I didn't read was people checking the three main plugs from engine to firewall. So I cleaned all of them and applied dielectric grease Now this was after I had cleaned all the other with no luck. He has been driving the car for 7 months now and the problem hasn't came back.
Thought I would share after a few moths trial. I hope this helps.