Imam al-Shafi'i (may Allah have mercy on him) said: "Allah, the Blessed and Exalted, says: 'And those who guard their private parts, except from their wives or those their right hands possess, for indeed they are not to be blamed. But whoever seeks beyond that, then those are the transgressors.' [Surah al-Mu'minun: 5-7]"
Imam al-Shafi'i (may Allah have mercy on him) said: "So the use of the private part is not lawful except with a wife or a slave woman; therefore masturbation (istimna') is not lawful, and Allah knows best."
Hadith Referenceالسنن الكبرى للبيهقي / كتاب النكاح / Q14132
Sayyiduna Abdullah bin Abbas (may Allah be pleased with them both) was asked about khadkhadah (self-stimulation), and he said: Marrying a slave woman is better than it, and it is better than fornication (zina).
This is mursal and mawquf.
Hadith Referenceالسنن الكبرى للبيهقي / كتاب النكاح / 14132
Abu al-Zubayr narrates from Sayyiduna Abdullah bin Abbas (may Allah be pleased with them both) that a young man came to him. The people began to leave, but he remained seated. Some of the people said: O young man, go! Sayyiduna Abdullah bin Abbas (may Allah be pleased with them both) said: Leave him; something has kept him seated. When the people had gone, the young man said: O Ibn Abbas, I am a young man and I feel intense desire, and I rubbed my private part until I ejaculated. Ibn Abbas (may Allah be pleased with them both) said: This is better than fornication, and marrying a slave woman is better than it.
Hadith Referenceالسنن الكبرى للبيهقي / كتاب النكاح / 14133