It could be legal but a “punitively large sum of money” would not be
The remedy for a breach of contract is damages, not punishment; punishment is reserved for the state in response to an offence, not to an individual for a breach of contract. Such a clause would be void, and you would be left seeing for damages that you suffered by the breach which would appear to be approximately $0.
Furthermore, while you can require the subsequent owner to include a similar clause in a sale to a third-party, if they don’t, you have no cause of action against that third-party. In any event, you are still left seeking your $0 damages.
Other ways of achieving the outcome
Lease with an option to buy
Lease the property for 5 years with the use restriction with an option to buy if they complied.
Restrictive Covenant
Where local law permits, place the restrictive covenant on the land. For example, until 31 December 2028, the property may not be rented out. The reason I phrased it that way rather than “must be your primary residence” is that courts are extremely reluctant (as in almost never) to allow a person’s lifestyle choices like where they live to be restricted.
Note that such covenants can be set aside by government in some jurisdictions. For example, in new-south-wales any restriction that prohibits a use the council would allow, may be set aside on application.
Government Planning
If this is a worthwhile policy objective (see below), then it is likely more useful to engage government in the solution. For example, the NSW Government is going to allow the construction of residential units in commercially zoned areas but only if they are built-to-rent.
What problem are you and your friend trying to solve?
Restrictions on renting properties tend to make housing less affordable, not more affordable. Having a large number of investment properties available on the market tends to drive rent (and therefore housing) down, not up. So, I’m not exactly sure what “the problem of investment properties” is. Your solution would appear to make housing affordability worse.
If you are trying to address the problem of home ownership, then your solution seems counterproductive. Many first time property owners get into the market through buying an investment property rather than buying a home. If you have somewhere cheap to live (e.g. mum & dad’s house), this can be far more affordable than buying a place to live. Your plan closes this down. So, this solution could also make home ownership worse.
While encouraging home ownership is a laudable aim (maybe), doing so at the expense of affordable housing for people who can’t or don’t want to own a home seems counterproductive.