Yes, flashing your own device with the official stock firmware is completely legal. Distributing copyrighted firmware without permission is not.