There are many places in Spain where you can camp, on the beach for example, if you are careful about bringing drinking water. Friends have travelled across Spain without ever stopping at a formal site. The small villages in the Sierra Nevadas will mostly allow you to sleep in the vicinity, and it is possible that this is also true for the rest of Spain. This map, in Spanish, seems to provide a more formal list of pleasant areas.
For the most part, this is legal. There are certain restrictions, such as not camping near paid camp sites or in urban areas. Military areas need to be avoided as well. Lighting fires is forbidden most places for a lot of the year. Sleeping in the open air is the easiest, because you cannot just set up a tent and leave it there.
There can be problems with gangs of thieves, though I have not encountered them in the areas that I visit around the Sierra Nevadas.