In general, masturbation is haram (forbidden) in Islam.
Imam Shafii stated that masturbation is forbidden based on the following verse from the Quran (interpretation of the meaning):
“And those who guard their chastity (i.e. private parts, from illegal sexual acts). Except from their wives or (the captives and slaves) that their right hands possess, for then, they are free from blame. But whoever seeks beyond that, then those are the transgressors.”-(The Quran 23:5-7).
The Prophet Muhammad (peace be upon him) said:
“O young men, whoever among you can afford to marry, let him get married, and whoever cannot do that, then he should fast, for it will be a protection for him.”-(Narrated by al-Bukhaari, al-Nikaah, 4677).