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."
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