Can a contract prohibit something that is legal?
It is entirely possible to make and enforce a contract that forbids you from doing anything that is within your legal rights. One illustration would be a parent offering their child money if they gave up smoking for a year. The child’s intention of abstaining from doing something that was within his legal right is sufficient to form the contract, and the agreement can be upheld.
Another example would be a non-compete clause. A non-compete clause in their employment contract may forbid them from working for a rival company after they leave one. Although accepting the job wouldn’t be against the law, it would be a violation of the contract. The fact that both parties agreed to it and signed it makes the contract enforceable.
Contracts restrict solely legal action. Illegal action is prohibited by law, regardless of any contract.
Contracts cannot restrict someone from exercising their legal rights (e.g. the right to life, liberty, and the pursuit of happiness).