Where did the symbiotic thingies that live in termite's intestines come from?

Like, where did they live before there were termites to live in?

Termites are just cooperative cockroaches. They are thought to have begun as something like the wood-feeding cockroach genus Cryptocercus. The microbes that live so successfully in their guts are derived from similar free-living forms in rotting logs that get eaten when cockroaches eat the rot.  So both the ancestoral microbes and the ancestoral cockroaches were living in logs and soil well before termites came about.  You can imagine a termite as a streamlined cockroach shaped by the needs and profit of the microbes as well as the benefits of living in social groups..