Always ask. My dog is a black labrador; an abused rescue I found at a shelter. When I got him (a male), he was limping and terrified. If you touched an ear, he would yelp like you kicked him: somebody had been dragging him (or lifting him) by his damn ear. An x-ray of his leg showed healing from a cracked bone, and his knee had been dislocated for so long it couldn't be put back without surgery. My vet suspected a hard kick caused both of those.
After seven years, there are seven people that can touch him on the head. Me, my wife and daughter are three of them. He's a happy dog. Still limping, but he gets medication to control the pain.
If you (a stranger) try to scratch him under the chin, he will let you. He likes to make friends. Try to pat him on the head or scratch his ears, and he will snarl to kill you. Persist and he will attack you. My dog knows forty commands, the difference between his right and left, he even knows what it means for him to make a choice between walking paths or foods. He won't cross the street or leave his yard without permission. He understands when I tell him to stop barking, or that somebody is a guest. But when it comes to his ears, this is behavior I can't do anything about.
If you ask me, I'll tell you: Do not touch his head or ears, it hurts. Scratch him under the chin. The hurt is psychological; he actually likes being scratched on the head if he trusts you, but this is the easiest way for me to inform you.
You don't know strange dogs, or their history. Don't assume.