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