Can a Contract Be Against the Law?
The Object and Purpose of a Contract Must be Legal and Moral As Otherwise the Contract May Be Deemed Unenforceable
A Helpful Guide For How to Determine Whether a Contract Is For An Illegal Purpose and Therefore Unenforceable
Basic contract law principles require that the object and purpose and terms of a contract be lawful and moral if the courts are to uphold and enforce the contract. This requirement is known simply as the element of 'legality' and is one of the six primary elements required for the formation of a legally binding contractual agreement. Without the six primary elements, the courts should treat the 'purported' contract as exactly that, 'purported' or at best, a failed attempt to establish a legally binding contractual relationship. Note that such inherently implies that where an attempt to contract fails, and therefore the very existence of any legally binding contract failed to occur, such a contract is, legally speaking, a failed contract.
With the above said, it is common that laypeople will attempt to establish an enforceable contractual arrangement, and cross the line into illegality, without any actual intentions to break the law and therefore with intent and belief that the attempt to contract is legitimate. As simplistic examples, it is easily recognized by most reasonable people that two people are unable to enter into an enforceable contract when the purpose of the contract is to illicitly smuggle drugs in that if the drug smuggler goes unpaid, the drug smuggler will be unable to attend court to seek an Order instructing payment as per the agreement to to smuggle drugs. However, the same principle applies when a homeowner and a landscaper attempt to enter into an enforceable contract to install a tree in front of the home but upon land that is municipally owned. If the landscaper installs the tree, per an agreement with the homeowner, and the municipality removes the tree advising that such was an illegal act contrary to a municipal by-law, the landscaper will find great difficulty within any attempt to obtain court assistance in getting payment from the homeowner.
The Law, jurisprudence
Cases on the point of law that require legality of object and purpose are plentiful and are often available to address a specific issue of illegality or immorality as well as the general principle of unenforceable agreements. The principle was well outlined within Complete Access Lift & Mobility Ltd. v. Riggi, 2010 CanLII 100648 where it was stated:
116 Ex turpi causa is a venerable old legal maxim with a rather chequered history and a somewhat tenuous claim to accurately describing current legal practice. Loosely translated it means that the Courts will not enforce claims that arise out of illegal or immoral conduct. It has been all-but abolished in the context of tort law in Canada: Hall v. Hebert, 1993 CanLII 141 (SCC),  2 S.C.R. 159, but survives in the law of contracts: the law will not enforce a contract involving the commission of an illegal act.
The contracts that are illegal in the strict sense are the following: a contract to commit a crime, a tort, or a fraud on a third party; a contract that is sexually immoral; certain contracts contrary to public policy, such as contract to the prejudice of public safety; contract to the prejudice of due administration of justice; contract that tends to corruption in public affairs; contract to defraud the revenue, or one prohibited by statute.
A common illegality of contract (as above failure to enter into a legitimate bona fide and therefore enforceable contract) situation that arises are those attempts to contract where an object or purpose or term within the agreement is to avoid taxation, essentially a defrauding upon the government such as that which occurred in Jabbaz v. Mouammar, 2003 CanLII 2317 where it was said:
 I have been referred by the plaintiff to Bursey v. Bursey (1999), 1999 CanLII 19021 (NL CA), Carswell Nfld. 141, 99 G.T.C. 7190, 174 Nfld. & P.E.I.R. 391, 533 A.P.R. 291, 47 R.F.L. (4th) 1. In Bursey v. Bursey the issue was the enforceability of a provision in a domestic contract requiring the wife to indemnify the husband for half the retail sales tax payable on equipment owned by his business operated during the marriage. The husband had deliberately failed to pay the tax. He assured the wife that she would not have to indemnify him so long as she did not report him to Revenue Canada. The purpose of the indemnity clause was to discourage the wife from reporting her husband’s failure to pay tax to the relevant authorities. The Newfoundland Court of Appeal wrote, at paragraph 25:
