We develop a model for contagion risks and optimal security investment in a directed network of interconnected agents with heterogeneous degrees, loss functions and security profiles. Our model generalizes much of contagion models in the literature; in particular the independent cascade model and the linear threshold model. We state various limit theorems on the final size of infected agents in the case of random networks with given vertex degrees for finite and infinite variance degree distributions. The results allow us to derive a resilience condition of the network to the infection of a large group of agents and quantify how contagion amplifies small shocks to the network. We show that when the degree distribution has infinite variance and, highly correlated in- and out-degrees, then even when agents have high thresholds, a sub-linear fraction of initially infected agents is enough to trigger the infection of a positive fraction. We also show how these results are sensitive to vertex and edge percolation (immunization). We then study the asymptotic Nash equilibrium and socially optimal security investment. In the asymptotic limit, agents' risk depends on all other agents' investment through an aggregate quantity, that we call network vulnerability. The limit theorems allow us to capture the impact of one class of agents' decision on the overall network vulnerability. Based on our results, the vulnerability is semi-analytic allowing for a tractable Nash equilibrium. We give sufficient conditions for investment in equilibrium to be monotone in the network vulnerability. When investment is monotone, we show that the (asymptotic) Nash equilibrium is unique. In the particular example of two types core-periphery agents, we exhibit a strong effect of the cost heterogeneity and in particular non-monotonous investment as a function of costs.