Two-electron theory of surface and impurity states