The body breaks down the chemicals in the drug, and those chemicals deposit themselves into the hair and nails due to their chemical characteristics. Essentially your body is a large, flowing vessel of water. So pesticides, which are very hydrophobic, are mostly eliminated but some deposit into your fat, and never leave. Likewise the metabolic products of THC and cocaine deposit into the hair and nails, although in small quantities. Further, people never cut all of the nail and never cut off all of their hair either, so it leaves a good record of what you have been up to. And yes, if you shave your head, they will just take pubic hair. There are numerous toxicology textbooks and articles if you are interested in further reading, but you have to know a good deal of chemistry and biology to understand it.