我目前正在开发一个脚本,它将从GCP上的安全指挥中心获得所有发现。
我在使用为我创建的服务帐户时遇到了麻烦。服务帐户是在项目X上创建的,但具有组织查看和列出发现的权限。
这就是我所带来的(来自gcloud python库的想法):
from google.cloud import securitycenter
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file('svc-scc.json')
# Create a client.
client = securitycenter.SecurityCenterClient(credentials=credentials)
# organization_id is the numeric ID of the organization. e.g.:
organization_id = "XXXXXXXXX"
org_name = "organizations/{org_id}".format(org_id=organization_id)
# The "sources/-" suffix lists findings across all sources. You
# also use a specific source_name instead.
all_sources = "{org_name}/sources/-".format(org_name=org_name)
finding_result_iterator = client.list_findings(all_sources)
for i, finding_result in enumerate(finding_result_iterator):
print("{}: name: {} resource: {}".format(i, finding_result.finding.name, finding_result.finding.resource_name))svc-scc.json是从GCP上的IAM检索凭据的json文件:
{
"type": "service_account",
"project_id": "Project X",
"private_key_id": "XXXXXXXXXXXXXXXXXXXXXXX",
"private_key": "-----BEGIN PRIVATE KEY-----
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
---END PRIVATE KEY-----\n",
"client_email": "svc-scc@xxxxxxxxxxxx.iam.gserviceaccount.com",
"client_id": "XXXXXXXXXXXXXX",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/svc-scc%40xxxxxxxxxxx.iam.gserviceaccount.com"
} 这是通过Terraform对此服务帐户的权限:
resource "google_organization_iam_member" "securitycenter-org-permissions" {
for_each = toset(["securitycenter.assetsViewer", "securitycenter.findingsViewer"])
org_id = var.org_id
role = "roles/${each.value}"
member = "serviceAccount:${module.service_accounts.service_account["svc-scc"].email}"
}我发现了一个错误:
google.api_core.exceptions.PermissionDenied: 403 Security Command Center API has not been used in project X before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/securitycenter.googleapis.com/overview?project=X then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.为项目X启用securitycenter API的不是我们的最佳选择。
代码中是否有一种方法将组织指定为API调用的默认项目?
如果没有,我是否需要更改服务帐户?
谢谢你抽出时间!
发布于 2020-06-30 09:36:01
因此,按照您的建议,我提出了如下建议:我们已经在安全项目中创建了服务帐户,但是组织权限是在IAM项目上设置的(问题中的项目X)。由于Security启用了API,所以当我想从组织获得所有发现时,脚本将正常工作。
谢谢你们的帮助。
发布于 2020-06-26 15:45:24
当您使用客户端库时,这些库在幕后对您使用的产品进行API调用,并且调用是通过与服务帐户相关联的项目进行的,因此在运行代码时必须在项目中使用API。
如果您不想激活项目X的securitycenter API,但您可能希望使用已经激活了securitycenter API的项目Y,则需要向项目Y中的服务帐户(svc-scc@xxxxxxxxxxxx.iam.gserviceaccount.com)授予权限,然后在创建credentials时需要设置将要使用的项目。
credentials = service_account.Credentials.from_service_account_file('svc-scc.json', project_id='PROJECT-Y')https://stackoverflow.com/questions/62596981
复制相似问题