Disable the legacy GCE instance metadata APIs for GKE nodes. Under some circumstances, these can be used from within a pod to extract the node’s credentials
To remediate the misconfiguration “Ensure Legacy Compute Engine Instance Metadata APIs Are Disabled” for GCP using GCP console, follow the below steps:
Open the Google Cloud Console and select your project.
Navigate to the Compute Engine page from the left-hand menu.
From the Compute Engine page, select the “Metadata” tab.
Under the “Metadata” tab, click on the “Edit” button.
Scroll down to the “Legacy Metadata Access” section.
Select the “Disallow” option to disable the legacy metadata access.
Click on the “Save” button to save the changes.
Once you have completed these steps, the legacy Compute Engine instance metadata APIs will be disabled, and your GCP environment will be more secure.
This should output “true” which indicates that the legacy metadata APIs are now disabled.
Repeat the above steps for all the instances in your GCP project to ensure that the legacy metadata APIs are disabled for all instances.
Note: It is recommended to use the latest metadata APIs instead of the legacy ones for better security and performance.
Using Python
To remediate the misconfiguration “Ensure Legacy Compute Engine Instance Metadata APIs Are Disabled” for GCP using Python, you can use the following steps:
Import the necessary Python libraries:
Copy
Ask AI
from googleapiclient import discoveryfrom oauth2client.client import GoogleCredentials
if 'enable-guest-attributes' in metadata: if metadata['enable-guest-attributes'] == 'TRUE': metadata.pop('enable-guest-attributes') body = {'metadata': metadata} request = service.instances().setMetadata(project=project, zone=zone, instance=instance, body=body) response = request.execute() print('Legacy Compute Engine Instance Metadata APIs have been disabled.') else: print('Legacy Compute Engine Instance Metadata APIs are already disabled.')else: print('Legacy Compute Engine Instance Metadata APIs are already disabled.')
If the legacy metadata APIs are enabled, remove the ‘enable-guest-attributes’ key from the metadata and update the instance metadata with the new metadata:
Copy
Ask AI
metadata.pop('enable-guest-attributes')body = {'metadata': metadata}request = service.instances().setMetadata(project=project, zone=zone, instance=instance, body=body)response = request.execute()print('Legacy Compute Engine Instance Metadata APIs have been disabled.')
If the legacy metadata APIs are already disabled, print a message indicating that they are already disabled:
Copy
Ask AI
print('Legacy Compute Engine Instance Metadata APIs are already disabled.')
Note: Replace YOUR_PROJECT_ID and YOUR_INSTANCE_NAME with your actual project ID and instance name respectively. Also, replace the zone variable with the appropriate zone for your instance.