Great question. There are several hypotheses, but in reality no one really "knows" because this is incredibly difficult to prove. We may never know for certain.
Anyway, on to the three main hypotheses, I got this from http://en.wikipedia.org/wiki/Viral_evolution, I think you'll find it to be helpful.
"There are three classical hypotheses on the origins of viruses: Viruses may have once been small cells that parasitized larger cells (the degeneracy hypothesis or reduction hypothesis); some viruses may have evolved from bits of DNA or RNA that "escaped" from the genes of a larger organism (the vagrancy hypothesis or escape hypothesis); or viruses could have evolved from complex molecules of protein and nucleic acid at the same time as cells first appeared on earth (the virus-first hypothesis)."
However, as you may have guessed, there are plenty of questions that these theories do not answer. The next paragraph:
"None of these hypotheses was fully accepted: the regressive hypothesis did not explain why even the smallest of cellular parasites do not resemble viruses in any way. The escape hypothesis did not explain the complex capsids and other structures on virus particles. The virus-first hypothesis was quickly dismissed because it contravened the definition of viruses, in that they require host cells. Virologists are, however, beginning to reconsider and re-evaluate all three hypotheses."
There is a little more information on the Wikipedia page, I would recommend that you read that and do a little research on the different theories if you would like to know more.
I hope this helps,