It is only allowed in the very rare situation where if the person did not do this, they would commit zina (i.e. The early Muslims used to say, “The one who weds his hand is accursed.” (Fath al-Qadir) For the answer to this question, I will defer to Shaykh Faraz Rabbani, who writes: “Masturbation is sinful, being prohibitively disliked, and having many personal and societal ill-effects that are known and recognized in sane traditional societies and by balanced people in the world over.