It comes from Genesis 38.
Onan was told to have sex with his brother's widow "to raise up offspring" for him. However, it seems that he ejaculated on the ground instead as he knew the children would not be his.
(these children would have looked after Onan's sister in law in her old age, rather than him).
God didn't approve of this, so he killed Onan.
The moral of the story has been taken as being that masturbation is wrong, but it seems to me that the point was actually Onan's selfishness.