Section 51. When on duty under orders of the commander-in-chief, the military forces of the commonwealth may enter upon and occupy any public or private lands within the commonwealth for the necessary purposes of such duty, and no officer or enlisted person shall thereby become liable, either civilly or criminally, for trespass; but except in times of invasion, insurrection, riot, natural disaster, threats to homeland or national security, public catastrophe or danger, no organization of the armed forces nor individual members thereof shall be permitted to enter houses or other buildings or their immediate enclosures, without the consent of the owner or tenant in possession, nor to go upon the gardens, lawns, tobacco fields, cranberry bogs, vineyards, nurseries, planted fields, orchards or cemeteries unless extreme necessity for such entry exists, and then only in obedience to the specific orders of the senior officer present.