Because of cost and resource constraints, sensor nodes do not have a complicated hardware architecture or operating system to protect program safety. Hence, the notorious buffer-overflow vulnerability that has caused numerous Internet worm attacks could also be exploited to attack sensor networks. We call the malicious code that exploits a buffer-overflow vulnerability in a sensor program sensor worm. Clearly, sensor worm will be a serious threat, if not the most dangerous one, when an attacker could simply send a single packet to compromise the entire sensor network. Despite its importance, so far little work has been focused on sensor worms. In this work, we first illustrate the feasibility of launching sensor worms through real experiments on Mica2 motes. Inspired by the survivability through heterogeneity philosophy, we then explore the technique of software diversity to combat sensor worms. Given a limited number of software versions, we design an efficient algorithm to assign the appropriate version of software to each sensor, so that sensor worms are restrained from propagation. We also examine the impact of sensor node deployment errors on worm propagation, which directs the selection of our system parameters based on percolation theory. Finally, extensive analytical and simulation results confirm the effectiveness of our scheme in containing sensor worms.