The circumstances of this case do not require contemplating venturing beyond the parameters of precedent, which furnish a general rein on the scope of invalidating private compacts. This is because it is well settled that a contractual provision whose ultimate design is to perpetrate a fraud on a public taxing authority is contrary to public policy and unenforceable (see Alexander v. Rayson (1935),  1 K.B. 169 (Eng. K.B.); Miller v. Karlinski (1945), 62 T .L.R. 85 (Eng. C.A.); and, Napier v. National Business Agency Ltd.,  2 All E.R. 264 (Eng. C.A)). If the judge's finding that the indemnity provision was inserted in the agreement between the parties with the ulterior purpose of evading tax is supportable, then its objective can only be viewed as aimed at defrauding the provincial government. In that case, precedent clearly justifies declaring the provision unenforceable on the ground that it is, as the judge held, contrary to public policy.
Interestingly, the parties to an attempt to contract, meaning an unenforceable agreement due to illegality, are without the need to know at the time of the attempt to contract that the conduct is illegal. It is enough that the agreement required conduct that is illegal to make the agreement unenforceable. This was stated by the Court of Appeal in the case of William E. Thomson Associates Inc. v. Carpenter, 1989 CanLII 185, being a civil litigation case involving an attempt to collect a debt containing interest where the rate of interest was contrary to the sixty (60%) percent annual limit as prescribed within the Criminal Code, R.S.C. 1985, c. C-46 wherein at page 6 it was said:
There is no doubt that the respondent company committed an offence under s. 347(1)(a) by entering "into an agreement or arrangement to receive interest at a criminal rate". In R. v. McRobb (1984), 1984 CanLII 3521 (ON SC), 20 C.C.C. (3d) 493; affirmed by this court, 1986 CanLII 4766 (ON CA), 32 C.C.C. (3d) 479n, Ferguson Co. Ct. J. held that the requisite mens rea of an offence under s. 347 is provided simply by an accused voluntarily entering into a loan agreement providing for receipt by him of a criminal rate of interest. The Crown is not required to prove in addition that the accused knew that charging an interest rate above 60% was unlawful. Judge Ferguson said at pp. 500-1:
It would appear that the general rule applicable to both civil and criminal usury is that there must exist an intent that the lender is to take more than the legal rate of interest for the sum loaned. The required intent does not involve a consciousness of the illegality of the transaction or a specific intent to violate the statute, but only an intent to extract payments in excess of the amount of interest permitted by law.
He also held that it is no defence that the borrowers were willing to participate in the agreement and that the Crown is not required to prove in addition that the accused acted dishonestly or preyed on others by usury or was engaged in swindling or trickery.
Since the respondent company admitted the very offence prohibited by s. 347 of entering into an agreement to receive interest at a criminal rate, it follows that it cannot enforce payment of interest in civil proceedings. The ancient maxim ex turpi causa non oritur actio applies. The agreement to receive a criminal rate of interest is prohibited by statute and the courts have consistently held that such agreements are void and unenforceable: see S. Waddams, The Law of Contracts, 2nd ed. (1984), at p. 421. This principle was recognized by an early decision of the Supreme Court of Canada, cited with approval by Professor Waddams, in Bank of Toronto v. Perkins (1883), 1883 CanLII 52 (SCC), 8 S.C.R. 603, where Ritchie C.J. said at p. 610:
It would be a curious state of the law if, after the Legislature had prohibited a transaction, parties could enter into it, and, in defiance of the law, compel courts to enforce and give effect to their illegal transactions.
Strong J. expressed the principle even more forcefully at p. 613:
Whenever the doing of any act is expressly forbidden by statute, whether on grounds of public policy or otherwise, the English courts hold the act, if done, to be void, though no express words of avoidance are contained in the enactment itself.
Other Cause of Action Rights
It is of particular interest, per Complete Access Lift as above while citing Hall v. Hebert,  2 S.C.R. 159, that the ex turpi causa doctrine applies only to the unenforceability of contract an without application to tort law. Accordingly, it appears that parties to an unenforceable contract could attempt to form an agreement for which the terms are unenforceable due to illegality; however, for tort law matters, such as negligence, arising from the attempt to contract, the right to pursue legal claims, other than as a breach of contract, may remain available.
The possibility of pursuing remedies within a legal case for other than breach of contract where the contract contained illegality is frequently said and was a point addressed within the William E. Thomson Associates at page 11 wherein it was said:
Whether or not a contract tainted by illegality is completely unenforceable depends upon all the circumstances surrounding the contract and the balancing of the considerations discussed above and, in appropriate cases, other considerations. This careful case by case approach was anticipated more than half a century ago by Masten J.A. in Steinberg v. Cohen, 1929 CanLII 419 (ON CA),  64 O.L.R. 545,  2 D.L.R. 916 (H.C.J.), where he said at p. 558 O.L.R., p. 928 D.L.R.:
It is possible that each case should depend upon its own facts, and upon a balancing by the Court of the public interest on the one hand and of the private injustice on the other.
Accordingly, where a contract is illegal and therefore unenforceable within breach of contract litigation, there may remain an opportunity to obtain remedies from the court by bringing legal action as something other than breach of contract.
Contracts with an object or purpose or terms that are illegal or immoral may, and likely will, be deemed unenforceable; however, tort law issues and perhaps equity law issues including unjust enrichment claims, among other claims, may remain available for litigation within the courts.