In experiments, people behave more cooperatively when they are aware of an external threat, while in the field, we observe surprisingly high levels of cooperation and altruism within groups in conflict situations such as civil wars. We provide an explanation for these phenomena. We introduce a model in which different groups vary in their willingness to help each other against external attackers. Attackers infer the cooperativeness of a group from its members' behaviour under attack, and may be deterred by a group which bands together against an initial attack. Then, even self-interested individuals may behave cooperatively when threatened, so as to mimic more cooperative groups. By doing so, they drive away attackers and increase their own future security. We argue that a group's reputation is a public good with a natural weakest-link structure. We test the implications of our model in a laboratory experiment.