For example if I know that [s],[z], [dz] and [ez] are allophones. How do I determine the underlying phoneme sound?
If you have a set of phonetically similar phones in complementary distribution, with no contrasts,
then you may assume they are allophones of the same phoneme.
What you call the "underlying sound" is entirely your affair, like naming a species. It's just a name.
Phonemes are simply named patterns of sound usage, and
their phonological status may be very different from their phonetic status.
For instance, English has a phoneme with at least a dozen different allophones, all voiceless vowels.
The allophones include voiceless versions of every English vowel, immediately preceding that vowel.
I.e, [ḁa], [e̥e], [i̥i], [ɛ̥ɛ], where the mark below the vowel indicates voicelessness.
This English phoneme is entirely vocalic phonetically, but it's a consonant phonologically.
In fact, it's the English phoneme /h/, which used to be pronounced as a velar fricative; but
since it only appears before vowels in Modern English, it has become a mere voiceless vocal
onset, setting the tongue in position for the oncoming vowel, and then starting the phonation
before starting the voicing.
Names are just names, even for phonemes; but the usual convention (not followed with /h/)
is to use the name of the most common allophone for the phoneme when possible.
Let's say you are assuming that the underlying phoneme has intrinsic phonetic content and all of the same features as the surface phones (I don't agree with this personally, but that is what you assume in your first phonology course). What you then do is select your underlying phoneme such that you can write the simplest set of rules (and each rule should be as broadly applicable as possible) that predict the occurrence of all of the surface phones. If you want a shortcut to the answer, and historical data is available, determine the historical sound that all of the allophones descend from (assuming there is just one).