Legged robots may become unstable when subjected to unexpected disturbances such as external pushes and environmental irregularities mostly while moving on natural terrains. To enhance the mobility performance, legged robots should be able to keep or restore their balanced configuration when a sudden disturbance is exerted. The aim of this article is to design a controller for a quadruped robot to restore its balanced configuration despite exerting external pushes. This is achieved based on developing a full-dynamics model of the robot moving over even and uneven terrains. The proposed controller is based on a PD module which calculates the required accelerations for restoring the robot equilibrium. However, these accelerations may make the robot unstable and also cause the slippage of stance feet. Therefore, an optimization algorithm is used to compute the maximum admissible accelerations. The constraints of the optimization problem are the conditions which guarantee the robot stability and the stance feet slippage avoidance. The optimization algorithm is transformed into a linear constrained least-squares problem to be solved in real-time. The main contributions of this article are the development of a push recovery algorithm for quadruped robots and also the introduction of an appropriate condition which guarantees the stability of the robot even on uneven terrains. This stability condition is developed based on a full-dynamics model of the robot. The proposed algorithm is applied on an 18-DOF quadruped robot when the robot is standing over both even and uneven terrains. The obtained results show that the robot can successfully restore its balanced configuration by precise adjustment of the position and orientation of its main body while a massive external disturbance is exerted.