When is it legal to go to war?

Was it legal for the USA and Israel to start a war with Iran? Also, was it legal or not for Iran to retaliate by launching attacks on its Gulf state neighbours?